From 05e2c7eb880e5addc2d3d3030e7649751b1cf36f Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 1 May 2025 16:18:03 +0100 Subject: [PATCH 01/19] Ignore melange.dev folder --- .gitignore | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.gitignore b/.gitignore index fffea0075..513eac863 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,5 @@ docs/public/api/ml docs/public/api/re docs/api/ml docs/api/re + +melange.dev/* From 0e3731602b7582007f698bf97375691420496f96 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 1 May 2025 16:18:41 +0100 Subject: [PATCH 02/19] Allow to pull docs from opam source melange --- Makefile | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Makefile b/Makefile index 8603eb85c..0981c53d6 100644 --- a/Makefile +++ b/Makefile @@ -82,3 +82,17 @@ dev: ## Start docs dev server .PHONY: preview preview: ## Preview the docs yarn vitepress preview docs + +.PHONY: pull-melange-docs +pull-melange-docs: ## Pull melange docs + if [ ! -d "melange.dev" ]; then \ + opam source melange; \ + fi + cd melange.dev + dune build @docs + cd .. + odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/stdlib.odocl + odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/js.odocl + odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/belt.odocl + odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/dom.odocl + odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/node.odocl From d02eeaac3775fe0b0b4944b248f0b31654671c6d Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 1 May 2025 16:20:09 +0100 Subject: [PATCH 03/19] Commit markdown generated files from odoc --- docs/api/melange/Belt-Array.md | 564 ++++++++ docs/api/melange/Belt-Float.md | 26 + docs/api/melange/Belt-HashMap-Int.md | 75 + docs/api/melange/Belt-HashMap-String.md | 75 + docs/api/melange/Belt-HashMap.md | 143 ++ docs/api/melange/Belt-HashSet-Int.md | 62 + docs/api/melange/Belt-HashSet-String.md | 62 + docs/api/melange/Belt-HashSet.md | 107 ++ .../Belt-Id-MakeComparable-argument-1-M.md | 7 + docs/api/melange/Belt-Id-MakeComparable.md | 15 + .../Belt-Id-MakeComparableU-argument-1-M.md | 7 + docs/api/melange/Belt-Id-MakeComparableU.md | 15 + .../Belt-Id-MakeHashable-argument-1-M.md | 10 + docs/api/melange/Belt-Id-MakeHashable.md | 18 + .../Belt-Id-MakeHashableU-argument-1-M.md | 10 + docs/api/melange/Belt-Id-MakeHashableU.md | 18 + .../melange/Belt-Id-module-type-Comparable.md | 10 + .../melange/Belt-Id-module-type-Hashable.md | 13 + docs/api/melange/Belt-Id.md | 90 ++ docs/api/melange/Belt-Int.md | 26 + docs/api/melange/Belt-List.md | 594 ++++++++ docs/api/melange/Belt-Map-Dict.md | 262 ++++ docs/api/melange/Belt-Map-Int.md | 198 +++ docs/api/melange/Belt-Map-String.md | 198 +++ docs/api/melange/Belt-Map.md | 387 ++++++ docs/api/melange/Belt-MutableMap-Int.md | 151 ++ docs/api/melange/Belt-MutableMap-String.md | 151 ++ docs/api/melange/Belt-MutableMap.md | 187 +++ docs/api/melange/Belt-MutableQueue.md | 92 ++ docs/api/melange/Belt-MutableSet-Int.md | 149 ++ docs/api/melange/Belt-MutableSet-String.md | 149 ++ docs/api/melange/Belt-MutableSet.md | 171 +++ docs/api/melange/Belt-MutableStack.md | 54 + docs/api/melange/Belt-Option.md | 158 +++ docs/api/melange/Belt-Range.md | 46 + docs/api/melange/Belt-Result.md | 140 ++ docs/api/melange/Belt-Set-Dict.md | 181 +++ docs/api/melange/Belt-Set-Int.md | 143 ++ docs/api/melange/Belt-Set-String.md | 143 ++ docs/api/melange/Belt-Set.md | 316 +++++ docs/api/melange/Belt-SortArray-Int.md | 29 + docs/api/melange/Belt-SortArray-String.md | 29 + docs/api/melange/Belt-SortArray.md | 64 + docs/api/melange/Belt.md | 128 ++ docs/api/melange/Dom-Storage.md | 28 + docs/api/melange/Dom.md | 839 ++++++++++++ docs/api/melange/Js-Array.md | 170 +++ docs/api/melange/Js-Bigint.md | 59 + docs/api/melange/Js-Blob.md | 43 + docs/api/melange/Js-Console.md | 70 + docs/api/melange/Js-Date.md | 304 +++++ docs/api/melange/Js-Dict.md | 58 + docs/api/melange/Js-Exn.md | 70 + docs/api/melange/Js-File.md | 58 + docs/api/melange/Js-Float.md | 112 ++ docs/api/melange/Js-FormData.md | 75 + docs/api/melange/Js-Global.md | 130 ++ docs/api/melange/Js-Int.md | 62 + docs/api/melange/Js-Iterator.md | 22 + docs/api/melange/Js-Json.md | 242 ++++ docs/api/melange/Js-Map.md | 45 + docs/api/melange/Js-Math.md | 238 ++++ docs/api/melange/Js-Null.md | 61 + docs/api/melange/Js-Nullable.md | 64 + docs/api/melange/Js-Obj.md | 15 + docs/api/melange/Js-Promise.md | 53 + docs/api/melange/Js-Re.md | 146 ++ docs/api/melange/Js-Set.md | 39 + docs/api/melange/Js-String.md | 403 ++++++ .../api/melange/Js-Typed_array-ArrayBuffer.md | 16 + docs/api/melange/Js-Typed_array-DataView.md | 105 ++ .../melange/Js-Typed_array-Float32Array.md | 161 +++ .../melange/Js-Typed_array-Float64Array.md | 161 +++ docs/api/melange/Js-Typed_array-Int16Array.md | 161 +++ docs/api/melange/Js-Typed_array-Int32Array.md | 161 +++ docs/api/melange/Js-Typed_array-Int8Array.md | 161 +++ .../api/melange/Js-Typed_array-Uint16Array.md | 161 +++ .../api/melange/Js-Typed_array-Uint32Array.md | 161 +++ docs/api/melange/Js-Typed_array-Uint8Array.md | 161 +++ .../Js-Typed_array-Uint8ClampedArray.md | 161 +++ docs/api/melange/Js-Typed_array.md | 39 + docs/api/melange/Js-Types.md | 102 ++ docs/api/melange/Js-Undefined.md | 65 + docs/api/melange/Js-WeakMap.md | 21 + docs/api/melange/Js-WeakSet.md | 18 + docs/api/melange/Js.md | 266 ++++ docs/api/melange/Node-Buffer.md | 53 + docs/api/melange/Node-Child_process.md | 27 + docs/api/melange/Node-Fs-Watch.md | 30 + docs/api/melange/Node-Fs.md | 105 ++ docs/api/melange/Node-Module.md | 5 + docs/api/melange/Node-Path.md | 53 + docs/api/melange/Node-Process.md | 35 + docs/api/melange/Node.md | 66 + docs/api/melange/Stdlib-Arg.md | 215 +++ docs/api/melange/Stdlib-Array.md | 284 ++++ docs/api/melange/Stdlib-ArrayLabels.md | 294 ++++ docs/api/melange/Stdlib-Atomic.md | 118 ++ docs/api/melange/Stdlib-Bool.md | 62 + docs/api/melange/Stdlib-Buffer.md | 222 +++ docs/api/melange/Stdlib-Bytes.md | 527 +++++++ docs/api/melange/Stdlib-BytesLabels.md | 539 ++++++++ docs/api/melange/Stdlib-Char.md | 48 + docs/api/melange/Stdlib-Complex.md | 84 ++ docs/api/melange/Stdlib-Digest-BLAKE128.md | 61 + docs/api/melange/Stdlib-Digest-BLAKE256.md | 61 + docs/api/melange/Stdlib-Digest-BLAKE512.md | 61 + docs/api/melange/Stdlib-Digest-MD5.md | 61 + .../melange/Stdlib-Digest-module-type-S.md | 61 + docs/api/melange/Stdlib-Digest.md | 91 ++ docs/api/melange/Stdlib-Domain-DLS.md | 35 + docs/api/melange/Stdlib-Domain.md | 70 + docs/api/melange/Stdlib-Dynarray.md | 447 ++++++ docs/api/melange/Stdlib-Either.md | 94 ++ docs/api/melange/Stdlib-Filename.md | 132 ++ docs/api/melange/Stdlib-Float-Array.md | 247 ++++ docs/api/melange/Stdlib-Float.md | 388 ++++++ docs/api/melange/Stdlib-Format.md | 1100 +++++++++++++++ docs/api/melange/Stdlib-Fun.md | 36 + docs/api/melange/Stdlib-Gc-Memprof.md | 84 ++ docs/api/melange/Stdlib-Gc.md | 222 +++ .../Stdlib-Hashtbl-Make-argument-1-H.md | 16 + docs/api/melange/Stdlib-Hashtbl-Make.md | 89 ++ .../Stdlib-Hashtbl-MakeSeeded-argument-1-H.md | 13 + docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md | 88 ++ .../Stdlib-Hashtbl-module-type-HashedType.md | 17 + .../melange/Stdlib-Hashtbl-module-type-S.md | 84 ++ ...ib-Hashtbl-module-type-SeededHashedType.md | 15 + .../Stdlib-Hashtbl-module-type-SeededS.md | 83 ++ docs/api/melange/Stdlib-Hashtbl.md | 301 ++++ docs/api/melange/Stdlib-In_channel.md | 176 +++ docs/api/melange/Stdlib-Int.md | 135 ++ docs/api/melange/Stdlib-Int32.md | 188 +++ docs/api/melange/Stdlib-Int64.md | 204 +++ docs/api/melange/Stdlib-LargeFile.md | 20 + docs/api/melange/Stdlib-Lazy.md | 66 + docs/api/melange/Stdlib-Lexing.md | 104 ++ docs/api/melange/Stdlib-List.md | 377 +++++ docs/api/melange/Stdlib-ListLabels.md | 377 +++++ .../melange/Stdlib-Map-Make-argument-1-Ord.md | 9 + docs/api/melange/Stdlib-Map-Make.md | 246 ++++ .../Stdlib-Map-module-type-OrderedType.md | 10 + docs/api/melange/Stdlib-Map-module-type-S.md | 241 ++++ docs/api/melange/Stdlib-Map.md | 31 + docs/api/melange/Stdlib-Marshal.md | 78 ++ ...ib-MoreLabels-Hashtbl-Make-argument-1-H.md | 16 + .../melange/Stdlib-MoreLabels-Hashtbl-Make.md | 89 ++ ...eLabels-Hashtbl-MakeSeeded-argument-1-H.md | 13 + .../Stdlib-MoreLabels-Hashtbl-MakeSeeded.md | 88 ++ ...reLabels-Hashtbl-module-type-HashedType.md | 17 + ...Stdlib-MoreLabels-Hashtbl-module-type-S.md | 84 ++ ...ls-Hashtbl-module-type-SeededHashedType.md | 15 + ...-MoreLabels-Hashtbl-module-type-SeededS.md | 83 ++ docs/api/melange/Stdlib-MoreLabels-Hashtbl.md | 312 +++++ ...dlib-MoreLabels-Map-Make-argument-1-Ord.md | 9 + .../api/melange/Stdlib-MoreLabels-Map-Make.md | 246 ++++ ...-MoreLabels-Map-module-type-OrderedType.md | 10 + .../Stdlib-MoreLabels-Map-module-type-S.md | 241 ++++ docs/api/melange/Stdlib-MoreLabels-Map.md | 33 + ...dlib-MoreLabels-Set-Make-argument-1-Ord.md | 9 + .../api/melange/Stdlib-MoreLabels-Set-Make.md | 225 +++ ...-MoreLabels-Set-module-type-OrderedType.md | 10 + .../Stdlib-MoreLabels-Set-module-type-S.md | 220 +++ docs/api/melange/Stdlib-MoreLabels-Set.md | 33 + docs/api/melange/Stdlib-MoreLabels.md | 22 + docs/api/melange/Stdlib-Mutex.md | 38 + docs/api/melange/Stdlib-Obj-Ephemeron.md | 58 + .../Stdlib-Obj-Extension_constructor.md | 13 + docs/api/melange/Stdlib-Obj.md | 130 ++ docs/api/melange/Stdlib-Oo.md | 11 + docs/api/melange/Stdlib-Option.md | 85 ++ docs/api/melange/Stdlib-Out_channel.md | 177 +++ docs/api/melange/Stdlib-Parsing.md | 47 + docs/api/melange/Stdlib-Printexc-Slot.md | 35 + docs/api/melange/Stdlib-Printexc.md | 216 +++ docs/api/melange/Stdlib-Printf.md | 117 ++ docs/api/melange/Stdlib-Queue.md | 187 +++ docs/api/melange/Stdlib-Random-State.md | 44 + docs/api/melange/Stdlib-Random.md | 77 ++ docs/api/melange/Stdlib-Result.md | 108 ++ docs/api/melange/Stdlib-Scanf-Scanning.md | 73 + docs/api/melange/Stdlib-Scanf.md | 191 +++ docs/api/melange/Stdlib-Seq.md | 438 ++++++ .../melange/Stdlib-Set-Make-argument-1-Ord.md | 9 + docs/api/melange/Stdlib-Set-Make.md | 225 +++ .../Stdlib-Set-module-type-OrderedType.md | 10 + docs/api/melange/Stdlib-Set-module-type-S.md | 220 +++ docs/api/melange/Stdlib-Set.md | 31 + docs/api/melange/Stdlib-Stack.md | 85 ++ docs/api/melange/Stdlib-StdLabels.md | 22 + docs/api/melange/Stdlib-String.md | 369 +++++ docs/api/melange/Stdlib-StringLabels.md | 375 +++++ ...s-Immediate64-Make-argument-1-Immediate.md | 4 + ...mediate64-Make-argument-2-Non_immediate.md | 4 + .../melange/Stdlib-Sys-Immediate64-Make.md | 27 + ...b-Sys-Immediate64-module-type-Immediate.md | 4 + ...s-Immediate64-module-type-Non_immediate.md | 4 + docs/api/melange/Stdlib-Sys-Immediate64.md | 15 + docs/api/melange/Stdlib-Sys.md | 391 ++++++ docs/api/melange/Stdlib-Type-Id.md | 66 + docs/api/melange/Stdlib-Type.md | 25 + docs/api/melange/Stdlib-Uchar.md | 114 ++ docs/api/melange/Stdlib-Unit.md | 27 + .../melange/Stdlib-Weak-Make-argument-1-H.md | 16 + docs/api/melange/Stdlib-Weak-Make.md | 69 + docs/api/melange/Stdlib-Weak-module-type-S.md | 64 + docs/api/melange/Stdlib-Weak.md | 64 + docs/api/melange/Stdlib.md | 1216 +++++++++++++++++ 208 files changed, 27222 insertions(+) create mode 100644 docs/api/melange/Belt-Array.md create mode 100644 docs/api/melange/Belt-Float.md create mode 100644 docs/api/melange/Belt-HashMap-Int.md create mode 100644 docs/api/melange/Belt-HashMap-String.md create mode 100644 docs/api/melange/Belt-HashMap.md create mode 100644 docs/api/melange/Belt-HashSet-Int.md create mode 100644 docs/api/melange/Belt-HashSet-String.md create mode 100644 docs/api/melange/Belt-HashSet.md create mode 100644 docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md create mode 100644 docs/api/melange/Belt-Id-MakeComparable.md create mode 100644 docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md create mode 100644 docs/api/melange/Belt-Id-MakeComparableU.md create mode 100644 docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md create mode 100644 docs/api/melange/Belt-Id-MakeHashable.md create mode 100644 docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md create mode 100644 docs/api/melange/Belt-Id-MakeHashableU.md create mode 100644 docs/api/melange/Belt-Id-module-type-Comparable.md create mode 100644 docs/api/melange/Belt-Id-module-type-Hashable.md create mode 100644 docs/api/melange/Belt-Id.md create mode 100644 docs/api/melange/Belt-Int.md create mode 100644 docs/api/melange/Belt-List.md create mode 100644 docs/api/melange/Belt-Map-Dict.md create mode 100644 docs/api/melange/Belt-Map-Int.md create mode 100644 docs/api/melange/Belt-Map-String.md create mode 100644 docs/api/melange/Belt-Map.md create mode 100644 docs/api/melange/Belt-MutableMap-Int.md create mode 100644 docs/api/melange/Belt-MutableMap-String.md create mode 100644 docs/api/melange/Belt-MutableMap.md create mode 100644 docs/api/melange/Belt-MutableQueue.md create mode 100644 docs/api/melange/Belt-MutableSet-Int.md create mode 100644 docs/api/melange/Belt-MutableSet-String.md create mode 100644 docs/api/melange/Belt-MutableSet.md create mode 100644 docs/api/melange/Belt-MutableStack.md create mode 100644 docs/api/melange/Belt-Option.md create mode 100644 docs/api/melange/Belt-Range.md create mode 100644 docs/api/melange/Belt-Result.md create mode 100644 docs/api/melange/Belt-Set-Dict.md create mode 100644 docs/api/melange/Belt-Set-Int.md create mode 100644 docs/api/melange/Belt-Set-String.md create mode 100644 docs/api/melange/Belt-Set.md create mode 100644 docs/api/melange/Belt-SortArray-Int.md create mode 100644 docs/api/melange/Belt-SortArray-String.md create mode 100644 docs/api/melange/Belt-SortArray.md create mode 100644 docs/api/melange/Belt.md create mode 100644 docs/api/melange/Dom-Storage.md create mode 100644 docs/api/melange/Dom.md create mode 100644 docs/api/melange/Js-Array.md create mode 100644 docs/api/melange/Js-Bigint.md create mode 100644 docs/api/melange/Js-Blob.md create mode 100644 docs/api/melange/Js-Console.md create mode 100644 docs/api/melange/Js-Date.md create mode 100644 docs/api/melange/Js-Dict.md create mode 100644 docs/api/melange/Js-Exn.md create mode 100644 docs/api/melange/Js-File.md create mode 100644 docs/api/melange/Js-Float.md create mode 100644 docs/api/melange/Js-FormData.md create mode 100644 docs/api/melange/Js-Global.md create mode 100644 docs/api/melange/Js-Int.md create mode 100644 docs/api/melange/Js-Iterator.md create mode 100644 docs/api/melange/Js-Json.md create mode 100644 docs/api/melange/Js-Map.md create mode 100644 docs/api/melange/Js-Math.md create mode 100644 docs/api/melange/Js-Null.md create mode 100644 docs/api/melange/Js-Nullable.md create mode 100644 docs/api/melange/Js-Obj.md create mode 100644 docs/api/melange/Js-Promise.md create mode 100644 docs/api/melange/Js-Re.md create mode 100644 docs/api/melange/Js-Set.md create mode 100644 docs/api/melange/Js-String.md create mode 100644 docs/api/melange/Js-Typed_array-ArrayBuffer.md create mode 100644 docs/api/melange/Js-Typed_array-DataView.md create mode 100644 docs/api/melange/Js-Typed_array-Float32Array.md create mode 100644 docs/api/melange/Js-Typed_array-Float64Array.md create mode 100644 docs/api/melange/Js-Typed_array-Int16Array.md create mode 100644 docs/api/melange/Js-Typed_array-Int32Array.md create mode 100644 docs/api/melange/Js-Typed_array-Int8Array.md create mode 100644 docs/api/melange/Js-Typed_array-Uint16Array.md create mode 100644 docs/api/melange/Js-Typed_array-Uint32Array.md create mode 100644 docs/api/melange/Js-Typed_array-Uint8Array.md create mode 100644 docs/api/melange/Js-Typed_array-Uint8ClampedArray.md create mode 100644 docs/api/melange/Js-Typed_array.md create mode 100644 docs/api/melange/Js-Types.md create mode 100644 docs/api/melange/Js-Undefined.md create mode 100644 docs/api/melange/Js-WeakMap.md create mode 100644 docs/api/melange/Js-WeakSet.md create mode 100644 docs/api/melange/Js.md create mode 100644 docs/api/melange/Node-Buffer.md create mode 100644 docs/api/melange/Node-Child_process.md create mode 100644 docs/api/melange/Node-Fs-Watch.md create mode 100644 docs/api/melange/Node-Fs.md create mode 100644 docs/api/melange/Node-Module.md create mode 100644 docs/api/melange/Node-Path.md create mode 100644 docs/api/melange/Node-Process.md create mode 100644 docs/api/melange/Node.md create mode 100644 docs/api/melange/Stdlib-Arg.md create mode 100644 docs/api/melange/Stdlib-Array.md create mode 100644 docs/api/melange/Stdlib-ArrayLabels.md create mode 100644 docs/api/melange/Stdlib-Atomic.md create mode 100644 docs/api/melange/Stdlib-Bool.md create mode 100644 docs/api/melange/Stdlib-Buffer.md create mode 100644 docs/api/melange/Stdlib-Bytes.md create mode 100644 docs/api/melange/Stdlib-BytesLabels.md create mode 100644 docs/api/melange/Stdlib-Char.md create mode 100644 docs/api/melange/Stdlib-Complex.md create mode 100644 docs/api/melange/Stdlib-Digest-BLAKE128.md create mode 100644 docs/api/melange/Stdlib-Digest-BLAKE256.md create mode 100644 docs/api/melange/Stdlib-Digest-BLAKE512.md create mode 100644 docs/api/melange/Stdlib-Digest-MD5.md create mode 100644 docs/api/melange/Stdlib-Digest-module-type-S.md create mode 100644 docs/api/melange/Stdlib-Digest.md create mode 100644 docs/api/melange/Stdlib-Domain-DLS.md create mode 100644 docs/api/melange/Stdlib-Domain.md create mode 100644 docs/api/melange/Stdlib-Dynarray.md create mode 100644 docs/api/melange/Stdlib-Either.md create mode 100644 docs/api/melange/Stdlib-Filename.md create mode 100644 docs/api/melange/Stdlib-Float-Array.md create mode 100644 docs/api/melange/Stdlib-Float.md create mode 100644 docs/api/melange/Stdlib-Format.md create mode 100644 docs/api/melange/Stdlib-Fun.md create mode 100644 docs/api/melange/Stdlib-Gc-Memprof.md create mode 100644 docs/api/melange/Stdlib-Gc.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-Make.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-module-type-S.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md create mode 100644 docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md create mode 100644 docs/api/melange/Stdlib-Hashtbl.md create mode 100644 docs/api/melange/Stdlib-In_channel.md create mode 100644 docs/api/melange/Stdlib-Int.md create mode 100644 docs/api/melange/Stdlib-Int32.md create mode 100644 docs/api/melange/Stdlib-Int64.md create mode 100644 docs/api/melange/Stdlib-LargeFile.md create mode 100644 docs/api/melange/Stdlib-Lazy.md create mode 100644 docs/api/melange/Stdlib-Lexing.md create mode 100644 docs/api/melange/Stdlib-List.md create mode 100644 docs/api/melange/Stdlib-ListLabels.md create mode 100644 docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md create mode 100644 docs/api/melange/Stdlib-Map-Make.md create mode 100644 docs/api/melange/Stdlib-Map-module-type-OrderedType.md create mode 100644 docs/api/melange/Stdlib-Map-module-type-S.md create mode 100644 docs/api/melange/Stdlib-Map.md create mode 100644 docs/api/melange/Stdlib-Marshal.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Hashtbl.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Map-Make.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Map.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Set-Make.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md create mode 100644 docs/api/melange/Stdlib-MoreLabels-Set.md create mode 100644 docs/api/melange/Stdlib-MoreLabels.md create mode 100644 docs/api/melange/Stdlib-Mutex.md create mode 100644 docs/api/melange/Stdlib-Obj-Ephemeron.md create mode 100644 docs/api/melange/Stdlib-Obj-Extension_constructor.md create mode 100644 docs/api/melange/Stdlib-Obj.md create mode 100644 docs/api/melange/Stdlib-Oo.md create mode 100644 docs/api/melange/Stdlib-Option.md create mode 100644 docs/api/melange/Stdlib-Out_channel.md create mode 100644 docs/api/melange/Stdlib-Parsing.md create mode 100644 docs/api/melange/Stdlib-Printexc-Slot.md create mode 100644 docs/api/melange/Stdlib-Printexc.md create mode 100644 docs/api/melange/Stdlib-Printf.md create mode 100644 docs/api/melange/Stdlib-Queue.md create mode 100644 docs/api/melange/Stdlib-Random-State.md create mode 100644 docs/api/melange/Stdlib-Random.md create mode 100644 docs/api/melange/Stdlib-Result.md create mode 100644 docs/api/melange/Stdlib-Scanf-Scanning.md create mode 100644 docs/api/melange/Stdlib-Scanf.md create mode 100644 docs/api/melange/Stdlib-Seq.md create mode 100644 docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md create mode 100644 docs/api/melange/Stdlib-Set-Make.md create mode 100644 docs/api/melange/Stdlib-Set-module-type-OrderedType.md create mode 100644 docs/api/melange/Stdlib-Set-module-type-S.md create mode 100644 docs/api/melange/Stdlib-Set.md create mode 100644 docs/api/melange/Stdlib-Stack.md create mode 100644 docs/api/melange/Stdlib-StdLabels.md create mode 100644 docs/api/melange/Stdlib-String.md create mode 100644 docs/api/melange/Stdlib-StringLabels.md create mode 100644 docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md create mode 100644 docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md create mode 100644 docs/api/melange/Stdlib-Sys-Immediate64-Make.md create mode 100644 docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md create mode 100644 docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md create mode 100644 docs/api/melange/Stdlib-Sys-Immediate64.md create mode 100644 docs/api/melange/Stdlib-Sys.md create mode 100644 docs/api/melange/Stdlib-Type-Id.md create mode 100644 docs/api/melange/Stdlib-Type.md create mode 100644 docs/api/melange/Stdlib-Uchar.md create mode 100644 docs/api/melange/Stdlib-Unit.md create mode 100644 docs/api/melange/Stdlib-Weak-Make-argument-1-H.md create mode 100644 docs/api/melange/Stdlib-Weak-Make.md create mode 100644 docs/api/melange/Stdlib-Weak-module-type-S.md create mode 100644 docs/api/melange/Stdlib-Weak.md create mode 100644 docs/api/melange/Stdlib.md diff --git a/docs/api/melange/Belt-Array.md b/docs/api/melange/Belt-Array.md new file mode 100644 index 000000000..dc66f4fd3 --- /dev/null +++ b/docs/api/melange/Belt-Array.md @@ -0,0 +1,564 @@ +# Module `Belt.Array` +[`Belt.Array`](#) +**mutable array**: Utilities functions +[`Belt.Array`](#) Utililites for Array functions +``` +type 'a t = 'a array +``` +``` +val length : 'a t -> int +``` +`length xs` return the size of the array +``` +val size : 'a t -> int +``` +**See** [`length`](./#val-length) +``` +val get : 'a t -> int -> 'a option +``` +`get arr i` +If `i <= 0 <= length arr`;returns `Some value` where `value` is the item at index `i` If `i` is out of range;returns `None` +```ocaml + Belt.Array.get [|"a";"b";"c"|] 0 = Some "a";; + Belt.Array.get [|"a";"b";"c"|] 3 = None;; + Belt.Array.get [|"a";"b";"c"|] (-1) = None;; +``` +``` +val getExn : 'a t -> int -> 'a +``` +`getExn arr i` +**raise** an exception if `i` is out of range;otherwise return the value at index `i` in `arr` +``` +val getUnsafe : 'a t -> int -> 'a +``` +`getUnsafe arr i` +**Unsafe** +no bounds checking;this would cause type error if `i` does not stay within range +``` +val getUndefined : 'a t -> int -> 'a Js.undefined +``` +`getUndefined arr i` +It does the samething in the runtime as [`getUnsafe`](./#val-getUnsafe); it is *type safe* since the return type still track whether it is in range or not +``` +val set : 'a t -> int -> 'a -> bool +``` +`set arr n x` modifies `arr` in place; it replaces the nth element of `arr` with `x` +returns false means not updated due to out of range +``` +val setExn : 'a t -> int -> 'a -> unit +``` +`setExn arr i x` **raise** an exception if `i` is out of range +``` +val setUnsafe : 'a t -> int -> 'a -> unit +``` +``` +val shuffleInPlace : 'a t -> unit +``` +`shuffleInPlace arr` randomly re-orders the items in `arr` +``` +val shuffle : 'a t -> 'a t +``` +`shuffle xs` +returns a fresh array with items in original array randomly shuffled +``` +val reverseInPlace : 'a t -> unit +``` +`reverseInPlace arr` reverses items in `arr` in place +```ocaml + let arr = [|10;11;12;13;14|];; + let () = reverseInPlace arr;; + arr = [|14;13;12;11;10|];; +``` +``` +val reverse : 'a t -> 'a t +``` +`reverse arr` +returns a fresh array with items in arr in reverse order +```ocaml + reverse [|10;11;12;13;14|] = [|14;13;12;11;10|];; +``` +``` +val makeUninitialized : int -> 'a Js.undefined array +``` +`makeUninitialized n` creates an array of length `n` filled with the undefined value. You must specify the type of data that will eventually fill the array. +```ocaml + let arr: string Js.undefined array = makeUninitialized 5;; + getExn arr 0 = Js.undefined;; +``` +``` +val makeUninitializedUnsafe : int -> 'a t +``` +\`makeUninitializedUnsafe n\` +**Unsafe** +```ocaml +let arr = Belt.Array.makeUninitializedUnsafe 5;; +let () = Js.log(Belt.Array.getExn arr 0);; (* undefined *) +Belt.Array.setExn arr 0 "example";; +let () = Js.log(Belt.Array.getExn arr 0 = "example");; +``` +``` +val make : int -> 'a -> 'a t +``` +`make n e` return an array of size `n` filled with value `e` +returns an empty array when n is negative. +``` +val range : int -> int -> int t +``` +`range start finish` create an inclusive array +```ocaml + range 0 3 = [|0;1;2;3|];; + range 3 0 = [||] ;; + range 3 3 = [|3|];; +``` +``` +val rangeBy : int -> int -> step:int -> int t +``` +`rangeBy start finish ~step` +returns empty array when step is 0 or negative it also return empty array when start \> finish +```ocaml + rangeBy 0 10 ~step:3 = [|0;3;6;9|];; + rangeBy 0 12 ~step:3 = [|0;3;6;9;12|];; + rangeBy 33 0 ~step:1 = [||];; + rangeBy 33 0 ~step:(-1) = [||];; + rangeBy 3 12 ~step:(-1) = [||];; + rangeBy 3 3 ~step:0 = [||] ;; + rangeBy 3 3 ~step:(1) = [|3|] ;; +``` +``` +val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val makeBy : int -> (int -> 'a) -> 'a t +``` +`makeBy n f` +return an empty array when `n` is negative return an array of size `n` populated by `f i` start from `0` to `n - 1` +```ocaml + makeBy 5 (fun i -> i) = [|0;1;2;3;4|];; + makeBy 5 (fun i -> i * i) = [|0;1;4;9;16|] +``` +``` +val makeByAndShuffleU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val makeByAndShuffle : int -> (int -> 'a) -> 'a t +``` +`makeByAndShuffle n f` +Equivalent to `shuffle (makeBy n f)` +``` +val zip : 'a t -> 'b array -> ('a * 'b) array +``` +`zip a b` +Create an array of pairs from corresponding elements of `a` and `b`. Stop with the shorter array +```ocaml + zip [|1;2|] [|3;4;5|] = [|(1, 3);(2, 4)|] +``` +``` +val zipByU : 'a t -> 'b array -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c array +``` +``` +val zipBy : 'a t -> 'b array -> ('a -> 'b -> 'c) -> 'c array +``` +`zipBy xs ys f` +Create an array by applying `f` to corresponding elements of `xs` and `ys` Stops with shorter array +Equivalent to `map (zip xs ys) (fun (a,b) -> f a b) ` +```ocaml + zipBy [|1;2;3|] [|4;5|] (fun a b -> 2 * a + b) = [|6;9|];; +``` +``` +val unzip : ('a * 'b) array -> 'a t * 'b array +``` +`unzip a` takes an array of pairs and creates a pair of arrays. The first array contains all the first items of the pairs; the second array contains all the second items. +```ocaml + unzip [|(1,2) ; (3,4)|] = ([|1;3|], [|2;4|]);; + unzip [|(1,2) ; (3,4) ; (5,6) ; (7,8)|] = ([|1;3;5;7|], [|2;4;6;8|]);; +``` +``` +val concat : 'a t -> 'a t -> 'a t +``` +`concat xs ys` +returns a fresh array containing the concatenation of the arrays v1 and v2;so even if v1 or v2 is empty;it can not be shared +```ocaml + concat [|1;2;3|] [|4;5|] = [|1;2;3;4;5|];; + concat [| |] [|"a";"b";"c"|] = [|"a";"b";"c"|];; +``` +``` +val concatMany : 'a t t -> 'a t +``` +`concatMany xss` +returns a fresh array as the concatenation of xss (an array of arrays) +```ocaml + concatMany [| [|1;2;3|]; [|4;5;6|]; [|7;8|] |] = [|1;2;3;4;5;6;7;8|];; +``` +``` +val slice : 'a t -> offset:int -> len:int -> 'a t +``` +`slice xs offset len` creates a new array with the `len` elements of `xs` starting at `offset` for +`offset` can be negative;and is evaluated as `length xs - offset` `slice xs -1 1` means get the last element as a singleton array +`slice xs (-len) len` will return a copy of the array +if the array does not have enough data;`slice` extracts through the end of sequence. +if `len` is negative;returns the empty array. +```ocaml + slice [|10;11;12;13;14;15;16|] ~offset: 2 ~len: 3 = [|12;13;14|];; + slice [|10;11;12;13;14;15;16|] ~offset: (-4) ~len: 3 = [|13;14;15|];; + slice [|10;11;12;13;14;15;16|] ~offset:4 ~len:9 = [|14;15;16|];; +``` +``` +val sliceToEnd : 'a t -> int -> 'a t +``` +`sliceToEnd xs offset` creates a new array with the elements of `xs` starting at `offset` +`offset` can be negative;and is evaluated as `length xs - offset` `sliceToEnd xs -1` means get the last element as a singleton array +`sliceToEnd xs 0` will return a copy of the array +```ocaml + sliceToEnd [|10;11;12;13;14;15;16|] 2 = [|12;13;14;15;16|];; + sliceToEnd [|10;11;12;13;14;15;16|] (-4) = [|13;14;15;16|];; +``` +``` +val copy : 'a t -> 'a t +``` +`copy a` +returns a copy of a;that is;a fresh array containing the same elements as a. +``` +val fill : 'a t -> offset:int -> len:int -> 'a -> unit +``` +`fill arr ~offset ~len x` +Modifies `arr` in place, storing `x` in elements number `offset` to `offset + len - 1`. +`offset` can be negative;and is evaluated as `length arr - offset` +`fill arr ~offset:(-1) ~len:1` means fill the last element, if the array does not have enough data;`fill` will ignore it +```ocaml + + let arr = makeBy 5 (fun i -> i) ;; + fill arr ~offset:2 ~len:2 9 ;; + arr = [|0;1;9;9;4|];; + fill arr ~offset:7 ~len:2 8;; + arr = [|0;1;9;9;4|];; +``` +``` +val blit : + src:'a t -> + srcOffset:int -> + dst:'a t -> + dstOffset:int -> + len:int -> + unit +``` +`blit ~src:v1 ~srcOffset:o1 ~dst:v2 ~dstOffset:o2 ~len` +copies `len` elements from array `v1`;starting at element number `o1`;to array `v2`, starting at element number `o2`. +It works correctly even if `v1` and `v2` are the same array;and the source and destination chunks overlap. +`offset` can be negative;`-1` means `len - 1`;if `len + offset` is still negative;it will be set as 0 +For each of the examples;presume that `v1 = [|10;11;12;13;14;15;16;17|]` and `v2 = [|20;21;22;23;24;25;26;27|]`. The result shown is the content of the destination array. +```ocaml + Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v2 ~dstOffset: 2 ~len: 3 |. + [|20;21;14;15;16;25;26;27|] + Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v1 ~dstOffset: 2 ~len: 3 |. + [|10;11;14;15;16;15;16;17|] +``` +``` +val blitUnsafe : + src:'a t -> + srcOffset:int -> + dst:'a t -> + dstOffset:int -> + len:int -> + unit +``` +**Unsafe** blit without bounds checking +``` +val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> unit) -> unit +``` +`forEach xs f` +Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`;so no new array is created. Use `forEach` when you are primarily concerned with repetitively creating side effects. +```ocaml + forEach [|"a";"b";"c"|] (fun x -> Js.log("Item: " ^ x));; + (* prints: + Item: a + Item: b + Item: c + *) + + let total = ref 0;; + forEach [|1;2;3;4|] (fun x -> total := !total + x);; + !total = 1 + 2 + 3 + 4;; + +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b array +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b array +``` +`map xs f ` +returns a new array by calling f for each element of xs from the beginning to end +```ocaml + map [|1;2|] (fun x-> x + 10) = [|11;12|] +``` +``` +val flatMapU : 'a t -> ('a -> 'b t) Js.Fn.arity1 -> 'b t +``` +``` +val flatMap : 'a t -> ('a -> 'b t) -> 'b t +``` +`flatMap xs f` \*\*return\*\* a new array by calling \`f\` for each element of \`xs\` from the beginning to end, and then concatenating the results \``` flatMap `|1;2|` (fun x-\> `|x + 10;x + 20|`) \= `|11;21;12;22|` \``` +``` +val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option +``` +``` +val getBy : 'a t -> ('a -> bool) -> 'a option +``` +`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. +```ocaml + getBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 4 + getBy [|15;13;11|] (fun x -> x mod 2 = 0) = None +``` +``` +val getIndexByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> int option +``` +``` +val getIndexBy : 'a t -> ('a -> bool) -> int option +``` +`getIndexBy xs p` returns `Some index` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. +```ocaml + getIndexBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 1 + getIndexBy [|15;13;11|] (fun x -> x mod 2 = 0) = None +``` +``` +val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t +``` +``` +val keep : 'a t -> ('a -> bool) -> 'a t +``` +`keep xs p ` +returns a new array that keeps all elements satisfying p +```ocaml + keep [|1;2;3|] (fun x -> x mod 2 = 0) = [|2|] +``` +``` +val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t +``` +``` +val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t +``` +`keepWithIndex xs p ` +returns a new array that keeps all elements satisfying p. The predicate p takes two arguments: the element from xs and the index starting from 0. +```ocaml + keepWithIndex [|1;2;3|] (fun _x i -> i = 1) = [|2|] +``` +``` +val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b array +``` +``` +val keepMap : 'a t -> ('a -> 'b option) -> 'b array +``` +`keepMap xs p` +returns a new array that keeps all elements that return a non-None when applied to p +```ocaml + keepMap [|1;2;3|] (fun x -> if x mod 2 = 0 then Some x else None) + = [| 2 |] +``` +``` +val forEachWithIndexU : 'a t -> (int -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEachWithIndex : 'a t -> (int -> 'a -> unit) -> unit +``` +`forEachWithIndex xs f` +The same as [`forEach`](./#val-forEach); except that `f` is supplied with two arguments: the index starting from 0 and the element from `xs` +```ocaml + + forEachWithIndex [|"a";"b";"c"|] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; + (* prints: + Item 0 is a + Item 1 is b + Item 2 is c + *) + + let total = ref 0 ;; + forEachWithIndex [|10;11;12;13|] (fun i x -> total := !total + x + i);; + !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; +``` +``` +val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t +``` +`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. +```ocaml + mapWithIndex [|1;2;3|] (fun i x -> i + x) = + [|0 + 1; 1 + 2; 2 + 3|] +``` +``` +val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t +``` +``` +val partition : 'a t -> ('a -> bool) -> 'a t * 'a t +``` +`partition f a` split array into tuple of two arrays based on predicate f; first of tuple where predicate cause true, second where predicate cause false +```ocaml + partition [|1;2;3;4;5|] (fun x -> x mod 2 = 0 ) = ([|2;4|], [|1;2;3|]);; + partition [|1;2;3;4;5|] (fun x -> x mod 2 <> 0 ) = ([|1;2;3|], [|2;4|]);; +``` +``` +val reduceU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a +``` +`reduce xs init f` +Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”;which starts with a value of `init`. `reduce` returns the final value of the accumulator. +```ocaml + reduce [|2;3;4|] 1 (+) = 10;; + reduce [|"a";"b";"c";"d"|] "" (^) = "abcd";; +``` +``` +val reduceReverseU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduceReverse : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a +``` +`reduceReverse xs init f` +Works like [`reduce`](./#val-reduce);except that function `f` is applied to each item of `xs` from the last back to the first. +```ocaml + reduceReverse [|"a";"b";"c";"d"|] "" (^) = "dcba";; +``` +``` +val reduceReverse2U : + 'a t -> + 'b array -> + 'c -> + ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> + 'c +``` +``` +val reduceReverse2 : 'a t -> 'b array -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c +``` +`reduceReverse2 xs ys init f` Reduces two arrays `xs` and `ys`;taking items starting at `min (length xs) (length ys)` down to and including zero. +```ocaml + reduceReverse2 [|1;2;3|] [|1;2|] 0 (fun acc x y -> acc + x + y) = 6 +``` +``` +val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b +``` +`reduceWithIndex xs f` +Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the array and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. +```ocaml + reduceWithIndex [|1;2;3;4|] 0 (fun acc x i -> acc + x + i) = 16; +``` +``` +val joinWithU : 'a t -> string -> ('a -> string) Js.Fn.arity1 -> string +``` +``` +val joinWith : 'a t -> string -> ('a -> string) -> string +``` +`joinWith xs sep toString` +Concatenates all the elements of `xs` converted to string with `toString`, each separated by `sep`, the string given as the second argument, into a single string. If the array has only one element, then that element will be returned without using the separator. If the array is empty, the empty string will be returned. +```ocaml + joinWith [|0; 1|] ", " string_of_int = "0, 1" + joinWith [||] " " string_of_int = "" + joinWith [|1|] " " string_of_int = "1" +``` +``` +val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : 'a t -> ('a -> bool) -> bool +``` +`some xs p` +returns true if at least one of the elements in xs satifies p;where p is a predicate: a function taking an element and returning a bool. +```ocaml + some [|2; 3; 4|] (fun x -> x mod 2 = 1) = true;; + some [|-1; -3; -5|] (fun x -> x > 0) = false;; +``` +``` +val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : 'a t -> ('a -> bool) -> bool +``` +`every xs p` +returns true if all elements satisfy p;where p is a predicate: a function taking an element and returning a bool. +```ocaml + every [|1; 3; 5|] (fun x -> x mod 2 = 1) = true;; + every [|1; -3; 5|] (fun x -> x > 0) = false;; +``` +``` +val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`every2 xs ys p` returns true if `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) +```ocaml + every2 [|1;2;3|] [|0;1|] (>) = true;; + every2 [||] [|1|] (fun x y -> x > y) = true;; + every2 [|2;3|] [|1|] (fun x y -> x > y) = true;; + every2 [|0;1|] [|5;0|] (fun x y -> x > y) = false; +``` +``` +val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) +```ocaml + some2 [|0;2|] [|1;0;3|] (>) = true ;; + (some2 [||] [|1|] (fun x y -> x > y)) = false;; + (some2 [|2;3|] [|1;4|] (fun x y -> x > y)) = true;; +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +`cmp xs ys f` +- Compared by length if `length xs <> length ys`;returning \-1 if`length xs < length ys` or 1 if `length xs > length ys` +- Otherwise compare one by one `f x y`. `f` returns +- a negative number if `x` is “less than” `y` +- zero if `x` is “equal to” `y` +- a positive number if `x` is “greater than” `y` +- The comparison returns the first non-zero result of `f`;or zero if `f` returns zero for all `x` and `y`. +```ocaml + cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; + cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; + cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; +``` +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq xs ys` +- return false if length is not the same +- otherwise compare items one by one using `f xi yi`;and return true if all results are true;false otherwise +```ocaml + eq [|1; 2; 3|] [|-1; -2; -3|] (fun a b -> abs a = abs b) = true +``` +``` +val truncateToLengthUnsafe : 'a t -> int -> unit +``` +**Unsafe** `truncateToLengthUnsafe xs n` sets length of array `xs` to `n`. +If `n` is greater than the length of `xs`;the extra elements are set to `Js.Null_undefined.null` +If `n` is less than zero;raises a `RangeError`. +```ocaml + let arr = [|"ant";"bee";"cat";"dog";"elk"|];; + let () = truncateToLengthUnsafe arr 3;; + arr = [|"ant";"bee";"cat"|];; +``` +``` +val initU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val init : int -> (int -> 'a) -> 'a t +``` +``` +val push : 'a t -> 'a -> unit +``` +`arr->push(item)` push element \`item\` into the array \ No newline at end of file diff --git a/docs/api/melange/Belt-Float.md b/docs/api/melange/Belt-Float.md new file mode 100644 index 000000000..d062921e5 --- /dev/null +++ b/docs/api/melange/Belt-Float.md @@ -0,0 +1,26 @@ +# Module `Belt.Float` +[`Belt.Float`](#) Utililites for Float +``` +val toInt : float -> int +``` +``` +val fromInt : int -> float +``` +``` +val fromString : string -> float option +``` +``` +val toString : float -> string +``` +``` +val (+) : float -> float -> float +``` +``` +val (-) : float -> float -> float +``` +``` +val (*) : float -> float -> float +``` +``` +val (/) : float -> float -> float +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-HashMap-Int.md b/docs/api/melange/Belt-HashMap-Int.md new file mode 100644 index 000000000..f9083e664 --- /dev/null +++ b/docs/api/melange/Belt-HashMap-Int.md @@ -0,0 +1,75 @@ +# Module `HashMap.Int` +Specalized when key type is `int`, more efficient than the generic type +``` +type key = int +``` +``` +type 'b t +``` +``` +val make : hintSize:int -> 'b t +``` +``` +val clear : 'b t -> unit +``` +``` +val isEmpty : _ t -> bool +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` +``` +val copy : 'a t -> 'a t +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val has : 'b t -> key -> bool +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'b t -> (key -> 'b -> unit) -> unit +``` +``` +val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c +``` +``` +val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c +``` +``` +val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit +``` +``` +val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit +``` +``` +val size : _ t -> int +``` +``` +val toArray : 'a t -> (key * 'a) array +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val mergeMany : 'a t -> (key * 'a) array -> unit +``` +``` +val getBucketHistogram : _ t -> int array +``` +``` +val logStats : _ t -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-HashMap-String.md b/docs/api/melange/Belt-HashMap-String.md new file mode 100644 index 000000000..4708b8f0c --- /dev/null +++ b/docs/api/melange/Belt-HashMap-String.md @@ -0,0 +1,75 @@ +# Module `HashMap.String` +Specalized when key type is `string`, more efficient than the generic type +``` +type key = string +``` +``` +type 'b t +``` +``` +val make : hintSize:int -> 'b t +``` +``` +val clear : 'b t -> unit +``` +``` +val isEmpty : _ t -> bool +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` +``` +val copy : 'a t -> 'a t +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val has : 'b t -> key -> bool +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'b t -> (key -> 'b -> unit) -> unit +``` +``` +val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c +``` +``` +val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c +``` +``` +val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit +``` +``` +val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit +``` +``` +val size : _ t -> int +``` +``` +val toArray : 'a t -> (key * 'a) array +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val mergeMany : 'a t -> (key * 'a) array -> unit +``` +``` +val getBucketHistogram : _ t -> int array +``` +``` +val logStats : _ t -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-HashMap.md b/docs/api/melange/Belt-HashMap.md new file mode 100644 index 000000000..9acf8b3e0 --- /dev/null +++ b/docs/api/melange/Belt-HashMap.md @@ -0,0 +1,143 @@ +# Module `Belt.HashMap` +[`Belt.HashMap`](#) +The top level provides generic **mutable** hash map operations. +It also has two specialized inner modules [`Belt.HashMap.Int`](./Belt-HashMap-Int.md) and [`Belt.HashMap.String`](./Belt-HashMap-String.md) +A **mutable** Hash map which allows customized hash behavior. +All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashMaps of ints* initialized with different *hash* functions will have different type. +For example: +```ocaml + type t = int + module I0 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s0 : (_, string,_) t = make ~hintSize:40 ~id:(module I0) + module I1 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s1 : (_, string,_) t = make ~hintSize:40 ~id:(module I1) +``` +The invariant must be held: for two elements who are *equal*, their hashed value should be the same +Here the compiler would infer `s0` and `s1` having different type so that it would not mix. +```ocaml + val s0 : (int, I0.identity) t + val s1 : (int, I1.identity) t +``` +We can add elements to the collection: +```ocaml + + let () = + add s1 0 "3"; + add s1 1 "3" +``` +Since this is an mutable data strucure, `s1` will contain two pairs. +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type +``` +type ('key, 'value, 'id) t +``` +The type of hash tables from type `'key` to type `'value`. +``` +type ('a, 'id) id = + (module Belt__.Belt_Id.Hashable + with type identity = 'id + and type t = 'a) +``` +``` +val make : hintSize:int -> id:('key, 'id) id -> ('key, 'value, 'id) t +``` +``` +val clear : ('key, 'value, 'id) t -> unit +``` +Empty a hash table. +``` +val isEmpty : (_, _, _) t -> bool +``` +``` +val set : ('key, 'value, 'id) t -> 'key -> 'value -> unit +``` +`set tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` +``` +val copy : ('key, 'value, 'id) t -> ('key, 'value, 'id) t +``` +``` +val get : ('key, 'value, 'id) t -> 'key -> 'value option +``` +``` +val has : ('key, 'value, 'id) t -> 'key -> bool +``` +`has tbl x` checks if `x` is bound in `tbl`. +``` +val remove : ('key, 'value, 'id) t -> 'key -> unit +``` +``` +val forEachU : + ('key, 'value, 'id) t -> + ('key -> 'value -> unit) Js.Fn.arity2 -> + unit +``` +``` +val forEach : ('key, 'value, 'id) t -> ('key -> 'value -> unit) -> unit +``` +`forEach tbl f` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. +``` +val reduceU : + ('key, 'value, 'id) t -> + 'c -> + ('c -> 'key -> 'value -> 'c) Js.Fn.arity3 -> + 'c +``` +``` +val reduce : ('key, 'value, 'id) t -> 'c -> ('c -> 'key -> 'value -> 'c) -> 'c +``` +`reduce tbl init f` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. +``` +val keepMapInPlaceU : + ('key, 'value, 'id) t -> + ('key -> 'value -> 'value option) Js.Fn.arity2 -> + unit +``` +``` +val keepMapInPlace : + ('key, 'value, 'id) t -> + ('key -> 'value -> 'value option) -> + unit +``` +``` +val size : (_, _, _) t -> int +``` +`size tbl` returns the number of bindings in `tbl`. It takes constant time. +``` +val toArray : ('key, 'value, 'id) t -> ('key * 'value) array +``` +``` +val keysToArray : ('key, _, _) t -> 'key array +``` +``` +val valuesToArray : (_, 'value, _) t -> 'value array +``` +``` +val fromArray : + ('key * 'value) array -> + id:('key, 'id) id -> + ('key, 'value, 'id) t +``` +``` +val mergeMany : ('key, 'value, 'id) t -> ('key * 'value) array -> unit +``` +``` +val getBucketHistogram : (_, _, _) t -> int array +``` +``` +val logStats : (_, _, _) t -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-HashSet-Int.md b/docs/api/melange/Belt-HashSet-Int.md new file mode 100644 index 000000000..8a8c11c20 --- /dev/null +++ b/docs/api/melange/Belt-HashSet-Int.md @@ -0,0 +1,62 @@ +# Module `HashSet.Int` +Specalized when key type is `int`, more efficient than the generic type +This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. +It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) +**See** [`Belt.HashSet`](./Belt-HashSet.md) +``` +type key = int +``` +``` +type t +``` +``` +val make : hintSize:int -> t +``` +``` +val clear : t -> unit +``` +``` +val isEmpty : t -> bool +``` +``` +val add : t -> key -> unit +``` +``` +val copy : t -> t +``` +``` +val has : t -> key -> bool +``` +``` +val remove : t -> key -> unit +``` +``` +val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (key -> unit) -> unit +``` +``` +val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c +``` +``` +val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c +``` +``` +val size : t -> int +``` +``` +val logStats : t -> unit +``` +``` +val toArray : t -> key array +``` +``` +val fromArray : key array -> t +``` +``` +val mergeMany : t -> key array -> unit +``` +``` +val getBucketHistogram : t -> int array +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-HashSet-String.md b/docs/api/melange/Belt-HashSet-String.md new file mode 100644 index 000000000..9f0c86032 --- /dev/null +++ b/docs/api/melange/Belt-HashSet-String.md @@ -0,0 +1,62 @@ +# Module `HashSet.String` +Specalized when key type is `string`, more efficient than the generic type +This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. +It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) +**See** [`Belt.HashSet`](./Belt-HashSet.md) +``` +type key = string +``` +``` +type t +``` +``` +val make : hintSize:int -> t +``` +``` +val clear : t -> unit +``` +``` +val isEmpty : t -> bool +``` +``` +val add : t -> key -> unit +``` +``` +val copy : t -> t +``` +``` +val has : t -> key -> bool +``` +``` +val remove : t -> key -> unit +``` +``` +val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (key -> unit) -> unit +``` +``` +val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c +``` +``` +val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c +``` +``` +val size : t -> int +``` +``` +val logStats : t -> unit +``` +``` +val toArray : t -> key array +``` +``` +val fromArray : key array -> t +``` +``` +val mergeMany : t -> key array -> unit +``` +``` +val getBucketHistogram : t -> int array +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-HashSet.md b/docs/api/melange/Belt-HashSet.md new file mode 100644 index 000000000..8061c8421 --- /dev/null +++ b/docs/api/melange/Belt-HashSet.md @@ -0,0 +1,107 @@ +# Module `Belt.HashSet` +[`Belt.HashSet`](#) +The top level provides generic **mutable** hash set operations. +It also has two specialized inner modules [`Belt.HashSet.Int`](./Belt-HashSet-Int.md) and [`Belt.HashSet.String`](./Belt-HashSet-String.md) +A **mutable** Hash set which allows customized hash behavior. +All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashSets of ints* initialized with different *hash* functions will have different type. +For example: +```ocaml + type t = int + module I0 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s0 = make ~id:(module I0) ~hintSize:40 + module I1 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s1 = make ~id:(module I1) ~hintSize:40 +``` +The invariant must be held: for two elements who are *equal*, their hashed value should be the same +Here the compiler would infer `s0` and `s1` having different type so that it would not mix. +```ocaml + val s0 : (int, I0.identity) t + val s1 : (int, I1.identity) t +``` +We can add elements to the collection: +```ocaml + + let () = + add s1 0; + add s1 1 +``` +Since this is an mutable data strucure, `s1` will contain two pairs. +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type +``` +type ('a, 'id) t +``` +The type of hash tables from type `'a` to type `'b`. +``` +type ('a, 'id) id = + (module Belt__.Belt_Id.Hashable + with type identity = 'id + and type t = 'a) +``` +``` +val make : hintSize:int -> id:('a, 'id) id -> ('a, 'id) t +``` +``` +val clear : ('a, 'id) t -> unit +``` +``` +val isEmpty : (_, _) t -> bool +``` +``` +val add : ('a, 'id) t -> 'a -> unit +``` +``` +val copy : ('a, 'id) t -> ('a, 'id) t +``` +``` +val has : ('a, 'id) t -> 'a -> bool +``` +``` +val remove : ('a, 'id) t -> 'a -> unit +``` +``` +val forEachU : ('a, 'id) t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('a, 'id) t -> ('a -> unit) -> unit +``` +Order unspecified. +``` +val reduceU : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) Js.Fn.arity2 -> 'c +``` +``` +val reduce : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) -> 'c +``` +Order unspecified. +``` +val size : ('a, 'id) t -> int +``` +``` +val logStats : (_, _) t -> unit +``` +``` +val toArray : ('a, 'id) t -> 'a array +``` +``` +val fromArray : 'a array -> id:('a, 'id) id -> ('a, 'id) t +``` +``` +val mergeMany : ('a, 'id) t -> 'a array -> unit +``` +``` +val getBucketHistogram : (_, _) t -> int array +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md b/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md new file mode 100644 index 000000000..c50c978a9 --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md @@ -0,0 +1,7 @@ +# Parameter `MakeComparable.M` +``` +type t +``` +``` +val cmp : t -> t -> int +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeComparable.md b/docs/api/melange/Belt-Id-MakeComparable.md new file mode 100644 index 000000000..8f7a9ff16 --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeComparable.md @@ -0,0 +1,15 @@ +# Module `Id.MakeComparable` +## Parameters +``` +module M : sig ... end +``` +## Signature +``` +type identity +``` +``` +type t = M.t +``` +``` +val cmp : (t, identity) cmp +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md b/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md new file mode 100644 index 000000000..8fc1b5d88 --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md @@ -0,0 +1,7 @@ +# Parameter `MakeComparableU.M` +``` +type t +``` +``` +val cmp : (t -> t -> int) Js.Fn.arity2 +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeComparableU.md b/docs/api/melange/Belt-Id-MakeComparableU.md new file mode 100644 index 000000000..720efb1a1 --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeComparableU.md @@ -0,0 +1,15 @@ +# Module `Id.MakeComparableU` +## Parameters +``` +module M : sig ... end +``` +## Signature +``` +type identity +``` +``` +type t = M.t +``` +``` +val cmp : (t, identity) cmp +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md b/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md new file mode 100644 index 000000000..72f1862a2 --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md @@ -0,0 +1,10 @@ +# Parameter `MakeHashable.M` +``` +type t +``` +``` +val hash : t -> int +``` +``` +val eq : t -> t -> bool +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeHashable.md b/docs/api/melange/Belt-Id-MakeHashable.md new file mode 100644 index 000000000..a98e058be --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeHashable.md @@ -0,0 +1,18 @@ +# Module `Id.MakeHashable` +## Parameters +``` +module M : sig ... end +``` +## Signature +``` +type identity +``` +``` +type t = M.t +``` +``` +val hash : (t, identity) hash +``` +``` +val eq : (t, identity) eq +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md b/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md new file mode 100644 index 000000000..9d8b06d75 --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md @@ -0,0 +1,10 @@ +# Parameter `MakeHashableU.M` +``` +type t +``` +``` +val hash : (t -> int) Js.Fn.arity1 +``` +``` +val eq : (t -> t -> bool) Js.Fn.arity2 +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-MakeHashableU.md b/docs/api/melange/Belt-Id-MakeHashableU.md new file mode 100644 index 000000000..4dd0b7009 --- /dev/null +++ b/docs/api/melange/Belt-Id-MakeHashableU.md @@ -0,0 +1,18 @@ +# Module `Id.MakeHashableU` +## Parameters +``` +module M : sig ... end +``` +## Signature +``` +type identity +``` +``` +type t = M.t +``` +``` +val hash : (t, identity) hash +``` +``` +val eq : (t, identity) eq +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-module-type-Comparable.md b/docs/api/melange/Belt-Id-module-type-Comparable.md new file mode 100644 index 000000000..c83cf4e96 --- /dev/null +++ b/docs/api/melange/Belt-Id-module-type-Comparable.md @@ -0,0 +1,10 @@ +# Module type `Id.Comparable` +``` +type identity +``` +``` +type t +``` +``` +val cmp : (t, identity) cmp +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id-module-type-Hashable.md b/docs/api/melange/Belt-Id-module-type-Hashable.md new file mode 100644 index 000000000..4a1aaadd4 --- /dev/null +++ b/docs/api/melange/Belt-Id-module-type-Hashable.md @@ -0,0 +1,13 @@ +# Module type `Id.Hashable` +``` +type identity +``` +``` +type t +``` +``` +val hash : (t, identity) hash +``` +``` +val eq : (t, identity) eq +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Id.md b/docs/api/melange/Belt-Id.md new file mode 100644 index 000000000..ab2863728 --- /dev/null +++ b/docs/api/melange/Belt-Id.md @@ -0,0 +1,90 @@ +# Module `Belt.Id` +[`Belt.Id`](#) +Provide utilities to create identified comparators or hashes for data structures used below. +It create a unique identifier per module of functions so that different data structures with slightly different comparison functions won't mix +[`Belt.Id`](#) +Provide utiliites to create identified comparators or hashes for data structures used below. +It create a unique identifer per module of functions so that different data structures with slightly different comparison functions won't mix. +``` +type ('a, 'id) hash +``` +`('a, 'id) hash` +Its runtime represenation is a `hash` function, but signed with a type parameter, so that different hash functions type mismatch +``` +type ('a, 'id) eq +``` +`('a, 'id) eq` +Its runtime represenation is an `eq` function, but signed with a type parameter, so that different hash functions type mismatch +``` +type ('a, 'id) cmp +``` +`('a,'id) cmp` +Its runtime representation is a `cmp` function, but signed with a type parameter, so that different hash functions type mismatch +``` +module type Comparable = sig ... end +``` +``` +type ('key, 'id) comparable = + (module Comparable + with type identity = 'id + and type t = 'key) +``` +`('key, 'id) cmparable` is a module of functions, here it only includes `cmp`. +Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). +It can be created using function [`comparableU`](./#val-comparableU) or [`comparable`](./#val-comparable). +The idea of a unique identity when created is that it makes sure two sets would type mismatch if they use different comparison function +``` +module MakeComparableU (M : sig ... end) : Comparable with type t = M.t +``` +``` +module MakeComparable (M : sig ... end) : Comparable with type t = M.t +``` +``` +val comparableU : + cmp:('a -> 'a -> int) Js.Fn.arity2 -> + (module Comparable + with type t = 'a) +``` +``` +val comparable : cmp:('a -> 'a -> int) -> (module Comparable with type t = 'a) +``` +```ocaml + module C = ( + val Belt.Id.comparable ~cmp:(compare : int -> int -> int) + ) + let m = Belt.Set.make(module C) +``` +Note that the name of C can not be ignored +``` +module type Hashable = sig ... end +``` +``` +type ('key, 'id) hashable = + (module Hashable + with type identity = 'id + and type t = 'key) +``` +`('key, 'id) hashable` is a module of functions, here it only includes `hash`, `eq`. +Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). +It can be created using function [`hashableU`](./#val-hashableU) or [`hashable`](./#val-hashable). +The idea of a unique identity when created is that it makes sure two hash sets would type mismatch if they use different comparison function +``` +module MakeHashableU (M : sig ... end) : Hashable with type t = M.t +``` +``` +module MakeHashable (M : sig ... end) : Hashable with type t = M.t +``` +``` +val hashableU : + hash:('a -> int) Js.Fn.arity1 -> + eq:('a -> 'a -> bool) Js.Fn.arity2 -> + (module Hashable + with type t = 'a) +``` +``` +val hashable : + hash:('a -> int) -> + eq:('a -> 'a -> bool) -> + (module Hashable + with type t = 'a) +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Int.md b/docs/api/melange/Belt-Int.md new file mode 100644 index 000000000..2ace83c57 --- /dev/null +++ b/docs/api/melange/Belt-Int.md @@ -0,0 +1,26 @@ +# Module `Belt.Int` +[`Belt.Int`](#) Utililites for Int +``` +val toFloat : int -> float +``` +``` +val fromFloat : float -> int +``` +``` +val fromString : string -> int option +``` +``` +val toString : int -> string +``` +``` +val (+) : int -> int -> int +``` +``` +val (-) : int -> int -> int +``` +``` +val (*) : int -> int -> int +``` +``` +val (/) : int -> int -> int +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-List.md b/docs/api/melange/Belt-List.md new file mode 100644 index 000000000..93f1dd9cd --- /dev/null +++ b/docs/api/melange/Belt-List.md @@ -0,0 +1,594 @@ +# Module `Belt.List` +[`Belt.List`](#) +Utilities for List data type +[`Belt.List`](#) +Utilities for List data type. +This module is compatible with original ocaml stdlib. In general, all functions comes with the original stdlib also applies to this collection, however, this module provides faster and stack safer utilities +``` +type 'a t = 'a list +``` +`'a t` is compatible with built-in `list` type +``` +val length : 'a t -> int +``` +`length xs` +returns the length of the list xs +``` +val size : 'a t -> int +``` +**See** [`length`](./#val-length) +``` +val head : 'a t -> 'a option +``` +`head xs` returns `None` if `xs` is the empty list, otherwise it returns `Some value` where `value` is the first element in the list. +```ocaml + head [] = None ;; + head [1;2;3] = Some 1 ;; +``` +``` +val headExn : 'a t -> 'a +``` +`headExn xs` +**See** [`head`](./#val-head) +**raise** an exception if `xs` is empty +``` +val tail : 'a t -> 'a t option +``` +`tail xs` returns `None` if `xs` is empty; otherwise it returns `Some xs2` where `xs2` is everything except the first element of `xs`; +```ocaml + tail [] = None;; + tail [1;2;3;4] = Some [2;3;4];; +``` +``` +val tailExn : 'a t -> 'a t +``` +`tailExn xs` +**See** [`tail`](./#val-tail) +**raise** an exception if `xs` is empty +``` +val add : 'a t -> 'a -> 'a t +``` +`add xs y` adds `y` to the beginning of list `xs` +```ocaml + add [1] 3 = [3;1];; +``` +``` +val get : 'a t -> int -> 'a option +``` +`get xs n` +return the nth element in `xs`, or `None` if `n` is larger than the length +```ocaml + get [0;3;32] 2 = Some 32 ;; + get [0;3;32] 3 = None;; +``` +``` +val getExn : 'a t -> int -> 'a +``` +`getExn xs n` +**See** [`get`](./#val-get) +**raise** an exception if `n` is larger than the length +``` +val make : int -> 'a -> 'a t +``` +`make n v` +- return a list of length `n` with each element filled with value `v` +- return the empty list if `n` is negative +```ocaml + make 3 1 = [1;1;1] +``` +``` +val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val makeBy : int -> (int -> 'a) -> 'a t +``` +`makeBy n f` +- return a list of length `n` with element `i` initialized with `f i` +- return the empty list if `n` is negative +```ocaml + makeBy 5 (fun i -> i) = [0;1;2;3;4];; + makeBy 5 (fun i -> i * i) = [0;1;4;9;16];; +``` +``` +val shuffle : 'a t -> 'a t +``` +`shuffle xs` +returns a new list in random order +``` +val drop : 'a t -> int -> 'a t option +``` +`drop xs n` +return the list obtained by dropping the first `n` elements, or `None` if `xs` has fewer than `n` elements +```ocaml + drop [1;2;3] 2 = Some [3];; + drop [1;2;3] 3 = Some [];; + drop [1;2;3] 4 = None;; +``` +``` +val take : 'a t -> int -> 'a t option +``` +`take xs n` +return a list with the first `n` elements from `xs`, or `None` if `xs` has fewer than `n` elements +```ocaml + take [1;2;3] 1 = Some [1];; + take [1;2;3] 2 = Some [1;2];; + take [1;2;3] 4 = None;; +``` +``` +val splitAt : 'a t -> int -> ('a list * 'a list) option +``` +`splitAt xs n` split the list `xs` at position `n` return None when the length of `xs` is less than `n` +```ocaml + splitAt [0;1;2;3;4] 2 = Some ([0;1], [2;3;4]) +``` +``` +val concat : 'a t -> 'a t -> 'a t +``` +`concat xs ys` +returns the list obtained by adding ys after xs +```ocaml + concat [1;2;3] [4;5] = [1;2;3;4;5] +``` +``` +val concatMany : 'a t array -> 'a t +``` +`concatMany a` return the list obtained by concatenating in order all the lists in array `a` +```ocaml + concatMany [| [1;2;3] ; []; [3]; [4] |] = [1;2;3;3;4] +``` +``` +val reverseConcat : 'a t -> 'a t -> 'a t +``` +`reverseConcat xs ys` is equivalent to `concat (reverse xs) ys` +```ocaml + reverseConcat [1;2] [3;4] = [2;1;3;4] +``` +``` +val flatten : 'a t t -> 'a t +``` +`flatten ls` return the list obtained by concatenating in order all the lists in list `ls` +```ocaml + flatten [ [1;2;3] ; []; [3]; [4] ] = [1;2;3;3;4] +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +`map xs f` +return the list obtained by applying `f` to each element of `xs` +```ocaml + map [1;2] (fun x-> x + 1) = [3;4] +``` +``` +val zip : 'a t -> 'b t -> ('a * 'b) t +``` +`zip xs ys` +returns a list of pairs from the two lists with the length of the shorter list +```ocaml + zip [1;2] [3;4;5] = [(1,3); (2,4)] +``` +``` +val zipByU : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t +``` +``` +val zipBy : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t +``` +`zipBy xs ys f` +**See** [`zip`](./#val-zip) +Equivalent to `zip xs ys |> List.map (fun (x,y) -> f x y)` +```ocaml + zipBy [1;2;3] [4;5] (fun a b -> 2 * a + b) = [6;9];; +``` +``` +val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t +``` +`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. +```ocaml + mapWithIndex [1;2;3] (fun i x -> i + x) = + [0 + 1; 1 + 2; 2 + 3 ] +``` +``` +val fromArray : 'a array -> 'a t +``` +`fromArray arr` converts the given array to a list +```ocaml + fromArray [|1;2;3|] = [1;2;3] +``` +``` +val toArray : 'a t -> 'a array +``` +`toArray xs` converts the given list to an array +```ocaml + toArray [1;2;3] = [|1;2;3|] +``` +``` +val reverse : 'a t -> 'a t +``` +`reverse xs` returns a new list whose elements are those of `xs` in reverse order. +```ocaml + reverse [1;2;3] = [3;2;1] +``` +``` +val mapReverseU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val mapReverse : 'a t -> ('a -> 'b) -> 'b t +``` +`mapReverse xs f` +Equivalent to `reverse (map xs f)` +```ocaml + mapReverse [3;4;5] (fun x -> x * x) = [25;16;9];; +``` +``` +val forEachU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> 'b) -> unit +``` +`forEach xs f ` Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`, so no new array is created. Use `foreach` when you are primarily concerned with repetitively creating side effects. +```ocaml + forEach ["a";"b";"c"] (fun x -> Js.log("Item: " ^ x));; + (* prints: + Item: a + Item: b + Item: c + *) + + let us = ref 0;; + forEach [1;2;3;4] (fun x -> us := !us + x);; + !us = 1 + 2 + 3 + 4;; +``` +``` +val forEachWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> unit +``` +``` +val forEachWithIndex : 'a t -> (int -> 'a -> 'b) -> unit +``` +`forEachWithIndex xs f` +```ocaml + + forEach ["a";"b";"c"] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; + (* prints: + Item 0 is a + Item 1 is b + Item 2 is cc + *) + + let total = ref 0 ;; + forEachWithIndex [10;11;12;13] (fun i x -> total := !total + x + i);; + !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; +``` +``` +val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b +``` +`reduce xs f` +Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”, which starts with a value of `init`. `reduce` returns the final value of the accumulator. +```ocaml + reduce [1;2;3;4] 0 (+) = 10;; + reduce [1;2;3;4] 10 (-) = 0;; + reduce [1;2;3;4] [] add = [4;3;2;1]; +``` +``` +val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b +``` +`reduceWithIndex xs f` +Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the list and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. +```ocaml + reduceWithIndex [1;2;3;4] 0 (fun acc x i -> acc + x + i) = 16;; +``` +``` +val reduceReverseU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b +``` +``` +val reduceReverse : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b +``` +`reduceReverse xs f` +Works like [`reduce`](./#val-reduce), except that function `f` is applied to each item of `xs` from the last back to the first. +```ocaml + reduceReverse [1;2;3;4] 0 (+) = 10;; + reduceReverse [1;2;3;4] 10 (-) = 0;; + reduceReverse [1;2;3;4] [] add = [1;2;3;4];; +``` +``` +val mapReverse2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t +``` +``` +val mapReverse2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t +``` +`mapReverse2 xs ys f` +equivalent to `reverse (zipBy xs ys f)` +```ocaml + mapReverse2 [1;2;3] [1;2] (+) = [4;2] +``` +``` +val forEach2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> unit +``` +``` +val forEach2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> unit +``` +`forEach2 xs ys f` stop with the shorter list +``` +val reduce2U : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) Js.Fn.arity3 -> 'a +``` +``` +val reduce2 : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) -> 'a +``` +`reduce2 xs ys init f ` +Applies `f` to each element of `xs` and `ys` from beginning to end. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. +```ocaml + reduce2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; + reduce2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [2 +5;1 + 4 ];; (*add appends at end *) +``` +``` +val reduceReverse2U : + 'a t -> + 'b t -> + 'c -> + ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> + 'c +``` +``` +val reduceReverse2 : 'a t -> 'b t -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c +``` +`reduceReverse2 xs ys init f ` +Applies `f` to each element of `xs` and `ys` from end to beginning. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. +```ocaml + reduceReverse2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; + reduceReverse2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [1 + 4;2 + 5];; (*add appends at end *) +``` +``` +val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : 'a t -> ('a -> bool) -> bool +``` +`every xs p` +returns true if all elements satisfy p, where p is a predicate: a function taking an element and returning a bool. +```ocaml + every [] (fun x -> x mod 2 = 0) = true;; + every [2;4;6] (fun x -> x mod 2 = 0 ) = true;; + every [1;-3;5] (fun x -> x > 0) = false;; +``` +``` +val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : 'a t -> ('a -> bool) -> bool +``` +`some xs p` +returns true if at least one of the elements in xs satifies p, where p is a predicate: a function taking an element and returning a bool. +```ocaml + some [] (fun x -> x mod 2 = 0) = false ;; + some [1;2;4] (fun x -> x mod 2 = 0) = true;; + some [-1;-3;-5] (fun x -> x > 0) = false;; +``` +``` +val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`every2 xs ys p` returns true if predicate `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) +```ocaml + every2 [1;2;3] [0;1] (>) = true;; + every2 [] [1] (fun x y -> x > y) = true;; + every2 [2;3] [1] (fun x y -> x > y) = true;; + every2 [0;1] [5;0] (fun x y -> x > y) = false; +``` +``` +val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) +```ocaml + some2 [0;2] [1;0;3] (>) = true ;; + some2 [] [1] (fun x y -> x > y) = false;; + some2 [2;3] [1;4] (fun x y -> x > y) = true;; +``` +``` +val cmpByLength : 'a t -> 'a t -> int +``` +`cmpByLength l1 l2` +Compare two lists solely by length. Returns \-1 if `length l1` is less than `length l2`, 0 if `length l1` equals `length l2`, and 1 if `length l1` is greater than `length l2`. +```ocaml +cmpByLength [1;2] [3;4;5;6] = -1;; +cmpByLength [1;2;3] [4;5;6] = 0;; +cmpByLength [1;2;3;4] [5;6] = 1;; +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +Compare elements one by one `f x y`. `f` returns +- a negative number if `x` is “less than” `y` +- zero if `x` is “equal to” `y` +- a positive number if `x` is “greater than” `y` The comparison returns the first non-zero result of `f`, or zero if `f` returns zero for all `x` and `y`. If all items have compared equal, but `xs` is exhausted first, return \-1. (`xs` is shorter) If all items have compared equal, but `ys` is exhausted first, return 1 (`xs` is longer) +```ocaml + cmp [3] [3;7] (fun a b -> compare a b) = -1 + cmp [5;3] [5] (fun a b -> compare a b) = 1 + cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; + cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; + cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; +``` +**Attention**: The total ordering of List is different from Array, for Array, we compare the length first and, only if the lengths are equal, elements one by one. For lists, we just compare elements one by one +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq xs ys eqElem` check equality of `xs` and `ys` using `eqElem` for equality on elements, where `eqElem` is a function that returns true if items `x` and `y` meet some criterion for equality, false otherwise. `eq` false if length of `xs` and `ys` are not the same. +```ocaml + eq [1;2;3] [1;2] (=) = false ;; + eq [1;2] [1;2] (=) = true;; + eq [1; 2; 3] [-1; -2; -3] (fun a b -> abs a = abs b) = true;; +``` +``` +val hasU : 'a t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val has : 'a t -> 'b -> ('a -> 'b -> bool) -> bool +``` +`has xs eqFcn` returns true if the list contains at least one element for which `eqFcn x` returns true +```ocaml + has [1;2;3] 2 (=) = true;; + has [1;2;3] 4 (=) = false;; + has [-1;-2;-3] 2 (fun a b -> abs a = abs b) = true;; +``` +``` +val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option +``` +``` +val getBy : 'a t -> ('a -> bool) -> 'a option +``` +`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. +```ocaml + getBy [1;4;3;2] (fun x -> x mod 2 = 0) = Some 4 + getBy [15;13;11] (fun x -> x mod 2 = 0) = None +``` +``` +val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t +``` +``` +val keep : 'a t -> ('a -> bool) -> 'a t +``` +`keep xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` +```ocaml + keep [1;2;3;4] (fun x -> x mod 2 = 0) = + [2;4] +``` +``` +val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t +``` +``` +val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t +``` +`keepWithIndex xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` +```ocaml + keepWithIndex [1;2;3;4] (fun _x i -> i mod 2 = 0) + = + [1;3] +``` +``` +val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b t +``` +``` +val keepMap : 'a t -> ('a -> 'b option) -> 'b t +``` +`keepMap xs f` applies `f` to each element of `xs`. If `f xi` returns `Some value`, then `value` is kept in the resulting list; if `f xi` returns `None`, the element is not retained in the result. +```ocaml + keepMap [1;2;3;4] (fun x -> if x mod 2 = 0 then Some (-x ) else None) + = + [-2;-4] +``` +``` +val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t +``` +``` +val partition : 'a t -> ('a -> bool) -> 'a t * 'a t +``` +`partition xs p` creates a pair of lists; the first list consists of all elements of `xs` that satisfy the predicate function `p`; the second list consists of all elements of `xs` that do not satisfy `p` +```ocaml + partition [1;2;3;4] (fun x -> x mod 2 = 0) = + ([2;4], [1;3]) +``` +``` +val unzip : ('a * 'b) t -> 'a t * 'b t +``` +`unzip xs` takes a list of pairs and creates a pair of lists. The first list contains all the first items of the pairs; the second list contains all the second items. +```ocaml + unzip [(1,2) ; (3,4)] = ([1;3], [2;4]);; + unzip [(1,2) ; (3,4) ; (5,6) ; (7,8)] = ([1;3;5;7], [2;4;6;8]);; +``` +``` +val getAssocU : + ('a * 'c) t -> + 'b -> + ('a -> 'b -> bool) Js.Fn.arity2 -> + 'c option +``` +``` +val getAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> 'c option +``` +`getAssoc xs k eq` +return the second element of a pair in `xs` where the first element equals `x` as per the predicate function `eq`, or `None` if not found +```ocaml + getAssoc [ 1, "a"; 2, "b"; 3, "c"] 2 (=) = Some "b" + getAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = Some "afternoon" +``` +``` +val hasAssocU : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val hasAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> bool +``` +`hasAssoc xs k eq` return true if there is a pair in `xs` where the first element equals `k` as per the predicate funtion `eq` +```ocaml + hasAssoc [1, "a"; 2, "b"; 3,"c"] 1 (=) = true;; + hasAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = true;; +``` +``` +val removeAssocU : + ('a * 'c) t -> + 'b -> + ('a -> 'b -> bool) Js.Fn.arity2 -> + ('a * 'c) t +``` +``` +val removeAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> ('a * 'c) t +``` +`removeAssoc xs k eq` Return a list after removing the first pair whose first value is `k` per the equality predicate `eq`; if not found, return a new list identical to `xs`. +```ocaml + removeAssoc [1,"a"; 2, "b"; 3, "c" ] 1 (=) = + [2, "b"; 3, "c"] + removeAssoc [1,"a"; 2, "b"; 3, "c" ] 99 (=) = + [1, "a"; 2, "b"; 3, "c"] +``` +``` +val setAssocU : + ('a * 'c) t -> + 'a -> + 'c -> + ('a -> 'a -> bool) Js.Fn.arity2 -> + ('a * 'c) t +``` +``` +val setAssoc : ('a * 'c) t -> 'a -> 'c -> ('a -> 'a -> bool) -> ('a * 'c) t +``` +`setAssoc xs k v eq` if `k` exists in `xs` by satisfying the `eq` predicate, return a new list with the key and value replaced by the new `k` and `v`; otherwise, return a new list with the pair `k, v` added to the head of `xs`. +```ocaml + setAssoc [1,"a"; 2, "b"; 3, "c"] 2 "x" (=) = + [1,"a"; 2, "x"; 3,"c"] ;; + + setAssoc [1,"a"; 3, "c"] 2 "b" (=) = + [2,"b"; 1,"a"; 3, "c"] + + setAssoc [9, "morning"; 3, "morning?!"; 22, "night"] 15 "afternoon" + (fun a b -> a mod 12 = b mod 12) = [9, "morning"; 15, "afternoon"; 22, "night"] +``` +Note carefully the last example\! Since `15 mod 12` equals `3 mod 12`, *both* the key and value are replaced in the list. +``` +val sortU : 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a t +``` +``` +val sort : 'a t -> ('a -> 'a -> int) -> 'a t +``` +`sort xs` Returns a sorted list. +```ocaml + sort [5; 4; 9; 3; 7] (fun a b -> a - b) = [3; 4; 5; 7; 9] +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Map-Dict.md b/docs/api/melange/Belt-Map-Dict.md new file mode 100644 index 000000000..2c198bbe4 --- /dev/null +++ b/docs/api/melange/Belt-Map-Dict.md @@ -0,0 +1,262 @@ +# Module `Map.Dict` +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation +**Advanced usage only** +``` +type ('key, 'value, 'id) t +``` +``` +type ('key, 'id) cmp +``` +``` +val empty : ('k, 'v, 'id) t +``` +``` +val isEmpty : ('k, 'v, 'id) t -> bool +``` +``` +val has : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> bool +``` +``` +val cmpU : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + kcmp:('k, 'id) cmp -> + vcmp:('v -> 'v -> int) Js.Fn.arity2 -> + int +``` +``` +val cmp : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + kcmp:('k, 'id) cmp -> + vcmp:('v -> 'v -> int) -> + int +``` +``` +val eqU : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + kcmp:('k, 'id) cmp -> + veq:('a -> 'a -> bool) Js.Fn.arity2 -> + bool +``` +``` +val eq : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + kcmp:('k, 'id) cmp -> + veq:('a -> 'a -> bool) -> + bool +``` +`eq m1 m2 cmp` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. +``` +val findFirstByU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k * 'v) option +``` +``` +val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val reduceU : + ('k, 'a, 'id) t -> + 'b -> + ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> + 'b +``` +``` +val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +``` +val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified +``` +val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified +``` +val size : ('k, 'a, 'id) t -> int +``` +``` +val toList : ('k, 'a, 'id) t -> ('k * 'a) list +``` +In increasing order. +``` +val toArray : ('k, 'a, 'id) t -> ('k * 'a) array +``` +``` +val fromArray : ('k * 'a) array -> cmp:('k, 'id) cmp -> ('k, 'a, 'id) t +``` +``` +val keysToArray : ('k, 'a, 'id) t -> 'k array +``` +``` +val valuesToArray : ('k, 'a, 'id) t -> 'a array +``` +``` +val minKey : ('k, _, _) t -> 'k option +``` +``` +val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val maxKey : ('k, _, _) t -> 'k option +``` +``` +val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val minimum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val maximum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val get : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a option +``` +``` +val getUndefined : + ('k, 'a, 'id) t -> + 'k -> + cmp:('k, 'id) cmp -> + 'a Js.undefined +``` +``` +val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> cmp:('k, 'id) cmp -> 'a +``` +``` +val getExn : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a +``` +``` +val checkInvariantInternal : (_, _, _) t -> unit +``` +**raise** when invariant is not held +``` +val remove : ('a, 'b, 'id) t -> 'a -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t +``` +`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. +``` +val removeMany : + ('a, 'b, 'id) t -> + 'a array -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val set : ('a, 'b, 'id) t -> 'a -> 'b -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t +``` +`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. +``` +val updateU : + ('a, 'b, 'id) t -> + 'a -> + ('b option -> 'b option) Js.Fn.arity1 -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val update : + ('a, 'b, 'id) t -> + 'a -> + ('b option -> 'b option) -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val mergeU : + ('a, 'b, 'id) t -> + ('a, 'c, 'id) t -> + ('a -> 'b option -> 'c option -> 'd option) Js.Fn.arity3 -> + cmp:('a, 'id) cmp -> + ('a, 'd, 'id) t +``` +``` +val merge : + ('a, 'b, 'id) t -> + ('a, 'c, 'id) t -> + ('a -> 'b option -> 'c option -> 'd option) -> + cmp:('a, 'id) cmp -> + ('a, 'd, 'id) t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. +``` +val mergeMany : + ('a, 'b, 'id) t -> + ('a * 'b) array -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val keepU : + ('k, 'a, 'id) t -> + ('k -> 'a -> bool) Js.Fn.arity2 -> + ('k, 'a, 'id) t +``` +``` +val keep : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> ('k, 'a, 'id) t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. +``` +val partitionU : + ('k, 'a, 'id) t -> + ('k -> 'a -> bool) Js.Fn.arity2 -> + ('k, 'a, 'id) t * ('k, 'a, 'id) t +``` +``` +val partition : + ('k, 'a, 'id) t -> + ('k -> 'a -> bool) -> + ('k, 'a, 'id) t * ('k, 'a, 'id) t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. +``` +val split : + ('a, 'b, 'id) t -> + 'a -> + cmp:('a, 'id) cmp -> + (('a, 'b, 'id) t * ('a, 'b, 'id) t) * 'b option +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +``` +val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t +``` +``` +val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapWithKeyU : + ('k, 'a, 'id) t -> + ('k -> 'a -> 'b) Js.Fn.arity2 -> + ('k, 'b, 'id) t +``` +``` +val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Map-Int.md b/docs/api/melange/Belt-Map-Int.md new file mode 100644 index 000000000..36f9bfce3 --- /dev/null +++ b/docs/api/melange/Belt-Map-Int.md @@ -0,0 +1,198 @@ +# Module `Map.Int` +Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +``` +type key = int +``` +``` +type 'value t +``` +The type of maps from type `key` to type `'value`. +``` +val empty : 'v t +``` +``` +val isEmpty : 'v t -> bool +``` +``` +val has : 'v t -> key -> bool +``` +``` +val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int +``` +``` +val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool +``` +`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. +``` +val findFirstByU : + 'v t -> + (key -> 'v -> bool) Js.Fn.arity2 -> + (key * 'v) option +``` +``` +val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'v t -> (key -> 'v -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 +``` +``` +val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +``` +val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'v t -> (key -> 'v -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified +``` +val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'v t -> (key -> 'v -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified +``` +val size : 'v t -> int +``` +``` +val toList : 'v t -> (key * 'v) list +``` +In increasing order. +``` +val toArray : 'v t -> (key * 'v) array +``` +``` +val fromArray : (key * 'v) array -> 'v t +``` +``` +val keysToArray : 'v t -> key array +``` +``` +val valuesToArray : 'v t -> 'v array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'v t -> (key * 'v) option +``` +``` +val minUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val maximum : 'v t -> (key * 'v) option +``` +``` +val maxUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val get : 'v t -> key -> 'v option +``` +``` +val getUndefined : 'v t -> key -> 'v Js.undefined +``` +``` +val getWithDefault : 'v t -> key -> 'v -> 'v +``` +``` +val getExn : 'v t -> key -> 'v +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held +``` +val remove : 'v t -> key -> 'v t +``` +`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. +``` +val removeMany : 'v t -> key array -> 'v t +``` +``` +val set : 'v t -> key -> 'v -> 'v t +``` +`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. +``` +val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t +``` +``` +val update : 'v t -> key -> ('v option -> 'v option) -> 'v t +``` +``` +val mergeU : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> + 'c t +``` +``` +val merge : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) -> + 'c t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. +``` +val mergeMany : 'v t -> (key * 'v) array -> 'v t +``` +``` +val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t +``` +``` +val keep : 'v t -> (key -> 'v -> bool) -> 'v t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. +``` +val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t +``` +``` +val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. +``` +val split : key -> 'v t -> 'v t * 'v option * 'v t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +``` +val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t +``` +``` +val map : 'v t -> ('v -> 'v2) -> 'v2 t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t +``` +``` +val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Map-String.md b/docs/api/melange/Belt-Map-String.md new file mode 100644 index 000000000..89ba1550b --- /dev/null +++ b/docs/api/melange/Belt-Map-String.md @@ -0,0 +1,198 @@ +# Module `Map.String` +specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +``` +type key = string +``` +``` +type 'value t +``` +The type of maps from type `key` to type `'value`. +``` +val empty : 'v t +``` +``` +val isEmpty : 'v t -> bool +``` +``` +val has : 'v t -> key -> bool +``` +``` +val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int +``` +``` +val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool +``` +`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. +``` +val findFirstByU : + 'v t -> + (key -> 'v -> bool) Js.Fn.arity2 -> + (key * 'v) option +``` +``` +val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'v t -> (key -> 'v -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 +``` +``` +val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +``` +val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'v t -> (key -> 'v -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified +``` +val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'v t -> (key -> 'v -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified +``` +val size : 'v t -> int +``` +``` +val toList : 'v t -> (key * 'v) list +``` +In increasing order. +``` +val toArray : 'v t -> (key * 'v) array +``` +``` +val fromArray : (key * 'v) array -> 'v t +``` +``` +val keysToArray : 'v t -> key array +``` +``` +val valuesToArray : 'v t -> 'v array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'v t -> (key * 'v) option +``` +``` +val minUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val maximum : 'v t -> (key * 'v) option +``` +``` +val maxUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val get : 'v t -> key -> 'v option +``` +``` +val getUndefined : 'v t -> key -> 'v Js.undefined +``` +``` +val getWithDefault : 'v t -> key -> 'v -> 'v +``` +``` +val getExn : 'v t -> key -> 'v +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held +``` +val remove : 'v t -> key -> 'v t +``` +`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. +``` +val removeMany : 'v t -> key array -> 'v t +``` +``` +val set : 'v t -> key -> 'v -> 'v t +``` +`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. +``` +val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t +``` +``` +val update : 'v t -> key -> ('v option -> 'v option) -> 'v t +``` +``` +val mergeU : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> + 'c t +``` +``` +val merge : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) -> + 'c t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. +``` +val mergeMany : 'v t -> (key * 'v) array -> 'v t +``` +``` +val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t +``` +``` +val keep : 'v t -> (key -> 'v -> bool) -> 'v t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. +``` +val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t +``` +``` +val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. +``` +val split : key -> 'v t -> 'v t * 'v option * 'v t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +``` +val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t +``` +``` +val map : 'v t -> ('v -> 'v2) -> 'v2 t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t +``` +``` +val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Map.md b/docs/api/melange/Belt-Map.md new file mode 100644 index 000000000..6a24b66a6 --- /dev/null +++ b/docs/api/melange/Belt-Map.md @@ -0,0 +1,387 @@ +# Module `Belt.Map` +[`Belt.Map`](#), +The top level provides generic **immutable** map operations. +It also has three specialized inner modules [`Belt.Map.Int`](./Belt-Map-Int.md), [`Belt.Map.String`](./Belt-Map-String.md) and +[`Belt.Map.Dict`](./Belt-Map-Dict.md): This module separates data from function which is more verbose but slightly more efficient +A *immutable* sorted map module which allows customize *compare* behavior. +The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. +For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. +Example usage: +```ocaml + module PairComparator = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c + end) + + let myMap = Belt.Map.make ~id:(module PairComparator) + let myMap2 = Belt.Map.set myMap (1, 2) "myValue" +``` +The API documentation below will assume a predeclared comparator module for integers, IntCmp +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +``` +module String : sig ... end +``` +specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +``` +module Dict : sig ... end +``` +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation +``` +type ('key, 'value, 'identity) t +``` +`('key, 'identity) t` +`'key` is the field type +`'value` is the element type +`'identity` the identity of the collection +``` +type ('key, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'key) +``` +The identity needed for making an empty map +``` +val make : id:('k, 'id) id -> ('k, 'v, 'id) t +``` +`make ~id` creates a new map by taking in the comparator +```ocaml + let m = Belt.Map.make ~id:(module IntCmp) +``` +``` +val isEmpty : (_, _, _) t -> bool +``` +`isEmpty m` checks whether a map m is empty +```ocaml + isEmpty (fromArray [|1,"1"|] ~id:(module IntCmp)) = false +``` +``` +val has : ('k, 'v, 'id) t -> 'k -> bool +``` +`has m k` checks whether m has the key k +```ocaml + has (fromArray [|1,"1"|] ~id:(module IntCmp)) 1 = true +``` +``` +val cmpU : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + ('v -> 'v -> int) Js.Fn.arity2 -> + int +``` +``` +val cmp : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> int) -> int +``` +`cmp m0 m1 vcmp` +Total ordering of map given total ordering of value function. +It will compare size first and each element following the order one by one. +``` +val eqU : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + ('v -> 'v -> bool) Js.Fn.arity2 -> + bool +``` +``` +val eq : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> bool) -> bool +``` +`eq m1 m2 veq` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `veq` is the equality predicate used to compare the data associated with the keys. +``` +val findFirstByU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k * 'v) option +``` +``` +val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : ('k, 'v, 'id) t -> ('k -> 'v -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : ('k, 'v, 'id) t -> ('k -> 'v -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + let acc = ref [] ;; + forEach s0 (fun k v -> acc := (k,v) :: !acc);; + + !acc = [4,"4"; 3,"3"; 2,"2"; 1,"1"] +``` +``` +val reduceU : + ('k, 'v, 'id) t -> + 'acc -> + ('acc -> 'k -> 'v -> 'acc) Js.Fn.arity3 -> + 'acc +``` +``` +val reduce : ('k, 'v, 'id) t -> 'acc -> ('acc -> 'k -> 'v -> 'acc) -> 'acc +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + reduce s0 [] (fun acc k v -> (k,v) acc ) = [4,"4";3,"3";2,"2";1,"1"];; +``` +``` +val everyU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified +``` +val someU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified +``` +val size : ('k, 'v, 'id) t -> int +``` +`size s` +```ocaml + size (fromArray [2,"2"; 2,"1"; 3,"3"] ~id:(module IntCmp)) = 2 ;; +``` +``` +val toArray : ('k, 'v, 'id) t -> ('k * 'v) array +``` +`toArray s` +```ocaml + toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] +``` +``` +val toList : ('k, 'v, 'id) t -> ('k * 'v) list +``` +In increasing order +**See** [`toArray`](./#val-toArray) +``` +val fromArray : ('k * 'v) array -> id:('k, 'id) id -> ('k, 'v, 'id) t +``` +`fromArray kvs ~id` +```ocaml + toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] +``` +``` +val keysToArray : ('k, 'v, 'id) t -> 'k array +``` +`keysToArray s` +```ocaml + keysToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = + [|1;2;3|];; +``` +``` +val valuesToArray : ('k, 'v, 'id) t -> 'v array +``` +`valuesToArray s` +```ocaml + valuesToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = + [|"1";"2";"3"|];; +``` +``` +val minKey : ('k, _, _) t -> 'k option +``` +`minKey s` +returns the minimum key, None if not exist +``` +val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +**See** [`minKey`](./#val-minKey) +``` +val maxKey : ('k, _, _) t -> 'k option +``` +`maxKey s` +returns the maximum key, None if not exist +``` +val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +**See** [`maxKey`](./#val-maxKey) +``` +val minimum : ('k, 'v, _) t -> ('k * 'v) option +``` +`minimum s` +returns the minimum key value pair, None if not exist +``` +val minUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined +``` +**See** [`minimum`](./#val-minimum) +``` +val maximum : ('k, 'v, _) t -> ('k * 'v) option +``` +`maximum s` +returns the maximum key value pair, None if not exist +``` +val maxUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined +``` +**See** [`maximum`](./#val-maximum) +``` +val get : ('k, 'v, 'id) t -> 'k -> 'v option +``` +`get s k` +```ocaml + get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = + Some "2";; + get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = + None;; +``` +``` +val getUndefined : ('k, 'v, 'id) t -> 'k -> 'v Js.undefined +``` +**See** [`get`](./#val-get) +returns undefined when not found +``` +val getWithDefault : ('k, 'v, 'id) t -> 'k -> 'v -> 'v +``` +`getWithDefault s k default` +**See** [`get`](./#val-get) +returns default when k is not found +``` +val getExn : ('k, 'v, 'id) t -> 'k -> 'v +``` +`getExn s k` +**See** [`getExn`](./#val-getExn) +**raise** when `k` not exist +``` +val remove : ('k, 'v, 'id) t -> 'k -> ('k, 'v, 'id) t +``` +`remove m x` when `x` is not in `m`, `m` is returned reference unchanged. +```ocaml + let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; + + let s1 = remove s0 1;; + let s2 = remove s1 1;; + s1 == s2 ;; + keysToArray s1 = [|2;3|];; +``` +``` +val removeMany : ('k, 'v, 'id) t -> 'k array -> ('k, 'v, 'id) t +``` +`removeMany s xs` +Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` +``` +val set : ('k, 'v, 'id) t -> 'k -> 'v -> ('k, 'v, 'id) t +``` +`set m x y ` returns a map containing the same bindings as `m`, with a new binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. +```ocaml + let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; + + let s1 = set s0 2 "3";; + + valuesToArray s1 = ["1";"3";"3"];; +``` +``` +val updateU : + ('k, 'v, 'id) t -> + 'k -> + ('v option -> 'v option) Js.Fn.arity1 -> + ('k, 'v, 'id) t +``` +``` +val update : + ('k, 'v, 'id) t -> + 'k -> + ('v option -> 'v option) -> + ('k, 'v, 'id) t +``` +`update m x f` returns a map containing the same bindings as `m`, except for the binding of `x`. Depending on the value of `y` where `y` is `f (get x m)`, the binding of `x` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `x` is associated to `z` in the resulting map. +``` +val mergeMany : ('k, 'v, 'id) t -> ('k * 'v) array -> ('k, 'v, 'id) t +``` +`mergeMany s xs` +Add each of `xs` to `s`, note unlike [`set`](./#val-set), the reference of return value might be changed even if all values in `xs` exist `s` +``` +val mergeU : + ('k, 'v, 'id) t -> + ('k, 'v2, 'id) t -> + ('k -> 'v option -> 'v2 option -> 'v3 option) Js.Fn.arity3 -> + ('k, 'v3, 'id) t +``` +``` +val merge : + ('k, 'v, 'id) t -> + ('k, 'v2, 'id) t -> + ('k -> 'v option -> 'v2 option -> 'v3 option) -> + ('k, 'v3, 'id) t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. +``` +val keepU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k, 'v, 'id) t +``` +``` +val keep : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k, 'v, 'id) t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. +``` +val partitionU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k, 'v, 'id) t * ('k, 'v, 'id) t +``` +``` +val partition : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) -> + ('k, 'v, 'id) t * ('k, 'v, 'id) t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. +``` +val split : + ('k, 'v, 'id) t -> + 'k -> + (('k, 'v, 'id) t * ('k, 'v, 'id) t) * 'v option +``` +`split x m` returns a tuple `(l r), data`, where `l` is the map with all the bindings of `m` whose 'k is strictly less than `x`; `r` is the map with all the bindings of `m` whose 'k is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +``` +val mapU : ('k, 'v, 'id) t -> ('v -> 'v2) Js.Fn.arity1 -> ('k, 'v2, 'id) t +``` +``` +val map : ('k, 'v, 'id) t -> ('v -> 'v2) -> ('k, 'v2, 'id) t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapWithKeyU : + ('k, 'v, 'id) t -> + ('k -> 'v -> 'v2) Js.Fn.arity2 -> + ('k, 'v2, 'id) t +``` +``` +val mapWithKey : ('k, 'v, 'id) t -> ('k -> 'v -> 'v2) -> ('k, 'v2, 'id) t +``` +`mapWithKey m f` +The same as [`map`](./#val-map) except that `f` is supplied with one more argument: the key +``` +val getData : ('k, 'v, 'id) t -> ('k, 'v, 'id) Belt__.Belt_MapDict.t +``` +`getData s0` +**Advanced usage only** +returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing +``` +val getId : ('k, 'v, 'id) t -> ('k, 'id) id +``` +`getId s0` +**Advanced usage only** +returns the identity of s0 +``` +val packIdData : + id:('k, 'id) id -> + data:('k, 'v, 'id) Belt__.Belt_MapDict.t -> + ('k, 'v, 'id) t +``` +`packIdData ~id ~data` +**Advanced usage only** +returns the packed collection \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableMap-Int.md b/docs/api/melange/Belt-MutableMap-Int.md new file mode 100644 index 000000000..290569dea --- /dev/null +++ b/docs/api/melange/Belt-MutableMap-Int.md @@ -0,0 +1,151 @@ +# Module `MutableMap.Int` +``` +type key = int +``` +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val isEmpty : 'a t -> bool +``` +``` +val has : 'a t -> key -> bool +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq m1 m2 cmp` +``` +val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'a t -> (key -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. +``` +val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +``` +val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'a t -> (key -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. +``` +val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'a t -> (key -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. +``` +val size : 'a t -> int +``` +``` +val toList : 'a t -> (key * 'a) list +``` +In increasing order +``` +val toArray : 'a t -> (key * 'a) array +``` +In increasing order +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'a t -> (key * 'a) option +``` +``` +val minUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val maximum : 'a t -> (key * 'a) option +``` +``` +val maxUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val getUndefined : 'a t -> key -> 'a Js.undefined +``` +``` +val getWithDefault : 'a t -> key -> 'a -> 'a +``` +``` +val getExn : 'a t -> key -> 'a +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held +``` +val remove : 'a t -> key -> unit +``` +`remove m x` do the in-place modification +``` +val removeMany : 'a t -> key array -> unit +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. +``` +val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit +``` +``` +val update : 'a t -> key -> ('a option -> 'a option) -> unit +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableMap-String.md b/docs/api/melange/Belt-MutableMap-String.md new file mode 100644 index 000000000..8462f026b --- /dev/null +++ b/docs/api/melange/Belt-MutableMap-String.md @@ -0,0 +1,151 @@ +# Module `MutableMap.String` +``` +type key = string +``` +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val isEmpty : 'a t -> bool +``` +``` +val has : 'a t -> key -> bool +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq m1 m2 cmp` +``` +val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'a t -> (key -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. +``` +val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +``` +val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'a t -> (key -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. +``` +val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'a t -> (key -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. +``` +val size : 'a t -> int +``` +``` +val toList : 'a t -> (key * 'a) list +``` +In increasing order +``` +val toArray : 'a t -> (key * 'a) array +``` +In increasing order +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'a t -> (key * 'a) option +``` +``` +val minUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val maximum : 'a t -> (key * 'a) option +``` +``` +val maxUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val getUndefined : 'a t -> key -> 'a Js.undefined +``` +``` +val getWithDefault : 'a t -> key -> 'a -> 'a +``` +``` +val getExn : 'a t -> key -> 'a +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held +``` +val remove : 'a t -> key -> unit +``` +`remove m x` do the in-place modification +``` +val removeMany : 'a t -> key array -> unit +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. +``` +val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit +``` +``` +val update : 'a t -> key -> ('a option -> 'a option) -> unit +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableMap.md b/docs/api/melange/Belt-MutableMap.md new file mode 100644 index 000000000..ab3a5dfd6 --- /dev/null +++ b/docs/api/melange/Belt-MutableMap.md @@ -0,0 +1,187 @@ +# Module `Belt.MutableMap` +[`Belt.MutableMap`](#) +The top level provides generic **mutable** map operations. +It also has two specialized inner modules [`Belt.MutableMap.Int`](./Belt-MutableMap-Int.md) and [`Belt.MutableMap.String`](./Belt-MutableMap-String.md) +``` +module Int : sig ... end +``` +``` +module String : sig ... end +``` +A **mutable** sorted map module which allows customize *compare* behavior. +Same as Belt.Map, but mutable. +``` +type ('k, 'v, 'id) t +``` +``` +type ('key, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'key) +``` +``` +val make : id:('k, 'id) id -> ('k, 'a, 'id) t +``` +``` +val clear : (_, _, _) t -> unit +``` +``` +val isEmpty : (_, _, _) t -> bool +``` +``` +val has : ('k, _, _) t -> 'k -> bool +``` +``` +val cmpU : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + ('a -> 'a -> int) Js.Fn.arity2 -> + int +``` +``` +val cmp : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> int) -> int +``` +`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair +``` +val eqU : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + ('a -> 'a -> bool) Js.Fn.arity2 -> + bool +``` +``` +val eq : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> bool) -> bool +``` +`eq m1 m2 eqf` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `eqf` is the equality predicate used to compare the data associated with the keys. +``` +val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val reduceU : + ('k, 'a, 'id) t -> + 'b -> + ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> + 'b +``` +``` +val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +``` +val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. +``` +val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. +``` +val size : ('k, 'a, 'id) t -> int +``` +``` +val toList : ('k, 'a, 'id) t -> ('k * 'a) list +``` +In increasing order +``` +val toArray : ('k, 'a, 'id) t -> ('k * 'a) array +``` +In increasing order +``` +val fromArray : ('k * 'a) array -> id:('k, 'id) id -> ('k, 'a, 'id) t +``` +``` +val keysToArray : ('k, _, _) t -> 'k array +``` +``` +val valuesToArray : (_, 'a, _) t -> 'a array +``` +``` +val minKey : ('k, _, _) t -> 'k option +``` +``` +val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val maxKey : ('k, _, _) t -> 'k option +``` +``` +val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val minimum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val maximum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val get : ('k, 'a, 'id) t -> 'k -> 'a option +``` +``` +val getUndefined : ('k, 'a, 'id) t -> 'k -> 'a Js.undefined +``` +``` +val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> 'a +``` +``` +val getExn : ('k, 'a, 'id) t -> 'k -> 'a +``` +``` +val checkInvariantInternal : (_, _, _) t -> unit +``` +**raise** when invariant is not held +``` +val remove : ('k, 'a, 'id) t -> 'k -> unit +``` +`remove m x` do the in-place modification, +``` +val removeMany : ('k, 'a, 'id) t -> 'k array -> unit +``` +``` +val set : ('k, 'a, 'id) t -> 'k -> 'a -> unit +``` +`set m x y ` do the in-place modification +``` +val updateU : + ('k, 'a, 'id) t -> + 'k -> + ('a option -> 'a option) Js.Fn.arity1 -> + unit +``` +``` +val update : ('k, 'a, 'id) t -> 'k -> ('a option -> 'a option) -> unit +``` +``` +val mergeMany : ('k, 'a, 'id) t -> ('k * 'a) array -> unit +``` +``` +val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t +``` +``` +val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapWithKeyU : + ('k, 'a, 'id) t -> + ('k -> 'a -> 'b) Js.Fn.arity2 -> + ('k, 'b, 'id) t +``` +``` +val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableQueue.md b/docs/api/melange/Belt-MutableQueue.md new file mode 100644 index 000000000..4fa2ddaac --- /dev/null +++ b/docs/api/melange/Belt-MutableQueue.md @@ -0,0 +1,92 @@ +# Module `Belt.MutableQueue` +[`Belt.MutableQueue`](#) +An FIFO(first in first out) queue data structure +First-in first-out queues. +This module implements queues (FIFOs), with in-place modification. +``` +type 'a t +``` +The type of queues containing elements of type `'a`. +``` +val make : unit -> 'a t +``` +returns a new queue, initially empty. +``` +val clear : 'a t -> unit +``` +Discard all elements from the queue. +``` +val isEmpty : 'a t -> bool +``` +returns true if the given queue is empty, false otherwise. +``` +val fromArray : 'a array -> 'a t +``` +`fromArray a` is equivalent to `Array.forEach a (add q a)` +``` +val add : 'a t -> 'a -> unit +``` +`add q x` adds the element `x` at the end of the queue `q`. +``` +val peek : 'a t -> 'a option +``` +`peekOpt q` returns the first element in queue `q`, without removing it from the queue. +``` +val peekUndefined : 'a t -> 'a Js.undefined +``` +`peekUndefined q` returns `undefined` if not found +``` +val peekExn : 'a t -> 'a +``` +`peekExn q` +**raise** an exception if `q` is empty +``` +val pop : 'a t -> 'a option +``` +`pop q` removes and returns the first element in queue `q`. +``` +val popUndefined : 'a t -> 'a Js.undefined +``` +`popUndefined q` removes and returns the first element in queue `q`. it will return undefined if it is already empty +``` +val popExn : 'a t -> 'a +``` +`popExn q` +**raise** an exception if `q` is empty +``` +val copy : 'a t -> 'a t +``` +`copy q` +returns a fresh queue +``` +val size : 'a t -> int +``` +returns the number of elements in a queue. +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +``` +val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> unit) -> unit +``` +`forEach q f` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. +``` +val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b +``` +`reduce q accu f` is equivalent to `List.reduce l accu f`, where `l` is the list of `q`'s elements. The queue remains unchanged. +``` +val transfer : 'a t -> 'a t -> unit +``` +`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `forEach (fun x -> add x q2) q1; clear q1`, but runs in constant time. +``` +val toArray : 'a t -> 'a array +``` +First added will be in the beginning of the array \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableSet-Int.md b/docs/api/melange/Belt-MutableSet-Int.md new file mode 100644 index 000000000..0c2a24edd --- /dev/null +++ b/docs/api/melange/Belt-MutableSet-Int.md @@ -0,0 +1,149 @@ +# Module `MutableSet.Int` +Specalized when key type is `int`, more efficient than the generic type +This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. +It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) +**See** [`Belt.MutableSet`](./Belt-MutableSet.md) +``` +type value = int +``` +The type of the set elements. +``` +type t +``` +The type of sets. +``` +val make : unit -> t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val copy : t -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> unit +``` +``` +val addCheck : t -> value -> bool +``` +``` +val mergeMany : t -> value array -> unit +``` +``` +val remove : t -> value -> unit +``` +``` +val removeCheck : t -> value -> bool +``` +``` +val removeMany : t -> value array -> unit +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +``` +val cmp : t -> t -> int +``` +``` +val eq : t -> t -> bool +``` +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +In increasing order +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order with respect +``` +val toArray : t -> value array +``` +In increasing order with respect +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split s key` return a fresh copy of each +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableSet-String.md b/docs/api/melange/Belt-MutableSet-String.md new file mode 100644 index 000000000..2782f17a9 --- /dev/null +++ b/docs/api/melange/Belt-MutableSet-String.md @@ -0,0 +1,149 @@ +# Module `MutableSet.String` +Specalized when key type is `string`, more efficient than the generic type +This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. +It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) +**See** [`Belt.MutableSet`](./Belt-MutableSet.md) +``` +type value = string +``` +The type of the set elements. +``` +type t +``` +The type of sets. +``` +val make : unit -> t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val copy : t -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> unit +``` +``` +val addCheck : t -> value -> bool +``` +``` +val mergeMany : t -> value array -> unit +``` +``` +val remove : t -> value -> unit +``` +``` +val removeCheck : t -> value -> bool +``` +``` +val removeMany : t -> value array -> unit +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +``` +val cmp : t -> t -> int +``` +``` +val eq : t -> t -> bool +``` +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +In increasing order +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order with respect +``` +val toArray : t -> value array +``` +In increasing order with respect +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split s key` return a fresh copy of each +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableSet.md b/docs/api/melange/Belt-MutableSet.md new file mode 100644 index 000000000..3c76a34cc --- /dev/null +++ b/docs/api/melange/Belt-MutableSet.md @@ -0,0 +1,171 @@ +# Module `Belt.MutableSet` +[`Belt.MutableSet`](#) +The top level provides generic **mutable** set operations. +It also has two specialized inner modules [`Belt.MutableSet.Int`](./Belt-MutableSet-Int.md) and [`Belt.MutableSet.String`](./Belt-MutableSet-String.md) +A *mutable* sorted set module which allows customize *compare* behavior. +Same as Belt.Set, but mutable. +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type +``` +type ('k, 'id) t +``` +``` +type ('k, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'k) +``` +``` +val make : id:('value, 'id) id -> ('value, 'id) t +``` +``` +val fromArray : 'k array -> id:('k, 'id) id -> ('k, 'id) t +``` +``` +val fromSortedArrayUnsafe : + 'value array -> + id:('value, 'id) id -> + ('value, 'id) t +``` +``` +val copy : ('k, 'id) t -> ('k, 'id) t +``` +``` +val isEmpty : (_, _) t -> bool +``` +``` +val has : ('value, _) t -> 'value -> bool +``` +``` +val add : ('value, 'id) t -> 'value -> unit +``` +``` +val addCheck : ('value, 'id) t -> 'value -> bool +``` +``` +val mergeMany : ('value, 'id) t -> 'value array -> unit +``` +``` +val remove : ('value, 'id) t -> 'value -> unit +``` +``` +val removeCheck : ('value, 'id) t -> 'value -> bool +``` +``` +val removeMany : ('value, 'id) t -> 'value array -> unit +``` +``` +val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +``` +val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +``` +val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +``` +val subset : ('value, 'id) t -> ('value, 'id) t -> bool +``` +``` +val cmp : ('value, 'id) t -> ('value, 'id) t -> int +``` +``` +val eq : ('value, 'id) t -> ('value, 'id) t -> bool +``` +``` +val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('value, 'id) t -> ('value -> unit) -> unit +``` +`forEach m f` applies `f` in turn to all elements of `m`. In increasing order +``` +val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a +``` +In increasing order. +``` +val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : ('value, 'id) t -> ('value -> bool) -> bool +``` +`every s p` checks if all elements of the set satisfy the predicate `p`. Order unspecified +``` +val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : ('value, 'id) t -> ('value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. +``` +val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t +``` +``` +val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t +``` +`keep s p` returns the set of all elements in `s` that satisfy predicate `p`. +``` +val partitionU : + ('value, 'id) t -> + ('value -> bool) Js.Fn.arity1 -> + ('value, 'id) t * ('value, 'id) t +``` +``` +val partition : + ('value, 'id) t -> + ('value -> bool) -> + ('value, 'id) t * ('value, 'id) t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. +``` +val size : ('value, 'id) t -> int +``` +``` +val toList : ('value, 'id) t -> 'value list +``` +In increasing order +``` +val toArray : ('value, 'id) t -> 'value array +``` +In increasing order +``` +val minimum : ('value, 'id) t -> 'value option +``` +``` +val minUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val maximum : ('value, 'id) t -> 'value option +``` +``` +val maxUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val get : ('value, 'id) t -> 'value -> 'value option +``` +``` +val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined +``` +``` +val getExn : ('value, 'id) t -> 'value -> 'value +``` +``` +val split : + ('value, 'id) t -> + 'value -> + (('value, 'id) t * ('value, 'id) t) * bool +``` +`split s x` returns a triple `((l, r), present)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. `l,r` are freshly made, no sharing with `s` +``` +val checkInvariantInternal : (_, _) t -> unit +``` +**raise** when invariant is not held \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableStack.md b/docs/api/melange/Belt-MutableStack.md new file mode 100644 index 000000000..a40dcaf0c --- /dev/null +++ b/docs/api/melange/Belt-MutableStack.md @@ -0,0 +1,54 @@ +# Module `Belt.MutableStack` +[`Belt.MutableStack`](#) +An FILO(first in last out) stack data structure +First in last out stack. +This module implements stacks, with in-place modification. +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +returns a new stack, initially empty. +``` +val clear : 'a t -> unit +``` +Discard all elements from the stack. +``` +val copy : 'a t -> 'a t +``` +`copy x` O(1) operation, return a new stack +``` +val push : 'a t -> 'a -> unit +``` +``` +val popUndefined : 'a t -> 'a Js.undefined +``` +``` +val pop : 'a t -> 'a option +``` +``` +val topUndefined : 'a t -> 'a Js.undefined +``` +``` +val top : 'a t -> 'a option +``` +``` +val isEmpty : 'a t -> bool +``` +``` +val size : 'a t -> int +``` +``` +val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> unit) -> unit +``` +``` +val dynamicPopIterU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val dynamicPopIter : 'a t -> ('a -> unit) -> unit +``` +`dynamicPopIter s f ` apply `f` to each element of `s`. The item is poped before applying `f`, `s` will be empty after this opeartion. This function is useful for worklist algorithm \ No newline at end of file diff --git a/docs/api/melange/Belt-Option.md b/docs/api/melange/Belt-Option.md new file mode 100644 index 000000000..2fd13b0d9 --- /dev/null +++ b/docs/api/melange/Belt-Option.md @@ -0,0 +1,158 @@ +# Module `Belt.Option` +[`Belt.Option`](#) +Utilities for option data type. +[`Belt.Option`](#) +Utilities for option data type +``` +val keepU : 'a option -> ('a -> bool) Js.Fn.arity1 -> 'a option +``` +Uncurried version of `keep` +``` +val keep : 'a option -> ('a -> bool) -> 'a option +``` +`keep optionValue p` +If `optionValue` is `Some value` and `p value = true`, it returns `Some value`; otherwise returns `None` +```ocaml + keep (Some 10)(fun x -> x > 5);; (* returns [Some 10] *) + keep (Some 4)(fun x -> x > 5);; (* returns [None] *) + keep None (fun x -> x > 5);; (* returns [None] *) +``` +``` +val forEachU : 'a option -> ('a -> unit) Js.Fn.arity1 -> unit +``` +Uncurried version of `forEach` +``` +val forEach : 'a option -> ('a -> unit) -> unit +``` +`forEach optionValue f` +If `optionValue` is `Some value`, it calls `f value`; otherwise returns `()` +```ocaml + forEach (Some "thing")(fun x -> Js.log x);; (* logs "thing" *) + forEach None (fun x -> Js.log x);; (* returns () *) +``` +``` +val getExn : 'a option -> 'a +``` +`getExn optionalValue` Returns `value` if `optionalValue` is `Some value`, otherwise raises `getExn` +```ocaml + getExn (Some 3) = 3;; + getExn None (* Raises getExn error *) +``` +``` +val getUnsafe : 'a option -> 'a +``` +`getUnsafe x` returns x This is an unsafe operation, it assumes x is neither not None or (Some (None .. )) +``` +val mapWithDefaultU : 'a option -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b +``` +Uncurried version of `mapWithDefault` +``` +val mapWithDefault : 'a option -> 'b -> ('a -> 'b) -> 'b +``` +`mapWithDefault optionValue default f` +If `optionValue` is `Some value`, returns `f value`; otherwise returns `default` +```ocaml + mapWithDefault (Some 3) 0 (fun x -> x + 5) = 8;; + mapWithDefault None 0 (fun x -> x + 5) = 0;; +``` +``` +val mapU : 'a option -> ('a -> 'b) Js.Fn.arity1 -> 'b option +``` +Uncurried version of `map` +``` +val map : 'a option -> ('a -> 'b) -> 'b option +``` +`map optionValue f` +If `optionValue` is `Some value`, returns `Some (f value)`; otherwise returns `None` +```ocaml + map (Some 3) (fun x -> x * x) = (Some 9);; + map None (fun x -> x * x) = None;; +``` +``` +val flatMapU : 'a option -> ('a -> 'b option) Js.Fn.arity1 -> 'b option +``` +Uncurried version of `flatMap` +``` +val flatMap : 'a option -> ('a -> 'b option) -> 'b option +``` +`flatMap optionValue f` +If `optionValue` is `Some value`, returns `f value`; otherwise returns `None` The function `f` must have a return type of `'a option` +```ocaml + let f (x : float) = + if x >= 0.0 then + Some (sqrt x) + else + None;; + + flatMap (Some 4.0) f = Some 2.0;; + flatMap (Some (-4.0)) f = None;; + flatMap None f = None;; +``` +``` +val getWithDefault : 'a option -> 'a -> 'a +``` +`getWithDefault optionalValue default` +If `optionalValue` is `Some value`, returns `value`, otherwise `default` +```ocaml + getWithDefault (Some 1812) 1066 = 1812;; + getWithDefault None 1066 = 1066;; +``` +``` +val orElse : 'a option -> 'a option -> 'a option +``` +`orElse optionalValue otherOptional` +If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOptional` +```ocaml + orElse (Some 1812) (Some 1066) = Some 1812;; + orElse None (Some 1066) = Some 1066;; + orElse None None = None;; +``` +``` +val isSome : 'a option -> bool +``` +Returns `true` if the argument is `Some value`, `false` otherwise +``` +val isNone : 'a option -> bool +``` +Returns `true` if the argument is `None`, `false` otherwise +``` +val eqU : 'a option -> 'b option -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +Uncurried version of `eq` +``` +val eq : 'a option -> 'b option -> ('a -> 'b -> bool) -> bool +``` +`eq optValue1 optvalue2 predicate` +Evaluates two optional values for equality with respect to a predicate function. +If both `optValue1` and `optValue2` are `None`, returns `true`. +If one of the arguments is `Some value` and the other is `None`, returns `false` +If arguments are `Some value1` and `Some value2`, returns the result of `predicate value1 value2`; the `predicate` function must return a `bool` +```ocaml + let clockEqual = (fun a b -> a mod 12 = b mod 12);; + eq (Some 3) (Some 15) clockEqual = true;; + eq (Some 3) None clockEqual = false;; + eq None (Some 3) clockEqual = false;; + eq None None clockEqual = true;; +``` +``` +val cmpU : 'a option -> 'b option -> ('a -> 'b -> int) Js.Fn.arity2 -> int +``` +Uncurried version of `cmp` +``` +val cmp : 'a option -> 'b option -> ('a -> 'b -> int) -> int +``` +`cmp optValue1 optvalue2 comparisonFcn` +Compares two optional values with respect to a comparison function +If both `optValue1` and `optValue2` are `None`, returns 0. +If the first argument is `Some value1` and the second is `None`, returns 1 (something is greater than nothing) +If the first argument is `None` and the second is `Some value2`, returns \-1 (nothing is less than something) +If the arguments are `Some value1` and `Some value2`, returns the result of `comparisonFcn value1 value2`; `comparisonFcn` takes two arguments and returns \-1 if the first argument is less than the second, 0 if the arguments are equal, and 1 if the first argument is greater than the second. +```ocaml + let clockCompare = fun a b -> compare (a mod 12) (b mod 12);; + cmp (Some 3) (Some 15) clockCompare = 0;; + cmp (Some 3) (Some 14) clockCompare = 1;; + cmp (Some 2) (Some 15) clockCompare = -1;; + cmp None (Some 15) clockCompare = -1;; + cmp (Some 14) None clockCompare = 1;; + cmp None None clockCompare = 0;; +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Range.md b/docs/api/melange/Belt-Range.md new file mode 100644 index 000000000..d9f449398 --- /dev/null +++ b/docs/api/melange/Belt-Range.md @@ -0,0 +1,46 @@ +# Module `Belt.Range` +[`Belt.Range`](#) +Utilities for a closed range `(from, start)` +A small module to provide a inclusive range operations `[start, finsish]`, it use a for-loop internally instead of creating an array +``` +val forEachU : int -> int -> (int -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : int -> int -> (int -> unit) -> unit +``` +`forEach start finish action` +equivalent to `Belt.Array.(forEach (range start finish) action)` +``` +val everyU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : int -> int -> (int -> bool) -> bool +``` +`every start finish p` +equivalent to `Belt.Array.(every (range start finish) p )` +``` +val everyByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val everyBy : int -> int -> step:int -> (int -> bool) -> bool +``` +`everyBy start finish ~step p` +**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) +equivalent to `Belt.Array.(every (rangeBy start finish ~step) p)` +``` +val someU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : int -> int -> (int -> bool) -> bool +``` +`some start finish p` +equivalent to `Belt.Array.(some (range start finish) p)` +``` +val someByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val someBy : int -> int -> step:int -> (int -> bool) -> bool +``` +`someBy start finish ~step p` +**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) +equivalent to `Belt.Array.(some (rangeBy start finish ~step) p)` \ No newline at end of file diff --git a/docs/api/melange/Belt-Result.md b/docs/api/melange/Belt-Result.md new file mode 100644 index 000000000..8ac52a7b6 --- /dev/null +++ b/docs/api/melange/Belt-Result.md @@ -0,0 +1,140 @@ +# Module `Belt.Result` +[`Belt.Result`](#) +Utilities for result data type. +`Belt.Result` is a data type with two variants: `Ok` and `Error`. Each of these variants can contain data, and those two pieces of data need not have the same data type. `Belt.Result` is useful when you need to not only determine whether some data is valid or not (use `Belt.Option` for that), but also keep information about the invalid data. +In the examples, we presume the existence of two variables: +```ocaml +let good = Ok 42 +let bad = Error "Invalid data" +``` +``` +type ('a, 'b) t = ('a, 'b) result = +``` +``` +| Ok of 'a +``` +``` +| Error of 'b +``` +``` + +``` +``` +val getExn : ('a, 'b) t -> 'a +``` +`getExn res` +when `res` is `Ok n`, returns `n` when `res` is `Error m`, **raise** an exception +```ocaml + getExn good = 42;; + getExn bad;; (* raises exception *) +``` +``` +val mapWithDefaultU : ('a, 'c) t -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b +``` +``` +val mapWithDefault : ('a, 'c) t -> 'b -> ('a -> 'b) -> 'b +``` +`mapWithDefault res default f` +When `res` is `Ok n`, returns `f n`, otherwise `default`. +```ocaml + mapWithDefault good 0 (fun x -> x / 2) = 21 + mapWithDefault bad 0 (fun x -> x / 2) = 0 +``` +``` +val mapU : ('a, 'c) t -> ('a -> 'b) Js.Fn.arity1 -> ('b, 'c) t +``` +``` +val map : ('a, 'c) t -> ('a -> 'b) -> ('b, 'c) t +``` +`map res f` +When `res` is `Ok n`, returns `Ok (f n)`. Otherwise returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns an ordinary value. +```ocaml + let f x = sqrt (float_of_int x) + map (Ok 64) f = Ok 8.0 + map (Error "Invalid data") f = Error "Invalid data" +``` +``` +val flatMapU : ('a, 'c) t -> ('a -> ('b, 'c) t) Js.Fn.arity1 -> ('b, 'c) t +``` +``` +val flatMap : ('a, 'c) t -> ('a -> ('b, 'c) t) -> ('b, 'c) t +``` +`flatMap res f` +When `res` is `Ok n`, returns `f n`. Otherwise, returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns a `Belt.Result`. +```ocaml +let recip x = + if x != 0.0 + then + Ok (1.0 /. x) + else + Error "Divide by zero" + + flatMap (Ok 2.0) recip = Ok 0.5 + flatMap (Ok 0.0) recip = Error "Divide by zero" + flatMap (Error "Already bad") recip = Error "Already bad" +``` +``` +val getWithDefault : ('a, 'b) t -> 'a -> 'a +``` +`getWithDefault res defaultValue` +if `res` is `Ok n`, returns `n`, otherwise `default` +```ocaml + getWithDefault (Ok 42) 0 = 42 + getWithDefault (Error "Invalid Data") = 0 +``` +``` +val isOk : ('a, 'b) t -> bool +``` +`isOk res` +Returns `true` if `res` is of the form `Ok n`, `false` if it is the `Error e` variant. +``` +val isError : ('a, 'b) t -> bool +``` +`isError res` +Returns `true` if `res` is of the form `Error e`, `false` if it is the `Ok n` variant. +``` +val eqU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) -> bool +``` +`eq res1 res2 f` +Determine if two `Belt.Result` variables are equal with respect to an equality function. If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If one of `res1` and `res2` are of the form `Error e`, return false If both `res1` and `res2` are of the form `Error e`, return true +```ocaml + let good1 = Ok 42 + let good2 = Ok 32 + let bad1 = Error "invalid" + let bad2 = Error "really invalid" + + let mod10equal a b = + a mod 10 == b mod 10 + + eq good1 good2 mod10equal = true + eq good1 bad1 mod10equal = false + eq bad2 good2 mod10equal = false + eq bad1 bad2 mod10equal = true +``` +``` +val cmpU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) -> int +``` +`cmp res1 res2 f` +Compare two `Belt.Result` variables with respect to a comparison function. The comparison function returns \-1 if the first variable is "less than" the second, 0 if the two variables are equal, and 1 if the first is "greater than" the second. +If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If `res1` is of the form `Error e` and `res2` of the form `Ok n`, return \-1 (nothing is less than something) If `res1` is of the form `Ok n` and `res2` of the form `Error e`, return 1 (something is greater than nothing) If both `res1` and `res2` are of the form `Error e`, return 0 (equal) +```ocaml + let good1 = Ok 59 + let good2 = Ok 37 + let bad1 = Error "invalid" + let bad2 = Error "really invalid" + + let mod10cmp a b = + Pervasives.compare (a mod 10) (b mod 10) + + cmp (Ok 39) (Ok 57) mod10cmp = 1 + cmp (Ok 57) (Ok 39) mod10cmp = -1 + cmp (Ok 39) (Error "y") mod10cmp = 1 + cmp (Error "x") (Ok 57) mod10cmp = -1 + cmp (Error "x") (Error "y") mod10cmp = 0 +``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Set-Dict.md b/docs/api/melange/Belt-Set-Dict.md new file mode 100644 index 000000000..24342585f --- /dev/null +++ b/docs/api/melange/Belt-Set-Dict.md @@ -0,0 +1,181 @@ +# Module `Set.Dict` +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation +``` +type ('value, 'identity) t +``` +``` +type ('value, 'id) cmp +``` +``` +val empty : ('value, 'id) t +``` +``` +val fromArray : 'value array -> cmp:('value, 'id) cmp -> ('value, 'id) t +``` +``` +val fromSortedArrayUnsafe : 'value array -> ('value, 'id) t +``` +``` +val isEmpty : (_, _) t -> bool +``` +``` +val has : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> bool +``` +``` +val add : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> ('value, 'id) t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. +``` +val mergeMany : + ('value, 'id) t -> + 'value array -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val remove : + ('value, 'id) t -> + 'value -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. +``` +val removeMany : + ('value, 'id) t -> + 'value array -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val union : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val intersect : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val diff : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val subset : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. +``` +val cmp : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. +``` +val eq : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> bool +``` +`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. +``` +val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('value, 'id) t -> ('value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order +``` +val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a +``` +Iterate in increasing order. +``` +val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : ('value, 'id) t -> ('value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. +``` +val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : ('value, 'id) t -> ('value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. +``` +val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t +``` +``` +val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t +``` +`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. +``` +val partitionU : + ('value, 'id) t -> + ('value -> bool) Js.Fn.arity1 -> + ('value, 'id) t * ('value, 'id) t +``` +``` +val partition : + ('value, 'id) t -> + ('value -> bool) -> + ('value, 'id) t * ('value, 'id) t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. +``` +val size : ('value, 'id) t -> int +``` +``` +val toList : ('value, 'id) t -> 'value list +``` +In increasing order +``` +val toArray : ('value, 'id) t -> 'value array +``` +``` +val minimum : ('value, 'id) t -> 'value option +``` +``` +val minUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val maximum : ('value, 'id) t -> 'value option +``` +``` +val maxUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val get : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value option +``` +``` +val getUndefined : + ('value, 'id) t -> + 'value -> + cmp:('value, 'id) cmp -> + 'value Js.undefined +``` +``` +val getExn : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value +``` +``` +val split : + ('value, 'id) t -> + 'value -> + cmp:('value, 'id) cmp -> + (('value, 'id) t * ('value, 'id) t) * bool +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. +``` +val checkInvariantInternal : (_, _) t -> unit +``` +**raise** when invariant is not held \ No newline at end of file diff --git a/docs/api/melange/Belt-Set-Int.md b/docs/api/melange/Belt-Set-Int.md new file mode 100644 index 000000000..4c8f6f545 --- /dev/null +++ b/docs/api/melange/Belt-Set-Int.md @@ -0,0 +1,143 @@ +# Module `Set.Int` +Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) +**See** [`Belt.Set`](./Belt-Set.md) +``` +type value = int +``` +The type of the set elements. +``` +type t +``` +The type of sets. +``` +val empty : t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. +``` +val mergeMany : t -> value array -> t +``` +``` +val remove : t -> value -> t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. +``` +val removeMany : t -> value array -> t +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. +``` +val cmp : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. +``` +val eq : t -> t -> bool +``` +`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order +``` +val toArray : t -> value array +``` +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held \ No newline at end of file diff --git a/docs/api/melange/Belt-Set-String.md b/docs/api/melange/Belt-Set-String.md new file mode 100644 index 000000000..2b2206c01 --- /dev/null +++ b/docs/api/melange/Belt-Set-String.md @@ -0,0 +1,143 @@ +# Module `Set.String` +Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) +**See** [`Belt.Set`](./Belt-Set.md) +``` +type value = string +``` +The type of the set elements. +``` +type t +``` +The type of sets. +``` +val empty : t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. +``` +val mergeMany : t -> value array -> t +``` +``` +val remove : t -> value -> t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. +``` +val removeMany : t -> value array -> t +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. +``` +val cmp : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. +``` +val eq : t -> t -> bool +``` +`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order +``` +val toArray : t -> value array +``` +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held \ No newline at end of file diff --git a/docs/api/melange/Belt-Set.md b/docs/api/melange/Belt-Set.md new file mode 100644 index 000000000..12aec7e95 --- /dev/null +++ b/docs/api/melange/Belt-Set.md @@ -0,0 +1,316 @@ +# Module `Belt.Set` +[`Belt.Set`](#) +The top level provides generic **immutable** set operations. +It also has three specialized inner modules [`Belt.Set.Int`](./Belt-Set-Int.md), [`Belt.Set.String`](./Belt-Set-String.md) and +[`Belt.Set.Dict`](./Belt-Set-Dict.md): This module separates data from function which is more verbose but slightly more efficient +A *immutable* sorted set module which allows customize *compare* behavior. +The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. +For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. +Example usage: +```ocaml + module PairComparator = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c + end) + + let mySet = Belt.Set.make ~id:(module PairComparator) + let mySet2 = Belt.Set.add mySet (1, 2) +``` +The API documentation below will assume a predeclared comparator module for integers, IntCmp +``` +module Int : sig ... end +``` +Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +``` +module String : sig ... end +``` +Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison +``` +module Dict : sig ... end +``` +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation +``` +type ('value, 'identity) t +``` +`('value, 'identity) t` +`'value` is the element type +`'identity` the identity of the collection +``` +type ('value, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'value) +``` +The identity needed for making a set from scratch +``` +val make : id:('value, 'id) id -> ('value, 'id) t +``` +`make ~id` creates a new set by taking in the comparator +```ocaml + let s = make ~id:(module IntCmp) +``` +``` +val fromArray : 'value array -> id:('value, 'id) id -> ('value, 'id) t +``` +`fromArray xs ~id` +```ocaml + toArray (fromArray [1;3;2;4] (module IntCmp)) = [1;2;3;4] +``` +``` +val fromSortedArrayUnsafe : + 'value array -> + id:('value, 'id) id -> + ('value, 'id) t +``` +`fromSortedArrayUnsafe xs ~id` +The same as [`fromArray`](./#val-fromArray) except it is after assuming the input array `x` is already sorted +**Unsafe** +``` +val isEmpty : (_, _) t -> bool +``` +```ocaml + isEmpty (fromArray [||] ~id:(module IntCmp)) = true;; + isEmpty (fromArray [|1|] ~id:(module IntCmp)) = true;; +``` +``` +val has : ('value, 'id) t -> 'value -> bool +``` +```ocaml + let v = fromArray [|1;4;2;5|] ~id:(module IntCmp);; + has v 3 = false;; + has v 1 = true;; +``` +``` +val add : ('value, 'id) t -> 'value -> ('value, 'id) t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. +```ocaml + let s0 = make ~id:(module IntCmp);; + let s1 = add s0 1 ;; + let s2 = add s1 2;; + let s3 = add s2 2;; + toArray s0 = [||];; + toArray s1 = [|1|];; + toArray s2 = [|1;2|];; + toArray s3 = [|1;2|];; + s2 == s3;; +``` +``` +val mergeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t +``` +`mergeMany s xs` +Adding each of `xs` to `s`, note unlike [`add`](./#val-add), the reference of return value might be changed even if all values in `xs` exist `s` +``` +val remove : ('value, 'id) t -> 'value -> ('value, 'id) t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|2;3;1;4;5|];; + let s1 = remove s0 1 ;; + let s2 = remove s1 3 ;; + let s3 = remove s2 3 ;; + + toArray s1 = [|2;3;4;5|];; + toArray s2 = [|2;4;5|];; + s2 == s3;; +``` +``` +val removeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t +``` +`removeMany s xs` +Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` +``` +val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +`union s0 s1` +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + toArray (union s0 s1) = [|1;2;3;4;5;6|] +``` +``` +val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +`intersect s0 s1` +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + toArray (intersect s0 s1) = [|2;3;5|] +``` +``` +val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +`diff s0 s1` +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + toArray (diff s0 s1) = [|6|];; + toArray (diff s1 s0) = [|1;4|];; +``` +``` +val subset : ('value, 'id) t -> ('value, 'id) t -> bool +``` +`subset s0 s1` +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + let s2 = intersect s0 s1;; + subset s2 s0 = true;; + subset s2 s1 = true;; + subset s1 s0 = false;; +``` +``` +val cmp : ('value, 'id) t -> ('value, 'id) t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. It compare `size` first and then iterate over each element following the order of elements +``` +val eq : ('value, 'id) t -> ('value, 'id) t -> bool +``` +`eq s0 s1` +returns true if toArray s0 = toArray s1 +``` +val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('value, 'id) t -> ('value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let acc = ref [] ;; + forEach s0 (fun x -> acc := x !acc);; + !acc = [6;5;3;2];; +``` +``` +val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a +``` +In increasing order. +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + reduce s0 [] Belt.List.add = [6;5;3;2];; +``` +``` +val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : ('value, 'id) t -> ('value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. +``` +val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : ('value, 'id) t -> ('value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. +``` +val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t +``` +``` +val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t +``` +`keep m p` returns the set of all elements in `s` that satisfy predicate `p`. +``` +val partitionU : + ('value, 'id) t -> + ('value -> bool) Js.Fn.arity1 -> + ('value, 'id) t * ('value, 'id) t +``` +``` +val partition : + ('value, 'id) t -> + ('value -> bool) -> + ('value, 'id) t * ('value, 'id) t +``` +`partition m p` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. +``` +val size : ('value, 'id) t -> int +``` +`size s` +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + size s0 = 4;; +``` +``` +val toArray : ('value, 'id) t -> 'value array +``` +`toArray s0` +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + toArray s0 = [|2;3;5;6|];; +``` +``` +val toList : ('value, 'id) t -> 'value list +``` +In increasing order +**See** [`toArray`](./#val-toArray) +``` +val minimum : ('value, 'id) t -> 'value option +``` +`minimum s0` +returns the minimum element of the collection, None if it is empty +``` +val minUndefined : ('value, 'id) t -> 'value Js.undefined +``` +`minUndefined s0` +returns the minimum element of the collection, undefined if it is empty +``` +val maximum : ('value, 'id) t -> 'value option +``` +`maximum s0` +returns the maximum element of the collection, None if it is empty +``` +val maxUndefined : ('value, 'id) t -> 'value Js.undefined +``` +`maxUndefined s0` +returns the maximum element of the collection, undefined if it is empty +``` +val get : ('value, 'id) t -> 'value -> 'value option +``` +`get s0 k` +returns the reference of the value k' which is equivalent to k using the comparator specifiecd by this collection, None if it does not exist +``` +val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined +``` +**See** [`get`](./#val-get) +``` +val getExn : ('value, 'id) t -> 'value -> 'value +``` +**See** [`get`](./#val-get) +**raise** if not exist +``` +val split : + ('value, 'id) t -> + 'value -> + (('value, 'id) t * ('value, 'id) t) * bool +``` +`split set ele` +returns a tuple ((smaller, larger), present), present is true when ele exist in set +Below are operations only when better performance needed, it is still safe API but more verbose. More API will be exposed by needs +``` +val getData : ('value, 'id) t -> ('value, 'id) Belt__.Belt_SetDict.t +``` +`getData s0` +**Advanced usage only** +returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing +``` +val getId : ('value, 'id) t -> ('value, 'id) id +``` +`getId s0` +**Advanced usage only** +returns the identity of s0 +``` +val packIdData : + id:('value, 'id) id -> + data:('value, 'id) Belt__.Belt_SetDict.t -> + ('value, 'id) t +``` +`packIdData ~id ~data` +**Advanced usage only** +returns the packed collection \ No newline at end of file diff --git a/docs/api/melange/Belt-SortArray-Int.md b/docs/api/melange/Belt-SortArray-Int.md new file mode 100644 index 000000000..bbb11f8f2 --- /dev/null +++ b/docs/api/melange/Belt-SortArray-Int.md @@ -0,0 +1,29 @@ +# Module `SortArray.Int` +Specalized when key type is `int`, more efficient than the generic type +This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined +``` +type element = int +``` +``` +val strictlySortedLength : element array -> int +``` +The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed +returns \+n means increasing order -n means negative order +``` +val isSorted : element array -> bool +``` +`sorted xs` return true if `xs` is in non strict increasing order +``` +val stableSortInPlace : element array -> unit +``` +The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed +``` +val stableSort : element array -> element array +``` +The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed +``` +val binarySearch : element array -> element -> int +``` +If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. +If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` \ No newline at end of file diff --git a/docs/api/melange/Belt-SortArray-String.md b/docs/api/melange/Belt-SortArray-String.md new file mode 100644 index 000000000..7393c633f --- /dev/null +++ b/docs/api/melange/Belt-SortArray-String.md @@ -0,0 +1,29 @@ +# Module `SortArray.String` +Specalized when key type is `string`, more efficient than the generic type +This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined +``` +type element = string +``` +``` +val strictlySortedLength : element array -> int +``` +The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed +returns \+n means increasing order -n means negative order +``` +val isSorted : element array -> bool +``` +`sorted xs` return true if `xs` is in non strict increasing order +``` +val stableSortInPlace : element array -> unit +``` +The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed +``` +val stableSort : element array -> element array +``` +The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed +``` +val binarySearch : element array -> element -> int +``` +If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. +If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` \ No newline at end of file diff --git a/docs/api/melange/Belt-SortArray.md b/docs/api/melange/Belt-SortArray.md new file mode 100644 index 000000000..e65ff2cb8 --- /dev/null +++ b/docs/api/melange/Belt-SortArray.md @@ -0,0 +1,64 @@ +# Module `Belt.SortArray` +[`Belt.SortArray`](#) +The top level provides some generic sort related utilities. +It also has two specialized inner modules [`Belt.SortArray.Int`](./Belt-SortArray-Int.md) and [`Belt.SortArray.String`](./Belt-SortArray-String.md) +A module for Array sort relevant utiliites +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type +``` +val strictlySortedLengthU : 'a array -> ('a -> 'a -> bool) Js.Fn.arity2 -> int +``` +``` +val strictlySortedLength : 'a array -> ('a -> 'a -> bool) -> int +``` +`strictlySortedLenght xs cmp` return `+n` means increasing order `-n` means negative order +```ocaml + strictlySortedLength [|1;2;3;4;3|] (fun x y -> x < y) = 4;; + strictlySortedLength [||] (fun x y -> x < y) = 0;; + strictlySortedLength [|1|] (fun x y -> x < y) = 1;; + strictlySortedLength [|4;3;2;1|] (fun x y -> x < y) = -4;; +``` +``` +val isSortedU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> bool +``` +``` +val isSorted : 'a array -> ('a -> 'a -> int) -> bool +``` +`isSorted arr cmp` +returns true if array is increasingly sorted (equal is okay ) isSorted \[\|1;1;2;3;4\|\] (fun x y -\> compare x y) = true +``` +val stableSortInPlaceByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> unit +``` +``` +val stableSortInPlaceBy : 'a array -> ('a -> 'a -> int) -> unit +``` +`stableSortBy xs cmp` +Sort xs in place using comparator `cmp`, the stable means if the elements are equal, their order will be preserved +``` +val stableSortByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a array +``` +``` +val stableSortBy : 'a array -> ('a -> 'a -> int) -> 'a array +``` +`stableSort xs cmp` +returns a fresh array +The same as [`stableSortInPlaceBy`](./#val-stableSortInPlaceBy) except that `xs` is not modified +``` +val binarySearchByU : 'a array -> 'a -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val binarySearchBy : 'a array -> 'a -> ('a -> 'a -> int) -> int +``` +If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. +If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` +```ocaml + binarySearchBy [|1;2;3;4;33;35;36|] 33 = 4;; + lnot (binarySearchBy [|1;3;5;7|] 4) = 2;; +``` \ No newline at end of file diff --git a/docs/api/melange/Belt.md b/docs/api/melange/Belt.md new file mode 100644 index 000000000..4bfdfcbc4 --- /dev/null +++ b/docs/api/melange/Belt.md @@ -0,0 +1,128 @@ +# Module `Belt` +A stdlib shipped with Melange +This stdlib is still in *beta* but we encourage you to try it out and give us feedback. +**Motivation** +The motivation for creating such library is to provide Melange users a better end-to-end user experience, since the original OCaml stdlib was not written with JS in mind. Below is a list of areas this lib aims to improve: +0. Consistency in name convention: camlCase, and arguments order +1. Exception thrown functions are all suffixed with *Exn*, e.g, *getExn* +2. Better performance and smaller code size running on JS platform +**Name Convention** +For higher order functions, it will be suffixed **U** if it takes uncurried callback. +```ocaml + val forEach : 'a t -> ('a -> unit) -> unit + val forEachU : 'a t -> ('a -> unit [\@u]) -> unit +``` +In general, uncurried version will be faster, but it may be less familiar to people who have a background in functional programming. +**A special encoding for collection safety** +When we create a collection library for a custom data type we need a way to provide a comparator function. Take *Set* for example, suppose its element type is a pair of ints, it needs a custom *compare* function that takes two tuples and returns their order. The *Set* could not just be typed as ` Set.t (int * int) `, its customized *compare* function needs to manifest itself in the signature, otherwise, if the user creates another customized *compare* function, the two collection could mix which would result in runtime error. +The original OCaml stdlib solved the problem using *functor* which creates a big closure at runtime and makes dead code elimination much harder. We use a phantom type to solve the problem: +```ocaml + module Comparable1 = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c + end) + +let mySet1 = Belt.Set.make ~id:(module Comparable1) + +module Comparable2 = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c +end) + +let mySet2 = Belt.Set.make ~id:(module Comparable2) +``` +Here, the compiler would infer `mySet1` and `mySet2` having different type, so e.g. a \`merge\` operation that tries to merge these two sets will correctly fail. +```ocaml + val mySet1 : ((int * int), Comparable1.identity) t + val mySet2 : ((int * int), Comparable2.identity) t +``` +`Comparable1.identity` and `Comparable2.identity` are not the same using our encoding scheme. +**Collection Hierarchy** +In general, we provide a generic collection module, but also create specialized modules for commonly used data type. Take *Belt.Set* for example, we provide: +```ocaml + Belt.Set + Belt.Set.Int + Belt.Set.String +``` +The specialized modules *Belt.Set.Int*, *Belt.Set.String* are in general more efficient. +Currently, both *Belt\_Set* and *Belt.Set* are accessible to users for some technical reasons, we **strongly recommend** users stick to qualified import, *Belt.Set*, we may hide the internal, *i.e*, *Belt\_Set* in the future +``` +module Id : sig ... end +``` +[`Belt.Id`](./Belt-Id.md) +``` +module Array : sig ... end +``` +[`Belt.Array`](./Belt-Array.md) +``` +module SortArray : sig ... end +``` +[`Belt.SortArray`](./Belt-SortArray.md) +``` +module MutableQueue : sig ... end +``` +[`Belt.MutableQueue`](./Belt-MutableQueue.md) +``` +module MutableStack : sig ... end +``` +[`Belt.MutableStack`](./Belt-MutableStack.md) +``` +module List : sig ... end +``` +[`Belt.List`](./Belt-List.md) +``` +module Range : sig ... end +``` +[`Belt.Range`](./Belt-Range.md) +``` +module Set : sig ... end +``` +[`Belt.Set`](./Belt-Set.md) +``` +module Map : sig ... end +``` +[`Belt.Map`](./Belt-Map.md), +``` +module MutableSet : sig ... end +``` +[`Belt.MutableSet`](./Belt-MutableSet.md) +``` +module MutableMap : sig ... end +``` +[`Belt.MutableMap`](./Belt-MutableMap.md) +``` +module HashSet : sig ... end +``` +[`Belt.HashSet`](./Belt-HashSet.md) +``` +module HashMap : sig ... end +``` +[`Belt.HashMap`](./Belt-HashMap.md) +``` +module Option : sig ... end +``` +[`Belt.Option`](./Belt-Option.md) +[`Belt.Result`](./Belt-Result.md) +Utilities for result data type. +``` +module Result : sig ... end +``` +[`Belt.Result`](./Belt-Result.md) +[`Belt.Int`](./Belt-Int.md) +Utilities for Int. +``` +module Int : sig ... end +``` +[`Belt.Int`](./Belt-Int.md) Utililites for Int +[`Belt.Float`](./Belt-Float.md) +Utilities for Float. +``` +module Float : sig ... end +``` +[`Belt.Float`](./Belt-Float.md) Utililites for Float \ No newline at end of file diff --git a/docs/api/melange/Dom-Storage.md b/docs/api/melange/Dom-Storage.md new file mode 100644 index 000000000..74141fea8 --- /dev/null +++ b/docs/api/melange/Dom-Storage.md @@ -0,0 +1,28 @@ +# Module `Dom.Storage` +``` +type t +``` +``` +val getItem : string -> t -> string option +``` +``` +val setItem : string -> string -> t -> unit +``` +``` +val removeItem : string -> t -> unit +``` +``` +val clear : t -> unit +``` +``` +val key : int -> t -> string option +``` +``` +val length : t -> int +``` +``` +val localStorage : t +``` +``` +val sessionStorage : t +``` \ No newline at end of file diff --git a/docs/api/melange/Dom.md b/docs/api/melange/Dom.md new file mode 100644 index 000000000..780013266 --- /dev/null +++ b/docs/api/melange/Dom.md @@ -0,0 +1,839 @@ +# Module `Dom` +``` +type _baseClass +``` +``` +type animation +``` +``` +type cssStyleDeclaration +``` +``` +type cssStyleSheet +``` +``` +type 'a eventTarget_like +``` +``` +type eventTarget = _baseClass eventTarget_like +``` +``` +type _messagePort +``` +``` +type messagePort = _messagePort eventTarget_like +``` +``` +type _serviceWorker +``` +``` +type serviceWorker = _serviceWorker eventTarget_like +``` +``` +type _worker +``` +``` +type worker = _worker eventTarget_like +``` +``` +type 'a _workerGlobalScope +``` +``` +type workerGlobalScope = _baseClass _workerGlobalScope eventTarget_like +``` +``` +type _dedicatedWorkerGlobalScope +``` +``` +type dedicatedWorkerGlobalScope = + _dedicatedWorkerGlobalScope _workerGlobalScope eventTarget_like +``` +``` +type _serviceWorkerGlobalScope +``` +``` +type serviceWorkerGlobalScope = + _serviceWorkerGlobalScope _workerGlobalScope eventTarget_like +``` +``` +type _sharedWorkerGlobalScope +``` +``` +type sharedWorkerGlobalScope = + _sharedWorkerGlobalScope _workerGlobalScope eventTarget_like +``` +``` +type 'a _node +``` +``` +type 'a node_like = 'a _node eventTarget_like +``` +``` +type node = _baseClass node_like +``` +``` +type _attr +``` +``` +type attr = _attr node_like +``` +``` +type 'a _characterData +``` +``` +type 'a characterData_like = 'a _characterData node_like +``` +``` +type characterData = _baseClass characterData_like +``` +``` +type _cdataSection +``` +``` +type cdataSection = _cdataSection characterData_like +``` +``` +type _comment +``` +``` +type comment = _comment characterData_like +``` +``` +type 'a _document +``` +``` +type 'a document_like = 'a _document node_like +``` +``` +type document = _baseClass document_like +``` +``` +type _documentFragment +``` +``` +type documentFragment = _documentFragment node_like +``` +``` +type _documentType +``` +``` +type documentType = _documentType node_like +``` +``` +type domImplementation +``` +``` +type 'a _element +``` +``` +type 'a element_like = 'a _element node_like +``` +``` +type element = _baseClass element_like +``` +``` +type htmlCollection +``` +``` +type htmlFormControlsCollection +``` +``` +type htmlOptionsCollection +``` +``` +type intersectionObserver +``` +``` +type intersectionObserverEntry +``` +``` +type mutationObserver +``` +``` +type mutationRecord +``` +``` +type performanceObserver +``` +``` +type performanceObserverEntryList +``` +``` +type reportingObserver +``` +``` +type reportingObserverOptions +``` +``` +type resizeObserver +``` +``` +type resizeObserverEntry +``` +``` +type namedNodeMap +``` +``` +type nodeList +``` +``` +type radioNodeList +``` +``` +type processingInstruction +``` +``` +type _shadowRoot +``` +``` +type shadowRoot = _shadowRoot node_like +``` +``` +type _text +``` +``` +type text = _text characterData_like +``` +``` +type domRect +``` +``` +type dataTransfer +``` +``` +type domStringMap +``` +``` +type history +``` +``` +type _htmlDocument +``` +``` +type htmlDocument = _htmlDocument document_like +``` +``` +type 'a _htmlElement +``` +``` +type 'a htmlElement_like = 'a _htmlElement element_like +``` +``` +type htmlElement = _baseClass htmlElement_like +``` +``` +type _htmlAnchorElement +``` +``` +type htmlAnchorElement = _htmlAnchorElement htmlElement_like +``` +``` +type _htmlAreaElement +``` +``` +type htmlAreaElement = _htmlAreaElement htmlElement_like +``` +``` +type _htmlAudioElement +``` +``` +type htmlAudioElement = _htmlAudioElement htmlElement_like +``` +``` +type _htmlBaseElement +``` +``` +type htmlBaseElement = _htmlBaseElement htmlElement_like +``` +``` +type _htmlBodyElement +``` +``` +type htmlBodyElement = _htmlBodyElement htmlElement_like +``` +``` +type _htmlBrElement +``` +``` +type htmlBrElement = _htmlBrElement htmlElement_like +``` +``` +type _htmlButtonElement +``` +``` +type htmlButtonElement = _htmlButtonElement htmlElement_like +``` +``` +type _htmlCanvasElement +``` +``` +type htmlCanvasElement = _htmlCanvasElement htmlElement_like +``` +``` +type _htmlDataElement +``` +``` +type htmlDataElement = _htmlDataElement htmlElement_like +``` +``` +type _htmlDataListElement +``` +``` +type htmlDataListElement = _htmlDataListElement htmlElement_like +``` +``` +type _htmlDialogElement +``` +``` +type htmlDialogElement = _htmlDialogElement htmlElement_like +``` +``` +type _htmlDivElement +``` +``` +type htmlDivElement = _htmlDivElement htmlElement_like +``` +``` +type _htmlDlistElement +``` +``` +type htmlDlistElement = _htmlDlistElement htmlElement_like +``` +``` +type _htmlEmbedElement +``` +``` +type htmlEmbedElement = _htmlEmbedElement htmlElement_like +``` +``` +type _htmlFieldSetElement +``` +``` +type htmlFieldSetElement = _htmlFieldSetElement htmlElement_like +``` +``` +type _htmlFormElement +``` +``` +type htmlFormElement = _htmlFormElement htmlElement_like +``` +``` +type _htmlHeadElement +``` +``` +type htmlHeadElement = _htmlHeadElement htmlElement_like +``` +``` +type _htmlHeadingElement +``` +``` +type htmlHeadingElement = _htmlHeadingElement htmlElement_like +``` +``` +type _htmlHrElement +``` +``` +type htmlHrElement = _htmlHrElement htmlElement_like +``` +``` +type _htmlHtmlElement +``` +``` +type htmlHtmlElement = _htmlHtmlElement htmlElement_like +``` +``` +type _htmlIframeElement +``` +``` +type htmlIframeElement = _htmlIframeElement htmlElement_like +``` +``` +type _htmlImageElement +``` +``` +type htmlImageElement = _htmlImageElement htmlElement_like +``` +``` +type _htmlInputElement +``` +``` +type htmlInputElement = _htmlInputElement htmlElement_like +``` +``` +type _htmlLabelElement +``` +``` +type htmlLabelElement = _htmlLabelElement htmlElement_like +``` +``` +type _htmlLegendElement +``` +``` +type htmlLegendElement = _htmlLegendElement htmlElement_like +``` +``` +type _htmlLiElement +``` +``` +type htmlLiElement = _htmlLiElement htmlElement_like +``` +``` +type _htmlLinkElement +``` +``` +type htmlLinkElement = _htmlLinkElement htmlElement_like +``` +``` +type _htmlMapElement +``` +``` +type htmlMapElement = _htmlMapElement htmlElement_like +``` +``` +type _htmlMediaElement +``` +``` +type htmlMediaElement = _htmlMediaElement htmlElement_like +``` +``` +type _htmlMenuElement +``` +``` +type htmlMenuElement = _htmlMenuElement htmlElement_like +``` +``` +type _htmlMetaElement +``` +``` +type htmlMetaElement = _htmlMetaElement htmlElement_like +``` +``` +type _htmlMeterElement +``` +``` +type htmlMeterElement = _htmlMeterElement htmlElement_like +``` +``` +type _htmlModElement +``` +``` +type htmlModElement = _htmlModElement htmlElement_like +``` +``` +type _htmlOListElement +``` +``` +type htmlOListElement = _htmlOListElement htmlElement_like +``` +``` +type _htmlObjectElement +``` +``` +type htmlObjectElement = _htmlObjectElement htmlElement_like +``` +``` +type _htmlOptGroupElement +``` +``` +type htmlOptGroupElement = _htmlOptGroupElement htmlElement_like +``` +``` +type _htmlOptionElement +``` +``` +type htmlOptionElement = _htmlOptionElement htmlElement_like +``` +``` +type _htmlOutputElement +``` +``` +type htmlOutputElement = _htmlOutputElement htmlElement_like +``` +``` +type _htmlParagraphElement +``` +``` +type htmlParagraphElement = _htmlParagraphElement htmlElement_like +``` +``` +type _htmlParamElement +``` +``` +type htmlParamElement = _htmlParamElement htmlElement_like +``` +``` +type _htmlPreElement +``` +``` +type htmlPreElement = _htmlPreElement htmlElement_like +``` +``` +type _htmlProgressElement +``` +``` +type htmlProgressElement = _htmlProgressElement htmlElement_like +``` +``` +type _htmlQuoteElement +``` +``` +type htmlQuoteElement = _htmlQuoteElement htmlElement_like +``` +``` +type _htmlScriptElement +``` +``` +type htmlScriptElement = _htmlScriptElement htmlElement_like +``` +``` +type _htmlSelectElement +``` +``` +type htmlSelectElement = _htmlSelectElement htmlElement_like +``` +``` +type _htmlSlotElement +``` +``` +type htmlSlotElement = _htmlSlotElement htmlElement_like +``` +``` +type _htmlSourceElement +``` +``` +type htmlSourceElement = _htmlSourceElement htmlElement_like +``` +``` +type _htmlSpanElement +``` +``` +type htmlSpanElement = _htmlSpanElement htmlElement_like +``` +``` +type _htmlStyleElement +``` +``` +type htmlStyleElement = _htmlStyleElement htmlElement_like +``` +``` +type _htmlTableCaptionElement +``` +``` +type htmlTableCaptionElement = _htmlTableCaptionElement htmlElement_like +``` +``` +type _htmlTableCellElement +``` +``` +type htmlTableCellElement = _htmlTableCellElement htmlElement_like +``` +``` +type _htmlTableColElement +``` +``` +type htmlTableColElement = _htmlTableColElement htmlElement_like +``` +``` +type _htmlTableDataCellElement +``` +``` +type htmlTableDataCellElement = _htmlTableDataCellElement htmlElement_like +``` +``` +type _htmlTableElement +``` +``` +type htmlTableElement = _htmlTableElement htmlElement_like +``` +``` +type _htmlTableHeaderCellElement +``` +``` +type htmlTableHeaderCellElement = _htmlTableHeaderCellElement htmlElement_like +``` +``` +type _htmlTableRowElement +``` +``` +type htmlTableRowElement = _htmlTableRowElement htmlElement_like +``` +``` +type _htmlTableSectionElement +``` +``` +type htmlTableSectionElement = _htmlTableSectionElement htmlElement_like +``` +``` +type _htmlTextAreaElement +``` +``` +type htmlTextAreaElement = _htmlTextAreaElement htmlElement_like +``` +``` +type _htmlTimeElement +``` +``` +type htmlTimeElement = _htmlTimeElement htmlElement_like +``` +``` +type _htmlTitleElement +``` +``` +type htmlTitleElement = _htmlTitleElement htmlElement_like +``` +``` +type _htmlTrackElement +``` +``` +type htmlTrackElement = _htmlTrackElement htmlElement_like +``` +``` +type _htmlUlistElement +``` +``` +type htmlUlistElement = _htmlUlistElement htmlElement_like +``` +``` +type _htmlUnknownElement +``` +``` +type htmlUnknownElement = _htmlUnknownElement htmlElement_like +``` +``` +type _htmlVideoElement +``` +``` +type htmlVideoElement = _htmlVideoElement htmlElement_like +``` +``` +type location +``` +``` +type window +``` +``` +type _xmlDocument +``` +``` +type xmlDocument = _xmlDocument document_like +``` +``` +type 'a event_like +``` +``` +type event = _baseClass event_like +``` +``` +type 'a _uiEvent +``` +``` +type 'a uiEvent_like = 'a _uiEvent event_like +``` +``` +type uiEvent = _baseClass uiEvent_like +``` +``` +type _animationEvent +``` +``` +type animationEvent = _animationEvent event_like +``` +``` +type _beforeUnloadEvent +``` +``` +type beforeUnloadEvent = _beforeUnloadEvent event_like +``` +``` +type _clipboardEvent +``` +``` +type clipboardEvent = _clipboardEvent event_like +``` +``` +type _closeEvent +``` +``` +type closeEvent = _closeEvent event_like +``` +``` +type _compositionEvent +``` +``` +type compositionEvent = _compositionEvent uiEvent_like +``` +``` +type _customEvent +``` +``` +type customEvent = _customEvent event_like +``` +``` +type _dragEvent +``` +``` +type dragEvent = _dragEvent event_like +``` +``` +type _errorEvent +``` +``` +type errorEvent = _errorEvent event_like +``` +``` +type _focusEvent +``` +``` +type focusEvent = _focusEvent uiEvent_like +``` +``` +type _idbVersionChangeEvent +``` +``` +type idbVersionChangeEvent = _idbVersionChangeEvent event_like +``` +``` +type _inputEvent +``` +``` +type inputEvent = _inputEvent uiEvent_like +``` +``` +type _keyboardEvent +``` +``` +type keyboardEvent = _keyboardEvent uiEvent_like +``` +``` +type _messageEvent +``` +``` +type messageEvent = _messageEvent event_like +``` +``` +type 'a _mouseEvent +``` +``` +type 'a mouseEvent_like = 'a _mouseEvent uiEvent_like +``` +``` +type mouseEvent = _baseClass mouseEvent_like +``` +``` +type _pageTransitionEvent +``` +``` +type pageTransitionEvent = _pageTransitionEvent event_like +``` +``` +type _pointerEvent +``` +``` +type pointerEvent = _pointerEvent mouseEvent_like +``` +``` +type _popStateEvent +``` +``` +type popStateEvent = _popStateEvent event_like +``` +``` +type _progressEvent +``` +``` +type progressEvent = _progressEvent event_like +``` +``` +type _relatedEvent +``` +``` +type relatedEvent = _relatedEvent event_like +``` +``` +type _storageEvent +``` +``` +type storageEvent = _storageEvent event_like +``` +``` +type _svgZoomEvent +``` +``` +type svgZoomEvent = _svgZoomEvent event_like +``` +``` +type _timeEvent +``` +``` +type timeEvent = _timeEvent event_like +``` +``` +type _touchEvent +``` +``` +type touchEvent = _touchEvent uiEvent_like +``` +``` +type _trackEvent +``` +``` +type trackEvent = _trackEvent event_like +``` +``` +type _transitionEvent +``` +``` +type transitionEvent = _transitionEvent event_like +``` +``` +type _webGlContextEvent +``` +``` +type webGlContextEvent = _webGlContextEvent event_like +``` +``` +type _wheelEvent +``` +``` +type wheelEvent = _wheelEvent uiEvent_like +``` +``` +type range +``` +``` +type selection +``` +``` +type domTokenList +``` +``` +type domSettableTokenList +``` +``` +type nodeFilter = { +``` +`acceptNode : element -> int;` +``` +} +``` +``` +type nodeIterator +``` +``` +type treeWalker +``` +``` +type svgRect +``` +``` +type svgPoint +``` +``` +type eventPointerId +``` +``` +type messageChannel +``` +``` +module Storage : sig ... end +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Array.md b/docs/api/melange/Js-Array.md new file mode 100644 index 000000000..6beb51e44 --- /dev/null +++ b/docs/api/melange/Js-Array.md @@ -0,0 +1,170 @@ +# Module `Js.Array` +Bindings to the functions in `Array.prototype` +JavaScript Array API +``` +type 'a t = 'a array +``` +``` +type 'a array_like = 'a Js.array_like +``` +``` +val from : 'a array_like -> 'a array +``` +``` +val fromMap : 'a array_like -> f:('a -> 'b) -> 'b array +``` +``` +val isArray : 'a -> bool +``` +``` +val length : 'a array -> int +``` +Mutating functions +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> 'a t -> 'a t +``` +``` +val fill : value:'a -> ?start:int -> ?end_:int -> 'a t -> 'a t +``` +``` +val pop : 'a t -> 'a option +``` +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/push +``` +val push : value:'a -> 'a t -> int +``` +``` +val pushMany : values:'a array -> 'a t -> int +``` +``` +val reverseInPlace : 'a t -> 'a t +``` +``` +val shift : 'a t -> 'a option +``` +``` +val sortInPlace : 'a t -> 'a t +``` +``` +val sortInPlaceWith : f:('a -> 'a -> int) -> 'a t -> 'a t +``` +``` +val spliceInPlace : start:int -> remove:int -> add:'a array -> 'a t -> 'a t +``` +``` +val removeFromInPlace : start:int -> 'a t -> 'a t +``` +``` +val removeCountInPlace : start:int -> count:int -> 'a t -> 'a t +``` +``` +val unshift : value:'a -> 'a t -> int +``` +``` +val unshiftMany : values:'a array -> 'a t -> int +``` +``` +val concat : other:'a t -> 'a t -> 'a t +``` +``` +val concatMany : arrays:'a t array -> 'a t -> 'a t +``` +``` +val includes : value:'a -> 'a t -> bool +``` +ES2015 +``` +val join : ?sep:string -> 'a t -> string +``` +Accessor functions +``` +val indexOf : value:'a -> ?start:int -> 'a t -> int +``` +``` +val lastIndexOf : value:'a -> 'a t -> int +``` +``` +val lastIndexOfFrom : value:'a -> start:int -> 'a t -> int +``` +``` +val copy : 'a t -> 'a t +``` +``` +val slice : ?start:int -> ?end_:int -> 'a t -> 'a t +``` +``` +val toString : 'a t -> string +``` +``` +val toLocaleString : 'a t -> string +``` +Iteration functions +``` +val entries : 'a t -> (int * 'a) Js.iterator +``` +``` +val every : f:('a -> bool) -> 'a t -> bool +``` +``` +val everyi : f:('a -> int -> bool) -> 'a t -> bool +``` +``` +val filter : f:('a -> bool) -> 'a t -> 'a t +``` +``` +val filteri : f:('a -> int -> bool) -> 'a t -> 'a t +``` +``` +val find : f:('a -> bool) -> 'a t -> 'a option +``` +``` +val findi : f:('a -> int -> bool) -> 'a t -> 'a option +``` +``` +val findIndex : f:('a -> bool) -> 'a t -> int +``` +``` +val findIndexi : f:('a -> int -> bool) -> 'a t -> int +``` +``` +val forEach : f:('a -> unit) -> 'a t -> unit +``` +``` +val forEachi : f:('a -> int -> unit) -> 'a t -> unit +``` +``` +val keys : 'a t -> int Js.iterator +``` +``` +val map : f:('a -> 'b) -> 'a t -> 'b t +``` +``` +val mapi : f:('a -> int -> 'b) -> 'a t -> 'b t +``` +``` +val reduce : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val reducei : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val reduceRight : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val reduceRighti : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val some : f:('a -> bool) -> 'a t -> bool +``` +``` +val somei : f:('a -> int -> bool) -> 'a t -> bool +``` +``` +val values : 'a t -> 'a Js.iterator +``` +``` +val unsafe_get : 'a array -> int -> 'a +``` +``` +val unsafe_set : 'a array -> int -> 'a -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Bigint.md b/docs/api/melange/Js-Bigint.md new file mode 100644 index 000000000..76fcb0573 --- /dev/null +++ b/docs/api/melange/Js-Bigint.md @@ -0,0 +1,59 @@ +# Module `Js.Bigint` +Bindings to functions in JavaScript's `BigInt` +JavaScript BigInt API +``` +type t = Js.bigint +``` +``` +val make : 'a -> t +``` +`make repr` creates a new BigInt from the representation `repr`. `repr` can be a number, a string, boolean, etc. +``` +val asIntN : precision:int -> t -> t +``` +`asIntN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as a signed integer. +``` +val asUintN : precision:int -> t -> t +``` +`asUintN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as an unsigned integer. +``` +type toLocaleStringOptions = { +``` +`style : string;` +`currency : string;` +``` +} +``` +``` +val toLocaleString : + locale:string -> + ?options:toLocaleStringOptions -> + t -> + string +``` +`toLocaleString bigint` returns a string with a language-sensitive representation of this BigInt. +``` +val toString : t -> string +``` +`toString bigint` returns a string representing the specified BigInt value. +``` +val neg : t -> t +``` +``` +val add : t -> t -> t +``` +``` +val sub : t -> t -> t +``` +Subtraction. +``` +val mul : t -> t -> t +``` +Multiplication. +``` +val div : t -> t -> t +``` +Division. +``` +val rem : t -> t -> t +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Blob.md b/docs/api/melange/Js-Blob.md new file mode 100644 index 000000000..367bd075b --- /dev/null +++ b/docs/api/melange/Js-Blob.md @@ -0,0 +1,43 @@ +# Module `Js.Blob` +Bindings to Blob +``` +type t = Js.blob +``` +``` +type options = { +``` +`type_ : string option;` +A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". +``endings : [ `transparent | `native ] option;`` +How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the blob without changing them. To convert newlines to the host system's native convention, specify the value native. +``` +} +``` +``` +val make : string Js.iterator -> ?options:options -> unit -> t +``` +`make (Js.Array.values contents_array)` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. +``` +val size : t -> float +``` +`size t` returns the size of the Blob in bytes +``` +val type_ : t -> string +``` +`type_ t` returns the MIME type of the file. +``` +val arrayBuffer : t -> Js.arrayBuffer Js.promise +``` +`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. +``` +val bytes : t -> Js.uint8Array Js.promise +``` +`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the blob as an array of bytes. +``` +val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t +``` +`slice ?start ?end_ ?contentType t` creates and returns a new Blob object which contains data from a subset of the blob on which it's called. +``` +val text : t -> string Js.promise +``` +`text t` returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. \ No newline at end of file diff --git a/docs/api/melange/Js-Console.md b/docs/api/melange/Js-Console.md new file mode 100644 index 000000000..f382ef362 --- /dev/null +++ b/docs/api/melange/Js-Console.md @@ -0,0 +1,70 @@ +# Module `Js.Console` +``` +val log : 'a -> unit +``` +``` +val log2 : 'a -> 'b -> unit +``` +``` +val log3 : 'a -> 'b -> 'c -> unit +``` +``` +val log4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val logMany : 'a array -> unit +``` +``` +val info : 'a -> unit +``` +``` +val info2 : 'a -> 'b -> unit +``` +``` +val info3 : 'a -> 'b -> 'c -> unit +``` +``` +val info4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val infoMany : 'a array -> unit +``` +``` +val warn : 'a -> unit +``` +``` +val warn2 : 'a -> 'b -> unit +``` +``` +val warn3 : 'a -> 'b -> 'c -> unit +``` +``` +val warn4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val warnMany : 'a array -> unit +``` +``` +val error : 'a -> unit +``` +``` +val error2 : 'a -> 'b -> unit +``` +``` +val error3 : 'a -> 'b -> 'c -> unit +``` +``` +val error4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val errorMany : 'a array -> unit +``` +``` +val trace : unit -> unit +``` +``` +val timeStart : string -> unit +``` +``` +val timeEnd : string -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Date.md b/docs/api/melange/Js-Date.md new file mode 100644 index 000000000..c03601b6a --- /dev/null +++ b/docs/api/melange/Js-Date.md @@ -0,0 +1,304 @@ +# Module `Js.Date` +Bindings to the functions in JS's `Date.prototype` +JavaScript Date API +``` +type t +``` +``` +val valueOf : t -> float +``` +returns the primitive value of this date, equivalent to getTime +``` +val make : unit -> t +``` +returns a date representing the current time +``` +val fromFloat : float -> t +``` +``` +val fromString : string -> t +``` +``` +val makeWithYM : year:float -> month:float -> t +``` +``` +val makeWithYMD : year:float -> month:float -> date:float -> t +``` +``` +val makeWithYMDH : year:float -> month:float -> date:float -> hours:float -> t +``` +``` +val makeWithYMDHM : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + t +``` +``` +val makeWithYMDHMS : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + seconds:float -> + t +``` +``` +val utcWithYM : year:float -> month:float -> float +``` +``` +val utcWithYMD : year:float -> month:float -> date:float -> float +``` +``` +val utcWithYMDH : + year:float -> + month:float -> + date:float -> + hours:float -> + float +``` +``` +val utcWithYMDHM : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + float +``` +``` +val utcWithYMDHMS : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + seconds:float -> + float +``` +``` +val now : unit -> float +``` +returns the number of milliseconds since Unix epoch +``` +val parseAsFloat : string -> float +``` +returns NaN if passed invalid date string +``` +val getDate : t -> float +``` +return the day of the month (1-31) +``` +val getDay : t -> float +``` +returns the day of the week (0-6) +``` +val getFullYear : t -> float +``` +``` +val getHours : t -> float +``` +``` +val getMilliseconds : t -> float +``` +``` +val getMinutes : t -> float +``` +``` +val getMonth : t -> float +``` +returns the month (0-11) +``` +val getSeconds : t -> float +``` +``` +val getTime : t -> float +``` +returns the number of milliseconds since Unix epoch +``` +val getTimezoneOffset : t -> float +``` +``` +val getUTCDate : t -> float +``` +return the day of the month (1-31) +``` +val getUTCDay : t -> float +``` +returns the day of the week (0-6) +``` +val getUTCFullYear : t -> float +``` +``` +val getUTCHours : t -> float +``` +``` +val getUTCMilliseconds : t -> float +``` +``` +val getUTCMinutes : t -> float +``` +``` +val getUTCMonth : t -> float +``` +returns the month (0-11) +``` +val getUTCSeconds : t -> float +``` +``` +val setDate : date:float -> t -> float +``` +``` +val setFullYear : year:float -> t -> float +``` +``` +val setFullYearM : year:float -> month:float -> t -> float +``` +``` +val setFullYearMD : year:float -> month:float -> date:float -> t -> float +``` +``` +val setHours : hours:float -> t -> float +``` +``` +val setHoursM : hours:float -> minutes:float -> t -> float +``` +``` +val setHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float +``` +``` +val setHoursMSMs : + hours:float -> + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setMilliseconds : milliseconds:float -> t -> float +``` +``` +val setMinutes : minutes:float -> t -> float +``` +``` +val setMinutesS : minutes:float -> seconds:float -> t -> float +``` +``` +val setMinutesSMs : + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setMonth : month:float -> t -> float +``` +``` +val setMonthD : month:float -> date:float -> t -> float +``` +``` +val setSeconds : seconds:float -> t -> float +``` +``` +val setSecondsMs : seconds:float -> milliseconds:float -> t -> float +``` +``` +val setTime : time:float -> t -> float +``` +``` +val setUTCDate : date:float -> t -> float +``` +``` +val setUTCFullYear : year:float -> t -> float +``` +``` +val setUTCFullYearM : year:float -> month:float -> t -> float +``` +``` +val setUTCFullYearMD : year:float -> month:float -> date:float -> t -> float +``` +``` +val setUTCHours : hours:float -> t -> float +``` +``` +val setUTCHoursM : hours:float -> minutes:float -> t -> float +``` +``` +val setUTCHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float +``` +``` +val setUTCHoursMSMs : + hours:float -> + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setUTCMilliseconds : milliseconds:float -> t -> float +``` +``` +val setUTCMinutes : minutes:float -> t -> float +``` +``` +val setUTCMinutesS : minutes:float -> seconds:float -> t -> float +``` +``` +val setUTCMinutesSMs : + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setUTCMonth : month:float -> t -> float +``` +``` +val setUTCMonthD : month:float -> date:float -> t -> float +``` +``` +val setUTCSeconds : seconds:float -> t -> float +``` +``` +val setUTCSecondsMs : seconds:float -> milliseconds:float -> t -> float +``` +``` +val setUTCTime : time:float -> t -> float +``` +``` +val toDateString : t -> string +``` +``` +val toISOString : t -> string +``` +``` +val toJSON : t -> string option +``` +``` +val toJSONUnsafe : t -> string +``` +``` +val toLocaleDateString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val toLocaleTimeString : t -> string +``` +``` +val toString : t -> string +``` +``` +val toTimeString : t -> string +``` +``` +val toUTCString : t -> string +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Dict.md b/docs/api/melange/Js-Dict.md new file mode 100644 index 000000000..a04a5a5ac --- /dev/null +++ b/docs/api/melange/Js-Dict.md @@ -0,0 +1,58 @@ +# Module `Js.Dict` +Utility functions to treat a JS object as a dictionary +``` +type 'a t = 'a Js.dict +``` +Dictionary type (ie an '{ }' JS object). However it is restricted to hold a single type; therefore values must have the same type. +This Dictionary type is mostly used with the `Js_json.t` type. +``` +type key = string +``` +Key type +``` +val get : 'a t -> key -> 'a option +``` +`get dict key` returns `None` if the `key` is not found in the dictionary, `Some value` otherwise +``` +val unsafeGet : 'a t -> key -> 'a +``` +`unsafeGet dict key` return the value if the `key` exists, otherwise an **undefined** value is returned. Must be used only when the existence of a key is certain. (i.e. when having called `keys` function previously. +```ocaml +Array.iter (fun key -> Js.log (Js_dict.unsafeGet dic key)) (Js_dict.keys dict) +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`set dict key value` sets the `key`/`value` in `dict` +``` +val keys : 'a t -> string array +``` +`keys dict` returns all the keys in the dictionary `dict` +``` +val empty : unit -> 'a t +``` +`empty ()` returns an empty dictionary +``` +val unsafeDeleteKey : (string t -> string -> unit) Js.Fn.arity2 +``` +Experimental internal function +``` +val entries : 'a t -> (key * 'a) array +``` +`entries dict` returns the key value pairs in `dict` (ES2017) +``` +val values : 'a t -> 'a array +``` +`values dict` returns the values in `dict` (ES2017) +``` +val fromList : (key * 'a) list -> 'a t +``` +`fromList entries` creates a new dictionary containing each `(key, value)` pair in `entries` +``` +val fromArray : (key * 'a) array -> 'a t +``` +`fromArray entries` creates a new dictionary containing each `(key, value)` pair in `entries` +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +`map f dict` maps `dict` to a new dictionary with the same keys, using `f` to map each value \ No newline at end of file diff --git a/docs/api/melange/Js-Exn.md b/docs/api/melange/Js-Exn.md new file mode 100644 index 000000000..ecaf084c3 --- /dev/null +++ b/docs/api/melange/Js-Exn.md @@ -0,0 +1,70 @@ +# Module `Js.Exn` +Utilities for dealing with Js exceptions +``` +type t +``` +``` +type exn += private +``` +``` +| Error of t +``` +``` + +``` +``` +val asJsExn : exn -> t option +``` +``` +val stack : t -> string option +``` +``` +val message : t -> string option +``` +``` +val name : t -> string option +``` +``` +val fileName : t -> string option +``` +``` +val isCamlExceptionOrOpenVariant : 'a -> bool +``` +internal use only +``` +val anyToExnInternal : 'a -> exn +``` +`anyToExnInternal obj` will take any value `obj` and wrap it in a Js.Exn.Error if given value is not an exn already. If `obj` is an exn, it will return `obj` without any changes. +This function is mostly useful for cases where you want to unify a type of a value that potentially is either exn, a JS error, or any other JS value really (e.g. for a value passed to a Promise.catch callback) +IMPORTANT: This is an internal API and may be changed / removed any time in the future. +```ocaml + switch (Js.Exn.unsafeAnyToExn("test")) { + | Js.Exn.Error(v) => + switch (Js.Exn.message(v)) { + | Some(str) => Js.log("We won't end up here") + | None => Js.log2("We will land here: ", v) + } + } +``` +``` +val raiseError : string -> 'a +``` +Raise Js exception Error object with stacktrace +``` +val raiseEvalError : string -> 'a +``` +``` +val raiseRangeError : string -> 'a +``` +``` +val raiseReferenceError : string -> 'a +``` +``` +val raiseSyntaxError : string -> 'a +``` +``` +val raiseTypeError : string -> 'a +``` +``` +val raiseUriError : string -> 'a +``` \ No newline at end of file diff --git a/docs/api/melange/Js-File.md b/docs/api/melange/Js-File.md new file mode 100644 index 000000000..083a8c32a --- /dev/null +++ b/docs/api/melange/Js-File.md @@ -0,0 +1,58 @@ +# Module `Js.File` +Bindings to File +``` +type t = Js.file +``` +``` +type options = { +``` +`type_ : string option;` +A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". +``endings : [ `transparent | `native ] option;`` +How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the file without changing them. To convert newlines to the host system's native convention, specify the value native. +`lastModified : float option;` +A number representing the number of milliseconds between the Unix time epoch and when the file was last modified. Defaults to a value of Date.now(). +``` +} +``` +``` +val make : + string Js.iterator -> + filename:string -> + ?options:options -> + unit -> + t +``` +`make contents_array ~filename` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. +``` +val lastModified : t -> float +``` +`lastModified t` accesses the read-only property of the File interface, which provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. +``` +val name : t -> string +``` +The `name t` read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property. +``` +val size : t -> float +``` +`size t` returns the size of the File in bytes +``` +val type_ : t -> string +``` +`type_ t` returns the MIME type of the file. +``` +val arrayBuffer : t -> Js.arrayBuffer Js.promise +``` +`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. +``` +val bytes : t -> Js.uint8Array Js.promise +``` +`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the file as an array of bytes. +``` +val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t +``` +`slice ?start ?end_ ?contentType t` creates and returns a new File object which contains data from a subset of the file on which it's called. +``` +val text : t -> string Js.promise +``` +`text t` returns a Promise that resolves with a string containing the contents of the file, interpreted as UTF-8. \ No newline at end of file diff --git a/docs/api/melange/Js-Float.md b/docs/api/melange/Js-Float.md new file mode 100644 index 000000000..07a90c876 --- /dev/null +++ b/docs/api/melange/Js-Float.md @@ -0,0 +1,112 @@ +# Module `Js.Float` +Bindings to functions in JavaScript's `Number` that deal with floats +Provides functions for inspecting and manipulating `float`s +``` +type t = float +``` +``` +val _NaN : t +``` +The special value "Not a Number" +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) MDN +``` +val isNaN : t -> bool +``` +Tests if the given value is `_NaN` +Note that both `_NaN = _NaN` and `_NaN == _NaN` will return `false`. `isNaN` is therefore necessary to test for `_NaN`. +**Returns** `true` if the given value is `_NaN`, `false` otherwise +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) MDN +``` +val isFinite : t -> bool +``` +Tests if the given value is finite +**Returns** `true` if the given value is a finite number, `false` otherwise +```ocaml +(* returns [false] *) +let _ = Js.Float.isFinite infinity + +(* returns [false] *) +let _ = Js.Float.isFinite neg_infinity + +(* returns [false] *) +let _ = Js.Float.isFinite _NaN + +(* returns [true] *) +let _ = Js.Float.isFinite 1234 +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) MDN +``` +val toExponential : ?digits:int -> t -> string +``` +Formats a `float` using exponential (scientific) notation +**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). +**Returns** a `string` representing the given value in exponential notation +The output will be rounded or padded with zeroes if necessary. +raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) +```ocaml + Js.Float.toExponential 77.1234 = "7.71234e+1" + Js.Float.toExponential 77. = "7.7e+1" + Js.Float.toExponential ~digits:2 77.1234 = "7.71e+1" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN +``` +val toFixed : ?digits:int -> t -> string +``` +Formats a `float` using fixed point notation +**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). Defaults to `0`. +**Returns** a `string` representing the given value in fixed-point notation (usually) +The output will be rounded or padded with zeroes if necessary. +raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) +```ocaml + Js.Float.toFixed 12345.6789 = "12346" + Js.Float.toFixed 1.2e21 = "1.2e+21" + Js.Float.toFixed ~digits:1 12345.6789 = "12345.7" + Js.Float.toFixed ~digits:2 0. = "0.00" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toFixed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) MDN +``` +val toPrecision : ?digits:int -> t -> string +``` +Formats a `float` using some fairly arbitrary rules +**digits** specifies how many digits should appear in total. The value must between 0 and some arbitrary number that's hopefully at least larger than 20 (for Node it's 21. Why? Who knows). +**Returns** a `string` representing the given value in fixed-point or scientific notation +The output will be rounded or padded with zeroes if necessary. +`toPrecision` differs from `toFixed` in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. +raises `RangeError` if digits is not in the range accepted by this function (what do you mean "vague"?) +```ocaml + Js.Float.toPrecision 12345.6789 = "12345.6789" + Js.Float.toPrecision 1.2e21 = "1.2e+21" + Js.Float.toPrecision ~digits:1 12345.6789 = "1e+4" + Js.Float.toPrecision ~digits:2 0. = "0.0" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN +``` +val toString : ?radix:int -> t -> string +``` +Formats a `float` as a string +**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). +**Returns** a `string` representing the given value in fixed-point (usually) +raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) +```ocaml + Js.Float.toString 12345.6789 = "12345.6789" + Js.Float.toString ~radix:2 6. = "110" + Js.Float.toString ~radix:2 3.14 = "11.001000111101011100001010001111010111000010100011111" + Js.Float.toString ~radix:16 3735928559. = "deadbeef" + Js.Float.toString ~radix:36 123.456 = "3f.gez4w97ry0a18ymf6qadcxr" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN +``` +val fromString : string -> t +``` +Parses the given `string` into a `float` using JavaScript semantics +**Returns** the number as a `float` if successfully parsed, `_NaN` otherwise. +```ocaml +Js.Float.fromString "123" = 123. +Js.Float.fromString "12.3" = 12.3 +Js.Float.fromString "" = 0. +Js.Float.fromString "0x11" = 17. +Js.Float.fromString "0b11" = 3. +Js.Float.fromString "0o11" = 9. +Js.Float.fromString "foo" = _NaN +Js.Float.fromString "100a" = _NaN +``` \ No newline at end of file diff --git a/docs/api/melange/Js-FormData.md b/docs/api/melange/Js-FormData.md new file mode 100644 index 000000000..c1b922975 --- /dev/null +++ b/docs/api/melange/Js-FormData.md @@ -0,0 +1,75 @@ +# Module `Js.FormData` +Bindings to FormData +``` +type t +``` +``` +type entryValue +``` +The values returned by the \`get`,All`\` and iteration functions is either a string or a Blob. Melange uses an abstract type and defers to users of the API to handle it according to their application needs. +``` +val make : unit -> t +``` +`make ()` creates a new `FormData` object, initially empty. +``` +val append : + name:string -> + value:[ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> + t -> + unit +``` +`append t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. +``` +val appendBlob : + name:string -> + value:[ `Blob of Js.blob | `File of Js.file ] -> + ?filename:string -> + t -> + unit +``` +`appendBlob t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. This method differs from `append` in that instances in the Blob hierarchy can pass a third filename argument. +``` +val delete : name:string -> t -> unit +``` +`delete t ~name` deletes a key and its value(s) from a FormData object. +``` +val get : name:string -> t -> entryValue option +``` +`get t ~name` returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use [`getAll`](./#val-getAll) instead. +``` +val getAll : name:string -> t -> entryValue array +``` +`getAll t ~name` returns all the values associated with a given key from within a FormData object. +``` +val set : + name:string -> + [ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> + t -> + unit +``` +`set t ~name ~value` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. +``` +val setBlob : + name:string -> + [ `Blob of Js.blob | `File of Js.file ] -> + ?filename:string -> + t -> + unit +``` +`setBlob t ~name ~value ?filename` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. This method differs from `set` in that instances in the Blob hierarchy can pass a third filename argument. +``` +val has : name:string -> t -> bool +``` +`has ~name t` returns whether a FormData object contains a certain key. +``` +val keys : t -> string Js.iterator +``` +`keys t` returns an iterator which iterates through all keys contained in the FormData. The keys are strings. +``` +val values : t -> entryValue Js.iterator +``` +`values t` returns an iterator which iterates through all values contained in the FormData. The values are strings or Blob objects. +``` +val entries : t -> (string * entryValue) Js.iterator +``` +`entries t` returns an iterator which iterates through all key/value pairs contained in the FormData. \ No newline at end of file diff --git a/docs/api/melange/Js-Global.md b/docs/api/melange/Js-Global.md new file mode 100644 index 000000000..50d8ab446 --- /dev/null +++ b/docs/api/melange/Js-Global.md @@ -0,0 +1,130 @@ +# Module `Js.Global` +Bindings to functions in the JS global namespace +Contains functions available in the global scope (`window` in a browser context) +``` +type intervalId +``` +Identify an interval started by [`setInterval`](./#val-setInterval) +``` +type timeoutId +``` +Identify timeout started by [`setTimeout`](./#val-setTimeout) +``` +val clearInterval : intervalId -> unit +``` +Clear an interval started by [`setInterval`](./#val-setInterval) +```ocaml +(* API for a somewhat aggressive snoozing alarm clock *) + +let interval = ref Js.Nullable.null + +let remind () = + Js.log "Wake Up!"; + IO.punchSleepyGuy () + +let snooze mins = + interval := Js.Nullable.return (Js.Global.setInterval remind (mins * 60 * 1000)) + +let cancel () = + Js.Nullable.iter !interval (fun[\@u] intervalId -> Js.Global.clearInterval intervalId) +``` +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) MDN +``` +val clearTimeout : timeoutId -> unit +``` +Clear a timeout started by [`setTimeout`](./#val-setTimeout) +```ocaml +(* A simple model of a code monkey's brain *) + +let timer = ref Js.Nullable.null + +let work () = + IO.closeHackerNewsTab () + +let procrastinate mins = + Js.Nullable.iter !timer (fun[\@u] timer -> Js.Global.clearTimeout timer); + timer := Js.Nullable.return (Js.Global.setTimeout work (mins * 60 * 1000)) +``` +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout) MDN +``` +val setInterval : f:(unit -> unit) -> int -> intervalId +``` +*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls +**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN +```ocaml +(* Will count up and print the count to the console every second *) + +let count = ref 0 + +let tick () = + count := !count + 1; Js.log (string_of_int !count) + +let _ = + Js.Global.setInterval tick 1000 +``` +``` +val setIntervalFloat : f:(unit -> unit) -> float -> intervalId +``` +*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls +**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN +```ocaml +(* Will count up and print the count to the console every second *) + +let count = ref 0 + +let tick () = + count := !count + 1; Js.log (string_of_int !count) + +let _ = + Js.Global.setIntervalFloat tick 1000.0 +``` +``` +val setTimeout : f:(unit -> unit) -> int -> timeoutId +``` +Execute a callback after a specified delay (in milliseconds) +**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN +```ocaml +(* Prints "Timed out!" in the console after one second *) + +let message = "Timed out!" + +let _ = + Js.Global.setTimeout (fun () -> Js.log message) 1000 +``` +``` +val setTimeoutFloat : f:(unit -> unit) -> float -> timeoutId +``` +Execute a callback after a specified delay (in milliseconds) +**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN +```ocaml +(* Prints "Timed out!" in the console after one second *) + +let message = "Timed out!" + +let _ = + Js.Global.setTimeoutFloat (fun () -> Js.log message) 1000.0 +``` +``` +val encodeURI : string -> string +``` +URL-encodes a string. +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) MDN +``` +val decodeURI : string -> string +``` +Decodes a URL-enmcoded string produced by `encodeURI` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) MDN +``` +val encodeURIComponent : string -> string +``` +URL-encodes a string, including characters with special meaning in a URI. +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) MDN +``` +val decodeURIComponent : string -> string +``` +Decodes a URL-enmcoded string produced by `encodeURIComponent` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) MDN \ No newline at end of file diff --git a/docs/api/melange/Js-Int.md b/docs/api/melange/Js-Int.md new file mode 100644 index 000000000..ebf8be907 --- /dev/null +++ b/docs/api/melange/Js-Int.md @@ -0,0 +1,62 @@ +# Module `Js.Int` +Bindings to functions in JavaScript's `Number` that deal with ints +Provides functions for inspecting and manipulating `int`s +``` +type t = int +``` +If we use number, we need coerce to int32 by adding \`\|0\`, otherwise \`+0\` can be wrong. Most JS API is float oriented, it may overflow int32 or comes with `NAN` +``` +val toExponential : ?digits:t -> t -> string +``` +Formats an `int` using exponential (scientific) notation +**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). +**Returns** a `string` representing the given value in exponential notation +The output will be rounded or padded with zeroes if necessary. +raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) +```ocaml + Js.Int.toExponential 77 = "7.7e+1" + Js.Int.toExponential ~digits:2 77 = "7.70e+1" + Js.Int.toExponential ~digits:2 5678 = "5.68e+3" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN +``` +val toPrecision : ?digits:t -> t -> string +``` +Formats an `int` using some fairly arbitrary rules +**digits** specifies how many digits should appear in total. The value must between 1 and some 100. +**Returns** a `string` representing the given value in fixed-point or scientific notation +The output will be rounded or padded with zeroes if necessary. +`toPrecision` differs from [`Js.Float.toFixed`](./Js-Float.md#val-toFixed) in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. +raises `RangeError` if digits is not between 1 and 100. +```ocaml + Js.Int.toPrecision 123456789 = "123456789" + Js.Int.toPrecision ~digits:2 123456789 = "1.2e+8" + Js.Int.toPrecision ~digits:2 0 = "0.0" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN +``` +val toString : ?radix:t -> t -> string +``` +Formats an `int` as a string +**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). +**Returns** a `string` representing the given value in fixed-point (usually) +raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) +```ocaml + Js.Int.toString 123456789 = "123456789" + Js.Int.toString ~radix:2 6 = "110" + Js.Int.toString ~radix:16 3735928559 = "deadbeef" + Js.Int.toString ~radix:36 123456 = "2n9c" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN +``` +val toFloat : t -> float +``` +``` +val equal : t -> t -> bool +``` +``` +val max : t +``` +``` +val min : t +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Iterator.md b/docs/api/melange/Js-Iterator.md new file mode 100644 index 000000000..e466789f7 --- /dev/null +++ b/docs/api/melange/Js-Iterator.md @@ -0,0 +1,22 @@ +# Module `Js.Iterator` +Bindings to functions on `Iterator` +``` +type 'a t = 'a Js.iterator +``` +``` +type 'a value = { +``` +`done_ : bool option;` +`value : 'a option;` +``` +} +``` +``` +val next : 'a t -> 'a value +``` +``` +val toArray : 'a t -> 'a array +``` +``` +val toArrayWithMapper : 'a t -> f:('a -> 'b) -> 'b array +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Json.md b/docs/api/melange/Js-Json.md new file mode 100644 index 000000000..460764d0e --- /dev/null +++ b/docs/api/melange/Js-Json.md @@ -0,0 +1,242 @@ +# Module `Js.Json` +Utility functions to manipulate JSON values +Efficient JSON encoding using JavaScript API @see \ MDN +### Types +``` +type t +``` +The JSON data structure +``` +type _ kind = +``` +``` +| String : string kind +``` +``` +| Number : float kind +``` +``` +| Object : t Js.dict kind +``` +``` +| Array : t array kind +``` +``` +| Boolean : bool kind +``` +``` +| Null : t Js.null kind +``` +``` + +``` +Underlying type of a JSON value +``` +type tagged_t = +``` +``` +| JSONFalse +``` +``` +| JSONTrue +``` +``` +| JSONNull +``` +``` +| JSONString of string +``` +``` +| JSONNumber of float +``` +``` +| JSONObject of t Js.dict +``` +``` +| JSONArray of t array +``` +``` + +``` +### Accessor +``` +val classify : t -> tagged_t +``` +``` +val test : 'a -> 'b kind -> bool +``` +`test v kind` returns true if `v` is of `kind` +``` +val decodeString : t -> string option +``` +`decodeString json` returns `Some s` if `json` is a string, `None` otherwise +``` +val decodeNumber : t -> float option +``` +`decodeNumber json` returns `Some n` if `json` is a number, `None` otherwise +``` +val decodeObject : t -> t Js.dict option +``` +`decodeObject json` returns `Some o` if `json` is an object, `None` otherwise +``` +val decodeArray : t -> t array option +``` +`decodeArray json` returns `Some a` if `json` is an array, `None` otherwise +``` +val decodeBoolean : t -> bool option +``` +`decodeBoolean json` returns `Some b` if `json` is a boolean, `None` otherwise +``` +val decodeNull : t -> 'a Js.null option +``` +`decodeNull json` returns `Some null` if `json` is a null, `None` otherwise +### Construtors +Those functions allows the construction of an arbitrary complex JSON values. +``` +val null : t +``` +`null` is the singleton null JSON value +``` +val string : string -> t +``` +`string s` makes a JSON string of the `string` `s` +``` +val number : float -> t +``` +`number n` makes a JSON number of the `float` `n` +``` +val boolean : bool -> t +``` +`boolean b` makes a JSON boolean of the `bool` `b` +``` +val object_ : t Js.dict -> t +``` +`object_ dict` makes a JSON object of the `Js.dict` `dict` +``` +val array : t array -> t +``` +`array a` makes a JSON array of the `Js.Json.t array` `a` +The functions below are specialized for specific array type which happened to be already JSON object in the Melange runtime. Therefore they are more efficient (constant time rather than linear conversion). +``` +val stringArray : string array -> t +``` +`stringArray a` makes a JSON array of the `string array` `a` +``` +val numberArray : float array -> t +``` +`numberArray a` makes a JSON array of the `float array` `a` +``` +val booleanArray : bool array -> t +``` +`booleanArray` makes a JSON array of the `bool array` `a` +``` +val objectArray : t Js.dict array -> t +``` +`objectArray a` makes a JSON array of the `JsDict.t array` `a` +### String conversion +``` +val parseExn : string -> t +``` +`parseExn s` parses the string `s` into a JSON data structure +**Returns** a JSON data structure +raises `SyntaxError` if given string is not a valid JSON. Note SyntaxError is a JavaScript exception. +```ocaml +(* parse a simple JSON string *) + +let json = + try + Js.Json.parseExn {| "foo" |} + with + | _ -> failwith "Error parsing JSON string" +in +match Js.Json.classify json with +| Js.Json.JSONString value -> Js.log value +| _ -> failwith "Expected a string" +``` +```ocaml +(* parse a complex JSON string *) + +let getIds s = + let json = + try + Js.Json.parseExn s + with + | _ -> failwith "Error parsing JSON string" + in + match Js.Json.classify json with + | Js.Json.JSONObject value -> + (* In this branch, compiler infer value : Js.Json.t Js.dict *) + begin match Js.Dict.get value "ids" with + | Some ids -> + begin match Js.Json.classify ids with + | Js.Json.JSONArray ids -> + (* In this branch compiler infer ids : Js.Json.t array *) + ids + | _ -> failwith "Expected an array" + end + | None -> failwith "Expected an `ids` property" + end + | _ -> failwith "Expected an object" + + (* prints `1, 2, 3` *) + let _ = + Js.log (getIds {| { "ids" : [1, 2, 3] } |}) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) MDN +``` +val stringify : t -> string +``` +`stringify json` formats the JSON data structure as a string +**Returns** the string representation of a given JSON data structure +```ocaml +(* Creates and stringifies a simple JS object *) + +let dict = Js.Dict.empty () in +Js.Dict.set dict "name" (Js.Json.string "John Doe"); +Js.Dict.set dict "age" (Js.Json.number 30.0); +Js.Dict.set dict "likes" + (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); + +Js.log (Js.Json.stringify (Js.Json.object_ dict)) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN +``` +val stringifyWithSpace : t -> int -> string +``` +`stringify json` formats the JSON data structure as a string +**Returns** the string representation of a given JSON data structure +```ocaml +(* Creates and stringifies a simple JS object with spacing *) + +let dict = Js.Dict.empty () in +Js.Dict.set dict "name" (Js.Json.string "John Doe"); +Js.Dict.set dict "age" (Js.Json.number 30.0); +Js.Dict.set dict "likes" + (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); + + Js.log (Js.Json.stringifyWithSpace (Js.Json.object_ dict) 2) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN +``` +val stringifyAny : 'a -> string option +``` +`stringifyAny value` formats any `value` into a JSON string +```ocaml + (* prints ``"foo", "bar"`` *) + Js.log (Js.Json.stringifyAny [| "foo"; "bar" |]) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN +Best-effort serialization, it tries to seralize as many objects as possible and deserialize it back +``` +val deserializeUnsafe : string -> 'a +``` +It is unsafe in two aspects +- It may throw during parsing +- when you cast it to a specific type, it may have a type mismatch +``` +val serializeExn : 'a -> string +``` +It will raise in such situations: +- The object can not be serlialized to a JSON +- There are cycles +- Some JS engines can not stringify deeply nested json objects \ No newline at end of file diff --git a/docs/api/melange/Js-Map.md b/docs/api/melange/Js-Map.md new file mode 100644 index 000000000..06bc79977 --- /dev/null +++ b/docs/api/melange/Js-Map.md @@ -0,0 +1,45 @@ +# Module `Js.Map` +Bindings to functions in `Map` +ES6 Map API +``` +type ('k, 'v) t +``` +``` +val make : unit -> ('k, 'v) t +``` +``` +val fromArray : ('k * 'v) array -> ('k, 'v) t +``` +``` +val toArray : ('k, 'v) t -> ('k * 'v) array +``` +``` +val size : ('k, 'v) t -> int +``` +``` +val has : key:'k -> ('k, 'v) t -> bool +``` +``` +val get : key:'k -> ('k, 'v) t -> 'v option +``` +``` +val set : key:'k -> value:'v -> ('k, 'v) t -> ('k, 'v) t +``` +``` +val clear : ('k, 'v) t -> unit +``` +``` +val delete : key:'k -> ('k, 'v) t -> bool +``` +``` +val forEach : f:('v -> 'k -> ('k, 'v) t -> unit) -> ('k, 'v) t -> unit +``` +``` +val keys : ('k, 'v) t -> 'k Js.iterator +``` +``` +val values : ('k, 'v) t -> 'v Js.iterator +``` +``` +val entries : ('k, 'v) t -> ('k * 'v) Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Math.md b/docs/api/melange/Js-Math.md new file mode 100644 index 000000000..1ff75cc38 --- /dev/null +++ b/docs/api/melange/Js-Math.md @@ -0,0 +1,238 @@ +# Module `Js.Math` +Bindings to the functions in the `Math` object +JavaScript Math API +``` +val _E : float +``` +Euler's number +``` +val _LN2 : float +``` +natural logarithm of 2 +``` +val _LN10 : float +``` +natural logarithm of 10 +``` +val _LOG2E : float +``` +base 2 logarithm of E +``` +val _LOG10E : float +``` +base 10 logarithm of E +``` +val _PI : float +``` +Pi... (ratio of the circumference and diameter of a circle) +``` +val _SQRT1_2 : float +``` +square root of 1/2 +``` +val _SQRT2 : float +``` +square root of 2 +``` +val abs_int : int -> int +``` +absolute value +``` +val abs_float : float -> float +``` +absolute value +``` +val acos : float -> float +``` +arccosine in radians, can return NaN +``` +val acosh : float -> float +``` +hyperbolic arccosine in raidans, can return NaN, ES2015 +``` +val asin : float -> float +``` +arcsine in radians, can return NaN +``` +val asinh : float -> float +``` +hyperbolic arcsine in raidans, ES2015 +``` +val atan : float -> float +``` +arctangent in radians +``` +val atanh : float -> float +``` +hyperbolic arctangent in radians, can return NaN, ES2015 +``` +val atan2 : y:float -> x:float -> float +``` +arctangent of the quotient of x and y, mostly... this one's a bit weird +``` +val cbrt : float -> float +``` +cube root, can return NaN, ES2015 +``` +val unsafe_ceil_int : float -> int +``` +may return values not representable by `int` +``` +val ceil_int : float -> int +``` +smallest int greater than or equal to the argument +``` +val ceil_float : float -> float +``` +smallest float greater than or equal to the argument +``` +val clz32 : int -> int +``` +number of leading zero bits of the argument's 32 bit int representation, ES2015 +``` +val cos : float -> float +``` +cosine in radians +``` +val cosh : float -> float +``` +hyperbolic cosine in radians, ES2015 +``` +val exp : float -> float +``` +natural exponentional +``` +val expm1 : float -> float +``` +natural exponential minus 1, ES2015 +``` +val unsafe_floor_int : float -> int +``` +may return values not representable by `int` +``` +val floor_int : float -> int +``` +largest int greater than or equal to the arugment +``` +val floor_float : float -> float +``` +``` +val fround : float -> float +``` +round to nearest single precision float, ES2015 +``` +val hypot : float -> float -> float +``` +pythagorean equation, ES2015 +``` +val hypotMany : float array -> float +``` +generalized pythagorean equation, ES2015 +``` +val imul : int -> int -> int +``` +32-bit integer multiplication, ES2015 +``` +val log : float -> float +``` +natural logarithm, can return NaN +``` +val log1p : float -> float +``` +natural logarithm of 1 \+ the argument, can return NaN, ES2015 +``` +val log10 : float -> float +``` +base 10 logarithm, can return NaN, ES2015 +``` +val log2 : float -> float +``` +base 2 logarithm, can return NaN, ES2015 +``` +val max_int : int -> int -> int +``` +max value +``` +val maxMany_int : int array -> int +``` +max value +``` +val max_float : float -> float -> float +``` +max value +``` +val maxMany_float : float array -> float +``` +max value +``` +val min_int : int -> int -> int +``` +min value +``` +val minMany_int : int array -> int +``` +min value +``` +val min_float : float -> float -> float +``` +min value +``` +val minMany_float : float array -> float +``` +min value +``` +val pow_float : base:float -> exp:float -> float +``` +base to the power of the exponent +``` +val random : unit -> float +``` +random number in \[0,1) +``` +val random_int : int -> int -> int +``` +random number in \[min,max) +``` +val unsafe_round : float -> int +``` +rounds to nearest integer, returns a value not representable as `int` if NaN +``` +val round : float -> float +``` +rounds to nearest integer +``` +val sign_int : int -> int +``` +the sign of the argument, 1, \-1 or 0, ES2015 +``` +val sign_float : float -> float +``` +the sign of the argument, 1, \-1, 0, \-0 or NaN, ES2015 +``` +val sin : float -> float +``` +sine in radians +``` +val sinh : float -> float +``` +hyperbolic sine in radians, ES2015 +``` +val sqrt : float -> float +``` +square root, can return NaN +``` +val tan : float -> float +``` +tangent in radians +``` +val tanh : float -> float +``` +hyperbolic tangent in radians, ES2015 +``` +val unsafe_trunc : float -> int +``` +truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 +``` +val trunc : float -> float +``` +truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 \ No newline at end of file diff --git a/docs/api/melange/Js-Null.md b/docs/api/melange/Js-Null.md new file mode 100644 index 000000000..ce0b91bb8 --- /dev/null +++ b/docs/api/melange/Js-Null.md @@ -0,0 +1,61 @@ +# Module `Js.Null` +Utility functions on [`null`](./Js.md#type-null) +Provides functionality for dealing with the `'a Js.null` type +``` +type +'a t = 'a Js.null +``` +Local alias for `'a Js.null` +``` +val return : 'a -> 'a t +``` +Constructs a value of `'a Js.null` containing a value of `'a` +``` +val empty : 'a t +``` +The empty value, `null` +``` +val getUnsafe : 'a t -> 'a +``` +``` +val getExn : 'a t -> 'a +``` +``` +val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t +``` +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +Maps the contained value using the given function +If `'a Js.null` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.null` +```ocaml +let maybeGreetWorld (maybeGreeting: string Js.null) = + Js.Null.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") +``` +``` +val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit +``` +Iterates over the contained value with the given function +If `'a Js.null` contains a value, that value is unwrapped and applied to the given function. +```ocaml +let maybeSay (maybeMessage: string Js.null) = + Js.Null.iter maybeMessage ~f:(fun message -> Js.log message) +``` +``` +val fromOption : 'a option -> 'a t +``` +Maps `'a option` to `'a Js.null` + + +
Some a -> return a +
None -> empty +
+ +``` +val toOption : 'a t -> 'a option +``` +Maps `'a Js.null` to `'a option` + + +
return a -> Some a +
empty -> None +
diff --git a/docs/api/melange/Js-Nullable.md b/docs/api/melange/Js-Nullable.md new file mode 100644 index 000000000..f3aec1cf7 --- /dev/null +++ b/docs/api/melange/Js-Nullable.md @@ -0,0 +1,64 @@ +# Module `Js.Nullable` +Utility functions on [`nullable`](./Js.md#type-nullable) +Contains functionality for dealing with values that can be both `null` and `undefined` +``` +type +'a t = 'a Js.nullable +``` +Local alias for `'a Js.nullable` +``` +val return : 'a -> 'a t +``` +Constructs a value of `'a Js.nullable` containing a value of `'a` +``` +val isNullable : 'a t -> bool +``` +Returns `true` if the given value is `null` or `undefined`, `false` otherwise +``` +val null : 'a t +``` +The `null` value of type `'a Js.nullable` +``` +val undefined : 'a t +``` +The `undefined` value of type `'a Js.nullable` +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +``` +val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t +``` +Binds the contained value using the given function +If `'a Js.nullable` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.nullable` +```ocaml +let maybeGreetWorld (maybeGreeting: string Js.nullable) = + Js.Nullable.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") +``` +``` +val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit +``` +Iterates over the contained value with the given function +If `'a Js.nullable` contains a value, that value is unwrapped and applied to the given function. +```ocaml +let maybeSay (maybeMessage: string Js.nullable) = + Js.Nullable.iter maybeMessage ~f:(fun message -> Js.log message) +``` +``` +val fromOption : 'a option -> 'a t +``` +Maps `'a option` to `'a Js.nullable` + + +
Some a -> return a +
None -> undefined +
+ +``` +val toOption : 'a t -> 'a option +``` +Maps `'a Js.nullable` to `'a option` + + +
return a -> Some a +
undefined -> None +
null -> None +
diff --git a/docs/api/melange/Js-Obj.md b/docs/api/melange/Js-Obj.md new file mode 100644 index 000000000..ac6cff4da --- /dev/null +++ b/docs/api/melange/Js-Obj.md @@ -0,0 +1,15 @@ +# Module `Js.Obj` +Utility functions on \`Js.t\` JS objects +``` +val empty : unit -> < .. > Js.t +``` +``` +val assign : < .. > Js.t -> < .. > Js.t -> < .. > Js.t +``` +``` +val merge : < .. > Js.t -> < .. > Js.t -> < .. > Js.t +``` +`merge obj1 obj2` assigns the properties in `obj2` to a copy of `obj1`. The function returns a new object, and both arguments are not mutated +``` +val keys : _ Js.t -> string array +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Promise.md b/docs/api/melange/Js-Promise.md new file mode 100644 index 000000000..7aaaf8a58 --- /dev/null +++ b/docs/api/melange/Js-Promise.md @@ -0,0 +1,53 @@ +# Module `Js.Promise` +Bindings to JS `Promise` functions +Specialized bindings to Promise. Note: For simplicity, this binding does not track the error type, it treat it as an opaque type +``` +type +'a t = 'a Js.promise +``` +``` +type error +``` +``` +val make : + (resolve:('a -> unit) Js.Fn.arity1 -> + reject:(exn -> unit) Js.Fn.arity1 -> + unit) -> + 'a t +``` +``` +val resolve : 'a -> 'a t +``` +``` +val reject : exn -> 'a t +``` +``` +val all : 'a t array -> 'a array t +``` +``` +val all2 : ('a0 t * 'a1 t) -> ('a0 * 'a1) t +``` +``` +val all3 : ('a0 t * 'a1 t * 'a2 t) -> ('a0 * 'a1 * 'a2) t +``` +``` +val all4 : ('a0 t * 'a1 t * 'a2 t * 'a3 t) -> ('a0 * 'a1 * 'a2 * 'a3) t +``` +``` +val all5 : + ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t) -> + ('a0 * 'a1 * 'a2 * 'a3 * 'a4) t +``` +``` +val all6 : + ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t * 'a5 t) -> + ('a0 * 'a1 * 'a2 * 'a3 * 'a4 * 'a5) t +``` +``` +val race : 'a t array -> 'a t +``` +``` +val then_ : ('a -> 'b t) -> 'a t -> 'b t +``` +``` +val catch : (error -> 'a t) -> 'a t -> 'a t +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Re.md b/docs/api/melange/Js-Re.md new file mode 100644 index 000000000..54a7f30c5 --- /dev/null +++ b/docs/api/melange/Js-Re.md @@ -0,0 +1,146 @@ +# Module `Js.Re` +Bindings to the functions in `RegExp.prototype` +Provides bindings for JavaScript Regular Expressions +##### Syntax sugar +Melange provides a bit of syntax sugar for regex literals: `[%re "/foo/g"]` will evaluate to a [`t`](./#type-t) that can be passed around and used like usual. +**Note:** This is not an immutable API. A RegExp object with the `global` ("g") flag set will modify the [`lastIndex`](./#val-lastIndex) property when the RegExp object is used, and subsequent uses will continue the search from the previous [`lastIndex`](./#val-lastIndex). +```ocaml +let maybeMatches = Js.String.exec ~str:"banana" [\[%re "/na+/g"\]] +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) JavaScript API reference on MDN +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular\_Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) JavaScript Regular Expressions Guide on MDN +``` +type t = Js.re +``` +the RegExp object +``` +type result +``` +the result of a executing a RegExp on a string +``` +val captures : result -> string Js.nullable array +``` +an array of the match and captures, the first is the full match and the remaining are the substring captures +``` +val index : result -> int +``` +0-based index of the match in the input string +``` +val input : result -> string +``` +the original input string +``` +val fromString : string -> t +``` +Constructs a RegExp object ([`t`](./#type-t)) from a string +Regex literals (`[%re "/.../"]`) should generally be preferred, but `fromString` is very useful when you need to insert a string into a regex. +```ocaml +(* A function that extracts the content of the first element with the given tag *) + +let contentOf tag xmlString = + Js.Re.fromString ("<" ^ tag ^ ">(.*?)<\\/" ^ tag ^">") + |> Js.Re.exec ~str:xmlString + |> function + | Some result -> Js.Nullable.toOption (Js.Re.captures result).(1) + | None -> None +``` +``` +val fromStringWithFlags : string -> flags:string -> t +``` +Constructs a RegExp object ([`t`](./#type-t)) from a string with the given `flags` +See [`fromString`](./#val-fromString) +Valid flags: + +
g global +
i ignore case +
m multiline +
u unicode (es2015) +
y sticky (es2015) +
+ +``` +val flags : t -> string +``` +returns the enabled flags as a string +``` +val global : t -> bool +``` +returns a bool indicating whether the `global` flag is set +``` +val ignoreCase : t -> bool +``` +returns a bool indicating whether the `ignoreCase` flag is set +``` +val lastIndex : t -> int +``` +returns the index where the next match will start its search +This property will be modified when the RegExp object is used, if the `global` ("g") flag is set. +```ocaml +(* Finds and prints successive matches *) + +let re = [%re "/ab*/g"] in +let str = "abbcdefabh" in + +let break = ref false in +while not !break do + match re |> Js.Re.exec ~str with + | None -> break := true + | Some result -> + Js.Nullable.iter (Js.Re.captures result).(0) ((fun match_ -> + let next = string_of_int (Js.Re.lastIndex re) in + Js.log ("Found " ^ match_ ^ ". Next match starts at " ^ next))) +done +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/lastIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) MDN +``` +val setLastIndex : t -> int -> unit +``` +sets the index at which the next match will start its search from +``` +val multiline : t -> bool +``` +returns a bool indicating whether the `multiline` flag is set +``` +val source : t -> string +``` +returns the pattern as a string +``` +val sticky : t -> bool +``` +returns a bool indicating whether the `sticky` flag is set +``` +val unicode : t -> bool +``` +returns a bool indicating whether the `unicode` flag is set +``` +val exec : str:string -> t -> result option +``` +executes a search on a given string using the given RegExp object +**returns** `Some` [`result`](./#type-result) if a match is found, `None` otherwise +```ocaml +(* Match "quick brown" followed by "jumps", ignoring characters in between + * Remember "brown" and "jumps" + * Ignore case + *) + +let re = [%re "/quick\s(brown).+?(jumps)/ig"] in +let result = re |. Js.Re.exec ~str:"The Quick Brown Fox Jumps Over The Lazy Dog" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/exec](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) MDN +``` +val test : str:string -> t -> bool +``` +tests whether the given RegExp object will match a given string +**returns** `true` if a match is found, `false` otherwise +```ocaml +(* A simple implementation of Js.String.startsWith *) + +let str = "hello world!" + +let startsWith target substring = + Js.Re.fromString ("^" ^ substring) + |. Js.Re.test ~str:target + +let () = Js.log (str |. startsWith "hello") (* prints "true" *) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) MDN \ No newline at end of file diff --git a/docs/api/melange/Js-Set.md b/docs/api/melange/Js-Set.md new file mode 100644 index 000000000..7224e0291 --- /dev/null +++ b/docs/api/melange/Js-Set.md @@ -0,0 +1,39 @@ +# Module `Js.Set` +Bindings to functions in `Set` +ES6 Set API +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val fromArray : 'a array -> 'a t +``` +``` +val toArray : 'a t -> 'a array +``` +``` +val size : 'a t -> int +``` +``` +val add : value:'a -> 'a t -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val delete : value:'a -> 'a t -> bool +``` +``` +val forEach : f:('a -> unit) -> 'a t -> unit +``` +``` +val has : value:'a -> 'a t -> bool +``` +``` +val values : 'a t -> 'a Js.iterator +``` +``` +val entries : 'a t -> ('a * 'a) Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-String.md b/docs/api/melange/Js-String.md new file mode 100644 index 000000000..669859455 --- /dev/null +++ b/docs/api/melange/Js-String.md @@ -0,0 +1,403 @@ +# Module `Js.String` +Bindings to the functions in `String.prototype` +JavaScript String API +``` +type t = string +``` +``` +val make : 'a -> t +``` +`make value` converts the given value to a string +```ocaml + make 3.5 = "3.5";; + make [|1;2;3|]) = "1,2,3";; +``` +``` +val fromCharCode : int -> t +``` +`fromCharCode n` creates a string containing the character corresponding to that number; *n* ranges from 0 to 65535. If out of range, the lower 16 bits of the value are used. Thus, `fromCharCode 0x1F63A` gives the same result as `fromCharCode 0xF63A`. +```ocaml + fromCharCode 65 = "A";; + fromCharCode 0x3c8 = {js|ψ|js};; + fromCharCode 0xd55c = {js|한|js};; + fromCharCode -64568 = {js|ψ|js};; +``` +``` +val fromCharCodeMany : int array -> t +``` +`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given numbers, using the same rules as `fromCharCode`. +```ocaml + fromCharCodeMany([|0xd55c, 0xae00, 33|]) = {js|한글!|js};; +``` +``` +val fromCodePoint : int -> t +``` +`fromCodePoint n` creates a string containing the character corresponding to that numeric code point. If the number is not a valid code point, **raises** `RangeError`. Thus, `fromCodePoint 0x1F63A` will produce a correct value, unlike `fromCharCode 0x1F63A`, and `fromCodePoint -5` will raise a `RangeError`. +```ocaml + fromCodePoint 65 = "A";; + fromCodePoint 0x3c8 = {js|ψ|js};; + fromCodePoint 0xd55c = {js|한|js};; + fromCodePoint 0x1f63a = {js|😺|js};; +``` +``` +val fromCodePointMany : int array -> t +``` +`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given code point numbers, using the same rules as `fromCodePoint`. +```ocaml + fromCodePointMany([|0xd55c; 0xae00; 0x1f63a|]) = {js|한글😺|js} +``` +``` +val length : t -> int +``` +`length s` returns the length of the given string. +```ocaml + length "abcd" = 4;; +``` +``` +val get : t -> int -> t +``` +`get s n` returns as a string the character at the given index number. If `n` is out of range, this function returns `undefined`, so at some point this function may be modified to return `t option`. +```ocaml + get "Reason" 0 = "R";; + get "Reason" 4 = "o";; + get {js|Rẽasöń|js} 5 = {js|ń|js};; +``` +``` +val charAt : index:int -> t -> t +``` +`charAt ~index s` gets the character at position `index` within string `s`. If `index` is negative or greater than the length of `s`, returns the empty string. If the string contains characters outside the range `\u0000-\uffff`, it will return the first 16-bit value at that position in the string. +```ocaml + charAt ~index:0 "Reason" = "R" + charAt ~index:12 "Reason" = ""; + charAt ~index:5 {js|Rẽasöń|js} = {js|ń|js} +``` +``` +val charCodeAt : index:int -> t -> float +``` +`charCodeAt s ~index` returns the character code at position `index` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to `0x10000`. The return type is `float` because this function returns `NaN` if `index` is less than zero or greater than the length of the string. +```ocaml + charCodeAt ~index:0 {js|😺|js} = 0xd83d + codePointAt ~index:0 {js|😺|js} = Some 0x1f63a +``` +``` +val codePointAt : index:int -> t -> int option +``` +`codePointAt s ~index` returns the code point at position `index` within string `s` as a `Some` value. The return value handles code points greater than or equal to `0x10000`. If there is no code point at the given position, the function returns `None`. +```ocaml + codePointAt ~index:1 {js|¿😺?|js} = Some 0x1f63a + codePointAt ~index:5 "abc" = None +``` +ES2015 +``` +val concat : other:t -> t -> t +``` +`concat ~other:str2 str1` returns a new string with `str2` added after `str1`. +```ocaml + concat ~other:"bell" "cow" = "cowbell";; +``` +``` +val concatMany : strings:t array -> t -> t +``` +`concatMany ~strings original` returns a new string consisting of each item of the array of strings `strings` added to the `original` string. +```ocaml + concatMany ~strings:[|"2nd"; "3rd"; "4th"|] "1st" = "1st2nd3rd4th";; +``` +``` +val endsWith : suffix:t -> ?len:int -> t -> bool +``` +`endsWith ~suffix ?len str` returns `true` if the `str` ends with `suffix`, `false` otherwise. If `len` is specified, \`endsWith\` only takes into account the first `len` characters. +```ocaml + endsWith ~suffix:"cd" ~len:4 "abcd" = true;; + endsWith ~suffix:"cd" ~len:3 "abcde" = false;; + endsWith ~suffix:"cde" ~len:99 "abcde" = true;; + endsWith ~suffix:"ple" ~len:7 "example.dat" = true;; + endsWith ~suffix:"World!" "Hello, World!" = true;; + endsWith ~suffix:"world!" "Hello, World!" = false;; (* case-sensitive *) + endsWith ~suffix:"World" "Hello, World!" = false;; (* exact match *) +``` +``` +val includes : search:t -> ?start:int -> t -> bool +``` +`includes ~search ?start s` returns `true` if `search` is found anywhere within `s` starting at character number `start` (where 0 is the first character), `false` otherwise. +```ocaml + includes ~search:"gram" "programmer" = true;; + includes ~search:"er" "programmer" = true;; + includes ~search:"pro" "programmer" = true;; + includes ~search:"xyz" "programmer" = false;; + includes ~search:"gram" ~start:1 "programmer" = true;; + includes ~search:"gram" ~start:4 "programmer" = false;; + includes ~search:{js|한|js} ~start:1 {js|대한민국|js} = true;; +``` +``` +val indexOf : search:t -> ?start:int -> t -> int +``` +`indexOf ~search ?start s` returns the position at which `search` was found within `s` starting at character position `start`, or `-1` if `search` is not found in that portion of `s`. The return value is relative to the beginning of the string, no matter where the search started from. +```ocaml + indexOf ~search:"ok" "bookseller" = 2;; + indexOf ~search:"sell" "bookseller" = 4;; + indexOf ~search:"ee" "beekeeper" = 1;; + indexOf ~search:"xyz" "bookseller" = -1;; + indexOf ~search:"ok" ~start:1 "bookseller" = 2;; + indexOf ~search:"sell" ~start:2 "bookseller" = 4;; + indexOf ~search:"sell" ~start:5 "bookseller" = -1;; +``` +``` +val lastIndexOf : search:t -> ?start:int -> t -> int +``` +`lastIndexOf ~search ~start s` returns the position of the *last* occurrence of `searchValue` within `s`, searching backwards from the given `start` position. Returns `-1` if `searchValue` is not in `s`. The return value is always relative to the beginning of the string. +```ocaml + lastIndexOf ~search:"ok" "bookseller" = 2;; + lastIndexOf ~search:"ee" "beekeeper" = 4;; + lastIndexOf ~search:"xyz" "abcdefg" = -1;; + lastIndexOf ~search:"ok" ~start:6 "bookseller" = 2;; + lastIndexOf ~search:"ee" ~start:8 "beekeeper" = 4;; + lastIndexOf ~search:"ee" ~start:3 "beekeeper" = 1;; + lastIndexOf ~search:"xyz" ~start:4 "abcdefg" = -1;; +``` +``` +val localeCompare : other:t -> t -> float +``` +`localeCompare ~other:comparison reference` returns: +- a negative value if `reference` comes before `comparison` in sort order +- zero if `reference` and `comparison` have the same sort order +- a positive value if `reference` comes after `comparison` in sort order +```ocaml + (localeCompare ~other:"ant" "zebra") > 0.0;; + (localeCompare ~other:"zebra" "ant") < 0.0;; + (localeCompare ~other:"cat" "cat") = 0.0;; + (localeCompare ~other:"cat" "CAT") > 0.0;; +``` +``` +val match_ : regexp:Js.re -> t -> t option array option +``` +`match ~regexp str` matches a string against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the `g` modifier, if there is a match, the return value is `Some array` where the array contains: +- The entire matched string +- Any capture groups if the `regexp` had parentheses +For regular expressions with the `g` modifier, a matched expression returns `Some array` with all the matched substrings and no capture groups. +```ocaml + match "The better bats" ~regexp:[%re "/b[aeiou]t/"] = Some [|"bet"|] + match "The better bats" ~regexp:[%re "/b[aeiou]t/g"] = Some [|"bet";"bat"|] + match "Today is 2018-04-05." ~regexp:[%re "/(\\d+)-(\\d+)-(\\d+)/"] = Some [|"2018-04-05"; "2018"; "04"; "05"|] + match "The large container." ~regexp:[%re "/b[aeiou]g/"] = None +``` +``` +val normalize : ?form:[ `NFC | `NFD | `NFKC | `NFKD ] -> t -> t +``` +`normalize ~form str` returns the normalized Unicode string using the specified form of normalization, which may be one of: +- `` `NFC `` — Normalization Form Canonical Composition. +- `` `NFD `` — Normalization Form Canonical Decomposition. +- `` `NFKC `` — Normalization Form Compatibility Composition. +- `` `NFKD `` — Normalization Form Compatibility Decomposition. +If `form` is omitted, `` `NFC `` is used. +Consider the character `ã`, which can be represented as the single codepoint `\u00e3` or the combination of a lower case letter A `\u0061` and a combining tilde `\u0303`. Normalization ensures that both can be stored in an equivalent binary representation. +see [https://www.unicode.org/reports/tr15/tr15-45.html](https://www.unicode.org/reports/tr15/tr15-45.html) Unicode technical report for details +``` +val repeat : count:int -> t -> t +``` +`repeat ~count s` returns a string that consists of `count` repetitions of `s`. Raises `RangeError` if `n` is negative. +```ocaml + repeat ~count:3 "ha" = "hahaha" + repeat ~count:0 "empty" = "" +``` +``` +val replace : search:t -> replacement:t -> t -> t +``` +`replace ~search ~replacement string` returns a new string which is identical to `string` except with the first matching instance of `search` replaced by `replacement`. +`search` is treated as a verbatim string to match, not a regular expression. +```ocaml + replace ~search:"old" ~replacement:"new" "old string" = "new string" + replace ~search:"the" ~replacement:"this" "the cat and the dog" = "this cat and the dog" +``` +``` +val replaceByRe : regexp:Js.re -> replacement:t -> t -> t +``` +`replaceByRe ~regexp ~replacement string` returns a new string where occurrences matching `regexp` have been replaced by `replacement`. +```ocaml + replaceByRe ~regexp:[%re "/[aeiou]/g"] ~replacement:"x" "vowels be gone" = "vxwxls bx gxnx" + replaceByRe ~regexp:[%re "/(\\w+) (\\w+)/"] ~replacement:"$2, $1" "Juan Fulano" = "Fulano, Juan" +``` +``` +val unsafeReplaceBy0 : regexp:Js.re -> f:(t -> int -> t -> t) -> t -> t +``` +`unsafeReplaceBy0 ~regexp ~f s` returns a new string with some or all matches of a pattern with no capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the offset at which the match begins, and the whole string being matched +```ocaml +let str = "beautiful vowels" +let re = [%re "/[aeiou]/g"] +let matchFn matchPart offset wholeString = Js.String.toUpperCase matchPart + +let replaced = Js.String.unsafeReplaceBy0 ~regexp:re ~f:matchFn str + +let () = Js.log replaced (* prints "bEAUtifUl vOwEls" *) +``` +@see \ MDN +``` +val unsafeReplaceBy1 : regexp:Js.re -> f:(t -> t -> int -> t -> t) -> t -> t +``` +`unsafeReplaceBy1 ~regexp ~f s` returns a new string with some or all matches of a pattern with one set of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. +```ocaml +let str = "increment 23" +let re = [%re "/increment (\\d+)/g"] +let matchFn matchPart p1 offset wholeString = + wholeString ^ " is " ^ (string_of_int ((int_of_string p1) + 1)) + +let replaced = Js.String.unsafeReplaceBy1 ~regexp:re ~f:matchFn str + +let () = Js.log replaced (* prints "increment 23 is 24" *) +``` +@see \ MDN +``` +val unsafeReplaceBy2 : + regexp:Js.re -> + f:(t -> t -> t -> int -> t -> t) -> + t -> + t +``` +`unsafeReplaceBy2 ~regexp ~f s` returns a new string with some or all matches of a pattern with two sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. +```ocaml +let str = "7 times 6" +let re = [%re "/(\\d+) times (\\d+)/"] +let matchFn matchPart p1 p2 offset wholeString = + string_of_int ((int_of_string p1) * (int_of_string p2)) + +let replaced = Js.String.unsafeReplaceBy2 ~regexp:re ~f:matchFn str + +let () = Js.log replaced (* prints "42" *) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN +``` +val unsafeReplaceBy3 : + regexp:Js.re -> + f:(t -> t -> t -> t -> int -> t -> t) -> + t -> + t +``` +`unsafeReplaceBy3 ~regexp ~f s` returns a new string with some or all matches of a pattern with three sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN +``` +val search : regexp:Js.re -> t -> int +``` +`search ~regexp str` returns the starting position of the first match of `regexp` in the given `str`, or \-1 if there is no match. +```ocaml +search ~regexp:[%re "/\\d+/"] "testing 1 2 3" = 8;; +search ~regexp:[%re "/\\d+/"] "no numbers" = -1;; +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`slice ?start ?end str` returns the substring of `str` starting at character `start` up to but not including `end` +If either `start` or `end` is negative, then it is evaluated as `length str - start` (or `length str - end`). +If `end` is greater than the length of `str`, then it is treated as `length str`. +If `start` is greater than `end`, `slice` returns the empty string. +```ocaml + slice ~start:2 ~end_:5 "abcdefg" = "cde";; + slice ~start:2 ~end_:9 "abcdefg" = "cdefg";; + slice ~start:(-4) ~end_:(-2) "abcdefg" = "de";; + slice ~start:5 ~end_:1 "abcdefg" = "";; +``` +``` +val split : ?sep:t -> ?limit:int -> t -> t array +``` +`split ?sep ?limit str` splits the given `str` at every occurrence of `sep` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. +```ocaml + split ~sep:"/" ~limit: 3 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"|];; + split ~sep:"/" ~limit: 0 "ant/bee/cat/dog/elk" = [| |];; + split ~sep:"/" ~limit: 9 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"; "dog"; "elk"|];; +``` +``` +val splitByRe : regexp:Js.re -> ?limit:int -> t -> t option array +``` +`splitByRe str ~regexp ?limit ()` splits the given `str` at every occurrence of `regexp` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. +```ocaml + splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:3 "one: two: three: four" = [|"one"; "two"; "three"|];; + splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:0 "one: two: three: four" = [| |];; + splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:8 "one: two: three: four" = [|"one"; "two"; "three"; "four"|];; +``` +; +``` +val startsWith : prefix:t -> ?start:int -> t -> bool +``` +`startsWith ~prefix ?start str` returns `true` if the `str` starts with `prefix` starting at position `start`, `false` otherwise. If `start` is negative, the search starts at the beginning of `str`. +```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;; +``` +``` +val substr : ?start:int -> ?len:int -> t -> t +``` +`substr ?start ?len str` returns the substring of `str` of length `len` starting at position `start`. +If `start` is less than zero, the starting position is the length of `str` +- `start`. +If `start` is greater than or equal to the length of `str`, returns the empty string. +If `len` is less than or equal to zero, returns the empty string. +```ocaml + substr ~start:3 ~len:4 "abcdefghij" = "defghij" + substr ~start:(-3) ~len:4 "abcdefghij" = "hij" + substr ~start:12 ~len:2 "abcdefghij" = "" +``` +deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/substr\#sect1 +``` +val substring : ?start:int -> ?end_:int -> t -> t +``` +`substring ~start ~end_ str` returns characters `start` up to but not including `end_` from `str`. +If `start` is less than zero, it is treated as zero. +If `end_` is zero or negative, the empty string is returned. +If `start` is greater than `end_`, the start and finish points are swapped. +```ocaml + substring ~start:3 ~end_:6 "playground" = "ygr";; + substring ~start:6 ~end_:3 "playground" = "ygr";; + substring ~start:4 ~end_:12 "playground" = "ground";; +``` +``` +val toLowerCase : t -> t +``` +`toLowerCase str` converts `str` to lower case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can give different results depending upon context, for example with the Greek letter sigma, which has two different lower case forms when it is the last character in a string or not. +```ocaml + toLowerCase "ABC" = "abc";; + toLowerCase {js|ΣΠ|js} = {js|σπ|js};; + toLowerCase {js|ΠΣ|js} = {js|πς|js};; +``` +``` +val toLocaleLowerCase : t -> t +``` +`toLocaleLowerCase str` converts `str` to lower case using the current locale +``` +val toUpperCase : t -> t +``` +`toUpperCase str` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can expand the number of letters in the result; for example the German `ß` capitalizes to two `S`es in a row. +```ocaml + toUpperCase "abc" = "ABC";; + toUpperCase {js|Straße|js} = {js|STRASSE|js};; + toUpperCase {js|πς|js} = {js|ΠΣ|js};; +``` +``` +val toLocaleUpperCase : t -> t +``` +`toLocaleUpperCase str` converts `str` to upper case using the current locale +``` +val trim : t -> t +``` +`trim str` returns a string that is `str` with whitespace stripped from both ends. Internal whitespace is not removed. +```ocaml + trim " abc def " = "abc def" + trim "\n\r\t abc def \n\n\t\r " = "abc def" +``` +``` +val anchor : name:t -> t -> t +``` +`anchor ~name:anchorName anchorText` creates a string with an HTML `` element with `name` attribute of `anchorName` and `anchorText` as its content. +```ocaml + anchor ~name:"page1" "Page One" = "Page One" +``` +deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/anchor\#sect1 +``` +val link : href:t -> t -> t +``` +`link ~href:urlText linkText` creates a string with an HTML `` element with `href` attribute of `urlText` and `linkText` as its content. +```ocaml + link ~href:"page2.html" "Go to page two" = "Go to page two" +``` +deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/link\#sect1 +``` +val unsafeToArrayLike : t -> t Js.array_like +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-ArrayBuffer.md b/docs/api/melange/Js-Typed_array-ArrayBuffer.md new file mode 100644 index 000000000..50d3ea15f --- /dev/null +++ b/docs/api/melange/Js-Typed_array-ArrayBuffer.md @@ -0,0 +1,16 @@ +# Module `Typed_array.ArrayBuffer` +The underlying buffer that the typed arrays provide views of +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) MDN +``` +type t = Js.arrayBuffer +``` +``` +val make : int -> t +``` +takes length. initializes elements to 0 +``` +val byteLength : t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> Js.arrayBuffer +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-DataView.md b/docs/api/melange/Js-Typed_array-DataView.md new file mode 100644 index 000000000..02c62fac5 --- /dev/null +++ b/docs/api/melange/Js-Typed_array-DataView.md @@ -0,0 +1,105 @@ +# Module `Typed_array.DataView` +The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) MDN +``` +type t +``` +``` +val make : Js.arrayBuffer -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val getInt8 : int -> t -> int +``` +``` +val getUint8 : int -> t -> int +``` +``` +val getInt16 : int -> t -> int +``` +``` +val getInt16LittleEndian : int -> t -> int +``` +``` +val getUint16 : int -> t -> int +``` +``` +val getUint16LittleEndian : int -> t -> int +``` +``` +val getInt32 : int -> t -> int +``` +``` +val getInt32LittleEndian : int -> t -> int +``` +``` +val getUint32 : int -> t -> int +``` +``` +val getUint32LittleEndian : int -> t -> int +``` +``` +val getFloat32 : int -> t -> float +``` +``` +val getFloat32LittleEndian : int -> t -> float +``` +``` +val getFloat64 : int -> t -> float +``` +``` +val getFloat64LittleEndian : int -> t -> float +``` +``` +val setInt8 : int -> int -> t -> unit +``` +``` +val setUint8 : int -> int -> t -> unit +``` +``` +val setInt16 : int -> int -> t -> unit +``` +``` +val setInt16LittleEndian : int -> int -> t -> unit +``` +``` +val setUint16 : int -> int -> t -> unit +``` +``` +val setUint16LittleEndian : int -> int -> t -> unit +``` +``` +val setInt32 : int -> int -> t -> unit +``` +``` +val setInt32LittleEndian : int -> int -> t -> unit +``` +``` +val setUint32 : int -> int -> t -> unit +``` +``` +val setUint32LittleEndian : int -> int -> t -> unit +``` +``` +val setFloat32 : int -> float -> t -> unit +``` +``` +val setFloat32LittleEndian : int -> float -> t -> unit +``` +``` +val setFloat64 : int -> float -> t -> unit +``` +``` +val setFloat64LittleEndian : int -> float -> t -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Float32Array.md b/docs/api/melange/Js-Typed_array-Float32Array.md new file mode 100644 index 000000000..e1e08788f --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Float32Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Float32Array` +``` +type elt = float +``` +``` +type 'a typed_array = Js.float32Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Float64Array.md b/docs/api/melange/Js-Typed_array-Float64Array.md new file mode 100644 index 000000000..e060e474a --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Float64Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Float64Array` +``` +type elt = float +``` +``` +type 'a typed_array = Js.float64Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Int16Array.md b/docs/api/melange/Js-Typed_array-Int16Array.md new file mode 100644 index 000000000..d77ce67b4 --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Int16Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Int16Array` +``` +type elt = int +``` +``` +type 'a typed_array = Js.int16Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Int32Array.md b/docs/api/melange/Js-Typed_array-Int32Array.md new file mode 100644 index 000000000..6bf740756 --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Int32Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Int32Array` +``` +type elt = int32 +``` +``` +type 'a typed_array = Js.int32Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Int8Array.md b/docs/api/melange/Js-Typed_array-Int8Array.md new file mode 100644 index 000000000..27ed0e8e0 --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Int8Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Int8Array` +``` +type elt = int +``` +``` +type 'a typed_array = Js.int8Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Uint16Array.md b/docs/api/melange/Js-Typed_array-Uint16Array.md new file mode 100644 index 000000000..b707c4554 --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Uint16Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Uint16Array` +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint16Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Uint32Array.md b/docs/api/melange/Js-Typed_array-Uint32Array.md new file mode 100644 index 000000000..8bbb4b111 --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Uint32Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Uint32Array` +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint32Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Uint8Array.md b/docs/api/melange/Js-Typed_array-Uint8Array.md new file mode 100644 index 000000000..9a7a9fb6e --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Uint8Array.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Uint8Array` +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint8Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md b/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md new file mode 100644 index 000000000..c3705dc55 --- /dev/null +++ b/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md @@ -0,0 +1,161 @@ +# Module `Typed_array.Uint8ClampedArray` +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint8ClampedArray +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Typed_array.md b/docs/api/melange/Js-Typed_array.md new file mode 100644 index 000000000..0a25633c6 --- /dev/null +++ b/docs/api/melange/Js-Typed_array.md @@ -0,0 +1,39 @@ +# Module `Js.Typed_array` +Bindings to the functions in `TypedArray.prototype` +JavaScript Typed Array API +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) MDN +``` +module ArrayBuffer : sig ... end +``` +The underlying buffer that the typed arrays provide views of +``` +module Int8Array : sig ... end +``` +``` +module Uint8Array : sig ... end +``` +``` +module Uint8ClampedArray : sig ... end +``` +``` +module Int16Array : sig ... end +``` +``` +module Uint16Array : sig ... end +``` +``` +module Int32Array : sig ... end +``` +``` +module Uint32Array : sig ... end +``` +``` +module Float32Array : sig ... end +``` +``` +module Float64Array : sig ... end +``` +``` +module DataView : sig ... end +``` +The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. \ No newline at end of file diff --git a/docs/api/melange/Js-Types.md b/docs/api/melange/Js-Types.md new file mode 100644 index 000000000..768992327 --- /dev/null +++ b/docs/api/melange/Js-Types.md @@ -0,0 +1,102 @@ +# Module `Js.Types` +Utility functions for runtime reflection on JS types +``` +type symbol +``` +Js symbol type only available in ES6 +``` +type bigint_val +``` +Js bigint type only available in ES2020 +``` +type obj_val +``` +``` +type undefined_val +``` +This type has only one value `undefined` +``` +type null_val +``` +This type has only one value `null` +``` +type function_val +``` +``` +type _ t = +``` +``` +| Undefined : undefined_val t +``` +``` +| Null : null_val t +``` +``` +| Boolean : bool t +``` +``` +| Number : float t +``` +``` +| String : string t +``` +``` +| Function : function_val t +``` +``` +| Object : obj_val t +``` +``` +| Symbol : symbol t +``` +``` +| BigInt : bigint_val t +``` +``` + +``` +``` +val test : 'a -> 'b t -> bool +``` +```ocaml +test "x" String = true +``` +``` +type tagged_t = +``` +``` +| JSFalse +``` +``` +| JSTrue +``` +``` +| JSNull +``` +``` +| JSUndefined +``` +``` +| JSNumber of float +``` +``` +| JSString of string +``` +``` +| JSFunction of function_val +``` +``` +| JSObject of obj_val +``` +``` +| JSSymbol of symbol +``` +``` +| JSBigInt of bigint_val +``` +``` + +``` +``` +val classify : 'a -> tagged_t +``` \ No newline at end of file diff --git a/docs/api/melange/Js-Undefined.md b/docs/api/melange/Js-Undefined.md new file mode 100644 index 000000000..cc431b358 --- /dev/null +++ b/docs/api/melange/Js-Undefined.md @@ -0,0 +1,65 @@ +# Module `Js.Undefined` +Utility functions on [`undefined`](./Js.md#type-undefined) +Provides functionality for dealing with the `'a Js.undefined` type +``` +type +'a t = 'a Js.undefined +``` +Local alias for `'a Js.undefined` +``` +val return : 'a -> 'a t +``` +Constructs a value of `'a Js.undefined` containing a value of `'a` +``` +val testAny : 'a -> bool +``` +Returns `true` if the given value is `empty` (`undefined`) +``` +val empty : 'a t +``` +The empty value, `undefined` +``` +val getUnsafe : 'a t -> 'a +``` +``` +val getExn : 'a t -> 'a +``` +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +``` +val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t +``` +Bind the contained value using the given function +If `'a Js.undefined` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.undefined` +```ocaml +let maybeGreetWorld (maybeGreeting: string Js.undefined) = + Js.Undefined.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") +``` +``` +val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit +``` +Iterates over the contained value with the given function +If `'a Js.undefined` contains a value, that value is unwrapped and applied to the given function. +```ocaml +let maybeSay (maybeMessage: string Js.undefined) = + Js.Undefined.iter maybeMessage ~f:(fun message -> Js.log message) +``` +``` +val fromOption : 'a option -> 'a t +``` +Maps `'a option` to `'a Js.undefined` + + +
Some a -> return a +
None -> empty +
+ +``` +val toOption : 'a t -> 'a option +``` +Maps `'a Js.undefined` to `'a option` + + +
return a -> Some a +
empty -> None +
diff --git a/docs/api/melange/Js-WeakMap.md b/docs/api/melange/Js-WeakMap.md new file mode 100644 index 000000000..00b9e32c9 --- /dev/null +++ b/docs/api/melange/Js-WeakMap.md @@ -0,0 +1,21 @@ +# Module `Js.WeakMap` +Bindings to functions in `WeakMap` +ES6 WeakMap API +``` +type ('k, 'v) t +``` +``` +val make : unit -> ('k, 'v) t +``` +``` +val get : key:'k Js.dict -> ('k, 'v) t -> 'v option +``` +``` +val has : key:'k Js.dict -> ('k, 'v) t -> bool +``` +``` +val set : key:'k Js.dict -> value:'v -> ('k, 'v) t -> ('k, 'v) t +``` +``` +val delete : key:'k Js.dict -> ('k, 'v) t -> bool +``` \ No newline at end of file diff --git a/docs/api/melange/Js-WeakSet.md b/docs/api/melange/Js-WeakSet.md new file mode 100644 index 000000000..5d8dfb549 --- /dev/null +++ b/docs/api/melange/Js-WeakSet.md @@ -0,0 +1,18 @@ +# Module `Js.WeakSet` +Bindings to functions in `WeakSet` +ES6 WeakSet API +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val add : value:'a Js.dict -> 'a t -> 'a t +``` +``` +val delete : value:'a Js.dict -> 'a t -> bool +``` +``` +val has : value:'a Js.dict -> 'a t -> bool +``` \ No newline at end of file diff --git a/docs/api/melange/Js.md b/docs/api/melange/Js.md new file mode 100644 index 000000000..641dfc46c --- /dev/null +++ b/docs/api/melange/Js.md @@ -0,0 +1,266 @@ +# Module `Js` +``` +type +'a null +``` +A value of this type can be either `null` or `'a`. This type is the same as type `t` in [`Null`](./Js-Null.md) +``` +type +'a undefined +``` +A value of this type can be either `undefined` or `'a`. This type is the same as type `t` in [`Undefined`](./Js-Undefined.md) +``` +type +'a nullable +``` +A value of this type can be `undefined`, `null` or `'a`. This type is the same as type `t` n [`Nullable`](./Js-Nullable.md) +``` +type re +``` +The type for JavaScript `RegExp` +``` +type 'a dict +``` +The type for a simple key-value dictionary abstraction over native JavaScript objects +``` +type 'a iterator +``` +The type for JavaScript iterators +``` +type 'a array_like +``` +The type for array-like objects in JavaScript +``` +type bigint +``` +The type for JavaScript BigInt +``` +type +'a promise +``` +The type for JavaScript Promise +``` +type blob +``` +The type for JavaScript [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) +``` +type file +``` +The type for JavaScript [File](https://developer.mozilla.org/en-US/docs/Web/API/File) +``` +type arrayBuffer +``` +``` +type int8Array +``` +``` +type uint8Array +``` +``` +type uint8ClampedArray +``` +``` +type int16Array +``` +``` +type uint16Array +``` +``` +type int32Array +``` +``` +type uint32Array +``` +``` +type float32Array +``` +``` +type float64Array +``` +``` +val toOption : 'a nullable -> 'a option +``` +``` +val undefinedToOption : 'a undefined -> 'a option +``` +``` +val nullToOption : 'a null -> 'a option +``` +``` +val isNullable : 'a nullable -> bool +``` +``` +val import : 'a -> 'a promise +``` +TODO(anmonteiro): document +``` +val testAny : 'a -> bool +``` +The same as [`isNullable`](./#val-isNullable) except that it is more permissive on the types of input +``` +val null : 'a null +``` +The same as `empty` in [`Js.Null`](./Js-Null.md) will be compiled as `null` +``` +val undefined : 'a undefined +``` +The same as `empty` [`Js.Undefined`](./Js-Undefined.md) will be compiled as `undefined` +``` +val typeof : 'a -> string +``` +`typeof x` will be compiled as `typeof x` in JS Please consider functions in [`Types`](./Js-Types.md) for a type safe way of reflection +``` +val log : 'a -> unit +``` +A convenience function to log everything +``` +val log2 : 'a -> 'b -> unit +``` +``` +val log3 : 'a -> 'b -> 'c -> unit +``` +``` +val log4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val logMany : 'a array -> unit +``` +A convenience function to log more than 4 arguments +``` +val eqNull : 'a -> 'a null -> bool +``` +``` +val eqUndefined : 'a -> 'a undefined -> bool +``` +``` +val eqNullable : 'a -> 'a nullable -> bool +``` +##### Operators +``` +val unsafe_lt : 'a -> 'a -> bool +``` +`unsafe_lt a b` will be compiled as `a < b`. It is marked as unsafe, since it is impossible to give a proper semantics for comparision which applies to any type +``` +val unsafe_le : 'a -> 'a -> bool +``` +`unsafe_le a b` will be compiled as `a <= b`. See also [`unsafe_lt`](./#val-unsafe_lt) +``` +val unsafe_gt : 'a -> 'a -> bool +``` +`unsafe_gt a b` will be compiled as `a > b`. See also [`unsafe_lt`](./#val-unsafe_lt) +``` +val unsafe_ge : 'a -> 'a -> bool +``` +`unsafe_ge a b` will be compiled as `a >= b`. See also [`unsafe_lt`](./#val-unsafe_lt) +Types for JS objects +``` +type 'a t +``` +This used to be mark a Js object type. +``` +module Exn : sig ... end +``` +Utilities for dealing with Js exceptions +``` +module String : sig ... end +``` +Bindings to the functions in `String.prototype` +``` +module Null : sig ... end +``` +Utility functions on [`null`](./#type-null) +``` +module Undefined : sig ... end +``` +Utility functions on [`undefined`](./#type-undefined) +``` +module Nullable : sig ... end +``` +Utility functions on [`nullable`](./#type-nullable) +``` +module Array : sig ... end +``` +Bindings to the functions in `Array.prototype` +``` +module Re : sig ... end +``` +Bindings to the functions in `RegExp.prototype` +``` +module Promise : sig ... end +``` +Bindings to JS `Promise` functions +``` +module Date : sig ... end +``` +Bindings to the functions in JS's `Date.prototype` +``` +module Dict : sig ... end +``` +Utility functions to treat a JS object as a dictionary +``` +module Global : sig ... end +``` +Bindings to functions in the JS global namespace +``` +module Json : sig ... end +``` +Utility functions to manipulate JSON values +``` +module Math : sig ... end +``` +Bindings to the functions in the `Math` object +``` +module Obj : sig ... end +``` +Utility functions on \`Js.t\` JS objects +``` +module Typed_array : sig ... end +``` +Bindings to the functions in `TypedArray.prototype` +``` +module Types : sig ... end +``` +Utility functions for runtime reflection on JS types +``` +module Float : sig ... end +``` +Bindings to functions in JavaScript's `Number` that deal with floats +``` +module Int : sig ... end +``` +Bindings to functions in JavaScript's `Number` that deal with ints +``` +module Bigint : sig ... end +``` +Bindings to functions in JavaScript's `BigInt` +``` +module Console : sig ... end +``` +``` +module Set : sig ... end +``` +Bindings to functions in `Set` +``` +module WeakSet : sig ... end +``` +Bindings to functions in `WeakSet` +``` +module Map : sig ... end +``` +Bindings to functions in `Map` +``` +module WeakMap : sig ... end +``` +Bindings to functions in `WeakMap` +``` +module Iterator : sig ... end +``` +Bindings to functions on `Iterator` +``` +module Blob : sig ... end +``` +Bindings to Blob +``` +module File : sig ... end +``` +Bindings to File +``` +module FormData : sig ... end +``` +Bindings to FormData \ No newline at end of file diff --git a/docs/api/melange/Node-Buffer.md b/docs/api/melange/Node-Buffer.md new file mode 100644 index 000000000..42d07998a --- /dev/null +++ b/docs/api/melange/Node-Buffer.md @@ -0,0 +1,53 @@ +# Module `Node.Buffer` +Node Buffer API +``` +type t = Node.buffer +``` +``` +type encoding = [ +``` +``` +| `ascii +``` +``` +| `utf8 +``` +``` +| `utf16le +``` +``` +| `ucs2 +``` +``` +| `base64 +``` +``` +| `base64url +``` +``` +| `latin1 +``` +``` +| `binary +``` +``` +| `hex +``` +``` + ] +``` +``` +val isBuffer : 'a -> bool +``` +``` +val fromString : string -> t +``` +``` +val fromStringWithEncoding : string -> encoding:encoding -> t +``` +``` +val toString : ?encoding:encoding -> t -> string +``` +``` +val concat : t array -> t +``` \ No newline at end of file diff --git a/docs/api/melange/Node-Child_process.md b/docs/api/melange/Node-Child_process.md new file mode 100644 index 000000000..04e8a7034 --- /dev/null +++ b/docs/api/melange/Node-Child_process.md @@ -0,0 +1,27 @@ +# Module `Node.Child_process` +Node Child Process API +``` +type option +``` +``` +val option : ?cwd:string -> ?encoding:string -> unit -> option +``` +``` +val execSync : string -> option -> string +``` +``` +type spawnResult +``` +``` +val spawnSync : string -> spawnResult +``` +``` +val readAs : + spawnResult -> + < pid : int + ; status : int Js.null + ; signal : string Js.null + ; stdout : Node.string_buffer Js.null + ; stderr : Node.string_buffer Js.null > + Js.t +``` \ No newline at end of file diff --git a/docs/api/melange/Node-Fs-Watch.md b/docs/api/melange/Node-Fs-Watch.md new file mode 100644 index 000000000..96eab747a --- /dev/null +++ b/docs/api/melange/Node-Fs-Watch.md @@ -0,0 +1,30 @@ +# Module `Fs.Watch` +``` +type t +``` +``` +type config +``` +``` +val config : + ?persistent:bool -> + ?recursive:bool -> + ?encoding:Js.String.t -> + unit -> + config +``` +``` +val watch : string -> ?config:config -> unit -> t +``` +there is no need to accept listener, since we return a `watcher` back it can register event listener there. Currently we introduce a type `string_buffer`, for the `filename`, it will be `Buffer` when the encoding is `` `utf8 ``. This is dependent type which can be tracked by GADT in some way, but to make things simple, let's just introduce an or type +``` +val on : + t -> + f: + [ `change of (string -> Node.string_buffer -> unit) Js.Fn.arity2 + | `error of unit Js.Fn.arity0 ] -> + t +``` +``` +val close : t -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Node-Fs.md b/docs/api/melange/Node-Fs.md new file mode 100644 index 000000000..c3dbd68e0 --- /dev/null +++ b/docs/api/melange/Node-Fs.md @@ -0,0 +1,105 @@ +# Module `Node.Fs` +Node FS API +see [https://blogs.janestreet.com/a-and-a/](https://blogs.janestreet.com/a-and-a/) refernce documentation +``` +val readdirSync : string -> string array +``` +Most fs functions let you omit the callback argument. If you do, a default callback is used that rethrows errors. To get a trace to the original call site, set the \`NODE\_DEBUG\` environment variable. +``` +val renameSync : string -> string -> unit +``` +``` +type fd = private int +``` +``` +type path = string +``` +The relative path to a filename can be used. Remember, however, that this path will be relative to `process.cwd()`. +``` +module Watch : sig ... end +``` +``` +val ftruncateSync : fd -> int -> unit +``` +``` +val truncateSync : string -> int -> unit +``` +``` +val chownSync : string -> uid:int -> gid:int -> unit +``` +``` +val fchownSync : fd -> uid:int -> gid:int -> unit +``` +``` +val readlinkSync : string -> string +``` +``` +val unlinkSync : string -> unit +``` +``` +val rmdirSync : string -> unit +``` +``` +val openSync : + path -> + [ `Read + | `Read_write + | `Read_write_sync + | `Write + | `Write_fail_if_exists + | `Write_read + | `Write_read_fail_if_exists + | `Append + | `Append_fail_if_exists + | `Append_read + | `Append_read_fail_if_exists ] -> + unit +``` +``` +type encoding = [ +``` +``` +| `hex +``` +``` +| `utf8 +``` +``` +| `ascii +``` +``` +| `latin1 +``` +``` +| `base64 +``` +``` +| `ucs2 +``` +``` +| `base64 +``` +``` +| `binary +``` +``` +| `utf16le +``` +``` + ] +``` +``` +val readFileSync : string -> encoding -> string +``` +``` +val readFileAsUtf8Sync : string -> string +``` +``` +val existsSync : string -> bool +``` +``` +val writeFileSync : string -> string -> encoding -> unit +``` +``` +val writeFileAsUtf8Sync : string -> string -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Node-Module.md b/docs/api/melange/Node-Module.md new file mode 100644 index 000000000..0cf22c308 --- /dev/null +++ b/docs/api/melange/Node-Module.md @@ -0,0 +1,5 @@ +# Module `Node.Module` +Node Module API +``` +val module_ : < __cache : Node.node_module Js.Dict.t > Js.t +``` \ No newline at end of file diff --git a/docs/api/melange/Node-Path.md b/docs/api/melange/Node-Path.md new file mode 100644 index 000000000..083fb8e33 --- /dev/null +++ b/docs/api/melange/Node-Path.md @@ -0,0 +1,53 @@ +# Module `Node.Path` +Node Path API +``` +val basename : string -> string +``` +``` +val basename_ext : string -> string -> string +``` +``` +val delimiter : string +``` +``` +val dirname : string -> string +``` +``` +val dirname_ext : string -> string -> string +``` +``` +type pathObject = + < dir : string + ; root : string + ; base : string + ; name : string + ; ext : string > + Js.t +``` +``` +val format : pathObject -> string +``` +``` +val isAbsolute : string -> bool +``` +``` +val join2 : string -> string -> string +``` +``` +val join : string array -> string +``` +``` +val normalize : string -> string +``` +``` +val parse : string -> pathObject +``` +``` +val relative : from:string -> to_:string -> unit -> string +``` +``` +val resolve : string -> string -> string +``` +``` +val sep : string +``` \ No newline at end of file diff --git a/docs/api/melange/Node-Process.md b/docs/api/melange/Node-Process.md new file mode 100644 index 000000000..d359e26d3 --- /dev/null +++ b/docs/api/melange/Node-Process.md @@ -0,0 +1,35 @@ +# Module `Node.Process` +``` +type t = + < argv : string array + ; arch : string + ; abort : unit Js.OO.Meth.arity0 + ; chdir : (string -> unit) Js.OO.Meth.arity1 + ; cwd : string Js.OO.Meth.arity0 + ; disconnect : unit Js.OO.Meth.arity0 + ; platform : string + ; env : string Js.Dict.t > + Js.t +``` +``` +val process : t +``` +``` +val argv : string array +``` +``` +val exit : int -> 'a +``` +``` +val cwd : unit -> string +``` +``` +val uptime : t -> unit -> float +``` +The process.uptime() method returns the number of seconds the current Node.js process has been running.) +``` +val putEnvVar : string -> string -> unit +``` +``` +val deleteEnvVar : string -> unit +``` \ No newline at end of file diff --git a/docs/api/melange/Node.md b/docs/api/melange/Node.md new file mode 100644 index 000000000..2b7829da6 --- /dev/null +++ b/docs/api/melange/Node.md @@ -0,0 +1,66 @@ +# Module `Node` +``` +type node_exports +``` +``` +type node_module = + < id : string + ; exports : node_exports + ; parent : node_module Js.nullable + ; filename : string + ; loaded : bool + ; children : node_module array + ; paths : string array > + Js.t +``` +``` +type node_require = + < main : node_module Js.undefined + ; resolve : (string -> string) Js.Fn.arity1 > + Js.t +``` +``` +type string_buffer +``` +``` +type buffer +``` +``` +type _ string_buffer_kind = +``` +``` +| String : string string_buffer_kind +``` +``` +| Buffer : buffer string_buffer_kind +``` +``` + +``` +``` +val test : string_buffer -> 't string_buffer_kind * 't +``` +We expect a good inliner will eliminate such boxing in the future +``` +module Path : sig ... end +``` +Node Path API +``` +module Fs : sig ... end +``` +Node FS API +``` +module Process : sig ... end +``` +``` +module Module : sig ... end +``` +Node Module API +``` +module Buffer : sig ... end +``` +Node Buffer API +``` +module Child_process : sig ... end +``` +Node Child Process API \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Arg.md b/docs/api/melange/Stdlib-Arg.md new file mode 100644 index 000000000..330c16a09 --- /dev/null +++ b/docs/api/melange/Stdlib-Arg.md @@ -0,0 +1,215 @@ +# Module `Stdlib.Arg` +Parsing of command line arguments. +This module provides a general mechanism for extracting options and arguments from the command line to the program. For example: +```ocaml + let usage_msg = "append [-verbose] [] ... -o " + let verbose = ref false + let input_files = ref [] + let output_file = ref "" + + let anon_fun filename = + input_files := filename::!input_files + + let speclist = + [("-verbose", Arg.Set verbose, "Output debug information"); + ("-o", Arg.Set_string output_file, "Set output file name")] + + let () = + Arg.parse speclist anon_fun usage_msg; + (* Main functionality here *) +``` +Syntax of command lines: A keyword is a character string starting with a `-`. An option is a keyword alone or followed by an argument. The types of keywords are: `Unit`, `Bool`, `Set`, `Clear`, `String`, `Set_string`, `Int`, `Set_int`, `Float`, `Set_float`, `Tuple`, `Symbol`, `Rest`, `Rest_all` and `Expand`. +`Unit`, `Set` and `Clear` keywords take no argument. +A `Rest` or `Rest_all` keyword takes the remainder of the command line as arguments. (More explanations below.) +Every other keyword takes the following word on the command line as argument. For compatibility with GNU getopt\_long, `keyword=arg` is also allowed. Arguments not preceded by a keyword are called anonymous arguments. +Examples (`cmd` is assumed to be the command name): +- `cmd -flag `(a unit option) +- `cmd -int 1 `(an int option with argument `1`) +- `cmd -string foobar `(a string option with argument `"foobar"`) +- `cmd -float 12.34 `(a float option with argument `12.34`) +- `cmd a b c `(three anonymous arguments: `"a"`, `"b"`, and `"c"`) +- `cmd a b -- c d `(two anonymous arguments and a rest option with two arguments) +`Rest` takes a function that is called repeatedly for each remaining command line argument. `Rest_all` takes a function that is called once, with the list of all remaining arguments. +Note that if no arguments follow a `Rest` keyword then the function is not called at all whereas the function for a `Rest_all` keyword is called with an empty list. +alert unsynchronized\_access The Arg module relies on a mutable global state, parsing functions should only be called from a single domain. +``` +type spec = +``` +``` +| Unit of unit -> unit +``` +Call the function with unit argument +``` +| Bool of bool -> unit +``` +Call the function with a bool argument +``` +| Set of bool ref +``` +Set the reference to true +``` +| Clear of bool ref +``` +Set the reference to false +``` +| String of string -> unit +``` +Call the function with a string argument +``` +| Set_string of string ref +``` +Set the reference to the string argument +``` +| Int of int -> unit +``` +Call the function with an int argument +``` +| Set_int of int ref +``` +Set the reference to the int argument +``` +| Float of float -> unit +``` +Call the function with a float argument +``` +| Set_float of float ref +``` +Set the reference to the float argument +``` +| Tuple of spec list +``` +Take several arguments according to the spec list +``` +| Symbol of string list * string -> unit +``` +Take one of the symbols as argument and call the function with the symbol +``` +| Rest of string -> unit +``` +Stop interpreting keywords and call the function with each remaining argument +``` +| Rest_all of string list -> unit +``` +Stop interpreting keywords and call the function with all remaining arguments +``` +| Expand of string -> string array +``` +If the remaining arguments to process are of the form `["-foo"; "arg"] @ rest` where "foo" is registered as `Expand f`, then the arguments `f "arg" @ rest` are processed. Only allowed in `parse_and_expand_argv_dynamic`. +``` + +``` +The concrete type describing the behavior associated with a keyword. +``` +type key = string +``` +``` +type doc = string +``` +``` +type usage_msg = string +``` +``` +type anon_fun = string -> unit +``` +``` +val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit +``` +`Arg.parse speclist anon_fun usage_msg` parses the command line. `speclist` is a list of triples `(key, spec, doc)`. `key` is the option keyword, it must start with a `'-'` character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon_fun` is called on anonymous arguments. The functions in `spec` and `anon_fun` are called in the same order as their arguments appear on the command line. +If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows: +- The reason for the error: unknown option, invalid or missing argument, etc. +- `usage_msg` +- The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list. +For the user to be able to specify anonymous arguments starting with a `-`, include for example `("-", String anon_fun, doc)` in `speclist`. +By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage_msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`. +``` +val parse_dynamic : + (key * spec * doc) list ref -> + anon_fun -> + usage_msg -> + unit +``` +Same as [`Arg.parse`](./#val-parse), except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form: +- command subcommand `options` where the list of options depends on the value of the subcommand argument. +since 4.01 +``` +val parse_argv : + ?current:int ref -> + string array -> + (key * spec * doc) list -> + anon_fun -> + usage_msg -> + unit +``` +`Arg.parse_argv ~current args speclist anon_fun usage_msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or [`Arg.current`](./#val-current). You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises [`Arg.Bad`](./#exception-Bad) with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises [`Arg.Help`](./#exception-Help) with the help message as argument. +``` +val parse_argv_dynamic : + ?current:int ref -> + string array -> + (key * spec * doc) list ref -> + anon_fun -> + string -> + unit +``` +Same as [`Arg.parse_argv`](./#val-parse_argv), except that the `speclist` argument is a reference and may be updated during the parsing. See [`Arg.parse_dynamic`](./#val-parse_dynamic). +since 4.01 +``` +val parse_and_expand_argv_dynamic : + int ref -> + string array ref -> + (key * spec * doc) list ref -> + anon_fun -> + string -> + unit +``` +Same as [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic), except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic). +since 4.05 +``` +val parse_expand : (key * spec * doc) list -> anon_fun -> usage_msg -> unit +``` +Same as [`Arg.parse`](./#val-parse), except that the `Expand` arguments are allowed and the [`current`](./#val-current) reference is not updated. +since 4.05 +``` +exception Help of string +``` +Raised by `Arg.parse_argv` when the user asks for help. +``` +exception Bad of string +``` +Functions in `spec` or `anon_fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by [`Arg.parse_argv`](./#val-parse_argv) in case of an error. +``` +val usage : (key * spec * doc) list -> usage_msg -> unit +``` +`Arg.usage speclist usage_msg` prints to standard error an error message that includes the list of valid options. This is the same message that [`Arg.parse`](./#val-parse) prints in case of error. `speclist` and `usage_msg` are the same as for [`Arg.parse`](./#val-parse). +``` +val usage_string : (key * spec * doc) list -> usage_msg -> string +``` +Returns the message that would have been printed by [`Arg.usage`](./#val-usage), if provided with the same parameters. +``` +val align : ?limit:int -> (key * spec * doc) list -> (key * spec * doc) list +``` +Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line. +parameter limit options with keyword and message longer than limit will not be used to compute the alignment. +``` +val current : int ref +``` +Position (in [`Sys.argv`](./Stdlib-Sys.md#val-argv)) of the argument being processed. You can change this value, e.g. to force [`Arg.parse`](./#val-parse) to skip some arguments. [`Arg.parse`](./#val-parse) uses the initial value of [`Arg.current`](./#val-current) as the index of argument 0 (the program name) and starts parsing arguments at the next element. +``` +val read_arg : string -> string array +``` +`Arg.read_arg file` reads newline-terminated command line arguments from file `file`. +since 4.05 +``` +val read_arg0 : string -> string array +``` +Identical to [`Arg.read_arg`](./#val-read_arg) but assumes null character terminated command line arguments. +since 4.05 +``` +val write_arg : string -> string array -> unit +``` +`Arg.write_arg file args` writes the arguments `args` newline-terminated into the file `file`. If any of the arguments in `args` contains a newline, use [`Arg.write_arg0`](./#val-write_arg0) instead. +since 4.05 +``` +val write_arg0 : string -> string array -> unit +``` +Identical to [`Arg.write_arg`](./#val-write_arg) but uses the null character for terminator instead of newline. +since 4.05 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Array.md b/docs/api/melange/Stdlib-Array.md new file mode 100644 index 000000000..592e665a1 --- /dev/null +++ b/docs/api/melange/Stdlib-Array.md @@ -0,0 +1,284 @@ +# Module `Stdlib.Array` +Array operations. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +``` +type 'a t = 'a array +``` +An alias for the type of arrays. +``` +val length : 'a array -> int +``` +Return the length (number of elements) of the given array. +``` +val get : 'a array -> int -> 'a +``` +`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val set : 'a array -> int -> 'a -> unit +``` +`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. +``` +val make : int -> 'a -> 'a array +``` +`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val create_float : int -> float array +``` +`create_float n` returns a fresh float array of length `n`, with uninitialized data. +since 4.03 +``` +val init : int -> (int -> 'a) -> 'a array +``` +`init n f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +``` +val make_matrix : int -> int -> 'a -> 'a array array +``` +`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val init_matrix : int -> int -> (int -> int -> 'a) -> 'a array array +``` +`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +since 5.2 +``` +val append : 'a array -> 'a array -> 'a array +``` +`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. +``` +val concat : 'a array list -> 'a array +``` +Same as [`append`](./#val-append), but concatenates a list of arrays. +``` +val sub : 'a array -> int -> int -> 'a array +``` +`sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. +``` +val copy : 'a array -> 'a array +``` +`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. +``` +val fill : 'a array -> int -> int -> 'a -> unit +``` +`fill a pos len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. +``` +val blit : 'a array -> int -> 'a array -> int -> int -> unit +``` +`blit src src_pos dst dst_pos len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. +``` +val to_list : 'a array -> 'a list +``` +`to_list a` returns the list of all the elements of `a`. +``` +val of_list : 'a list -> 'a array +``` +`of_list l` returns a fresh array containing the elements of `l`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. +## Iterators +``` +val iter : ('a -> unit) -> 'a array -> unit +``` +`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. +``` +val iteri : (int -> 'a -> unit) -> 'a array -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. +``` +val map : ('a -> 'b) -> 'a array -> 'b array +``` +`map f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. +``` +val map_inplace : ('a -> 'a) -> 'a array -> unit +``` +`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. +since 5.1 +``` +val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. +``` +val mapi_inplace : (int -> 'a -> 'a) -> 'a array -> unit +``` +Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. +since 5.1 +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a array -> 'acc +``` +`fold_left f init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. +``` +val fold_left_map : + ('acc -> 'a -> 'acc * 'b) -> + 'acc -> + 'a array -> + 'acc * 'b array +``` +`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. +since 4.13 +``` +val fold_right : ('a -> 'acc -> 'acc) -> 'a array -> 'acc -> 'acc +``` +`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. +## Iterators on two arrays +``` +val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit +``` +`iter2 f a b` applies function `f` to all the elements of `a` and `b`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) +``` +val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array +``` +`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) +## Array scanning +``` +val for_all : ('a -> bool) -> 'a array -> bool +``` +`for_all f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. +since 4.03 +``` +val exists : ('a -> bool) -> 'a array -> bool +``` +`exists f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. +since 4.03 +``` +val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val mem : 'a -> 'a array -> bool +``` +`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). +since 4.03 +``` +val memq : 'a -> 'a array -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. +since 4.03 +``` +val find_opt : ('a -> bool) -> 'a array -> 'a option +``` +`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. +since 4.13 +``` +val find_index : ('a -> bool) -> 'a array -> int option +``` +`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. +It returns `None` if there is no such element. +since 5.1 +``` +val find_map : ('a -> 'b option) -> 'a array -> 'b option +``` +`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. +since 4.13 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a array -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 5.1 +## Arrays of pairs +``` +val split : ('a * 'b) array -> 'a array * 'b array +``` +`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. +since 4.13 +``` +val combine : 'a array -> 'b array -> ('a * 'b) array +``` +`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. +since 4.13 +## Sorting and shuffling +``` +val sort : ('a -> 'a -> int) -> 'a array -> unit +``` +Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. +The current implementation uses Heap Sort. It runs in constant stack space. +Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : +- `cmp x y` \> 0 if and only if `cmp y x` \< 0 +- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 +When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : +- `cmp a.(i) a.(j)` \>= 0 if i \>= j +``` +val stable_sort : ('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. +The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). +``` +val fast_sort : ('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. +``` +val shuffle : rand:(int -> int) -> 'a array -> unit +``` +`shuffle rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. +`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). +since 5.2 +## Arrays and Sequences +``` +val to_seq : 'a array -> 'a Seq.t +``` +Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. +since 4.07 +``` +val to_seqi : 'a array -> (int * 'a) Seq.t +``` +Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a array +``` +Create an array from the generator +since 4.07 +## Arrays and concurrency safety +Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. +### Atomicity +Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. +For example, consider the following program: +```ocaml +let size = 100_000_000 +let a = Array.make size 1 +let d1 = Domain.spawn (fun () -> + Array.iteri (fun i x -> a.(i) <- x + 1) a +) +let d2 = Domain.spawn (fun () -> + Array.iteri (fun i x -> a.(i) <- 2 * x + 1) a +) +let () = Domain.join d1; Domain.join d2 +``` +After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +### Data races +If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. +A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). +### Float arrays +Float arrays have two supplementary caveats in the presence of data races. +First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. +For instance, at the end of +```ocaml + let zeros = Array.make size 0. +let max_floats = Array.make size Float.max_float +let res = Array.copy zeros +let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) +let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) +let () = Domain.join d1; Domain.join d2 +``` +the `res` array might contain values that are neither `0.` nor `max_float`. +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-ArrayLabels.md b/docs/api/melange/Stdlib-ArrayLabels.md new file mode 100644 index 000000000..686488d76 --- /dev/null +++ b/docs/api/melange/Stdlib-ArrayLabels.md @@ -0,0 +1,294 @@ +# Module `Stdlib.ArrayLabels` +Array operations. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +``` +type 'a t = 'a array +``` +An alias for the type of arrays. +``` +val length : 'a array -> int +``` +Return the length (number of elements) of the given array. +``` +val get : 'a array -> int -> 'a +``` +`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val set : 'a array -> int -> 'a -> unit +``` +`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. +``` +val make : int -> 'a -> 'a array +``` +`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val create_float : int -> float array +``` +`create_float n` returns a fresh float array of length `n`, with uninitialized data. +since 4.03 +``` +val init : int -> f:(int -> 'a) -> 'a array +``` +`init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +``` +val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array +``` +`make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val init_matrix : + dimx:int -> + dimy:int -> + f:(int -> int -> 'a) -> + 'a array array +``` +`init_matrix ~dimx ~dimy ~f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +since 5.2 +``` +val append : 'a array -> 'a array -> 'a array +``` +`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. +``` +val concat : 'a array list -> 'a array +``` +Same as [`append`](./#val-append), but concatenates a list of arrays. +``` +val sub : 'a array -> pos:int -> len:int -> 'a array +``` +`sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. +``` +val copy : 'a array -> 'a array +``` +`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. +``` +val fill : 'a array -> pos:int -> len:int -> 'a -> unit +``` +`fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. +``` +val blit : + src:'a array -> + src_pos:int -> + dst:'a array -> + dst_pos:int -> + len:int -> + unit +``` +`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. +``` +val to_list : 'a array -> 'a list +``` +`to_list a` returns the list of all the elements of `a`. +``` +val of_list : 'a list -> 'a array +``` +`of_list l` returns a fresh array containing the elements of `l`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. +## Iterators +``` +val iter : f:('a -> unit) -> 'a array -> unit +``` +`iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. +``` +val iteri : f:(int -> 'a -> unit) -> 'a array -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. +``` +val map : f:('a -> 'b) -> 'a array -> 'b array +``` +`map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. +``` +val map_inplace : f:('a -> 'a) -> 'a array -> unit +``` +`map_inplace ~f a` applies function `f` to all elements of `a`, and updates their values in place. +since 5.1 +``` +val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. +``` +val mapi_inplace : f:(int -> 'a -> 'a) -> 'a array -> unit +``` +Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. +since 5.1 +``` +val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'acc +``` +`fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. +``` +val fold_left_map : + f:('acc -> 'a -> 'acc * 'b) -> + init:'acc -> + 'a array -> + 'acc * 'b array +``` +`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. +since 4.13 +``` +val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> init:'acc -> 'acc +``` +`fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. +## Iterators on two arrays +``` +val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit +``` +`iter2 ~f a b` applies function `f` to all the elements of `a` and `b`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) +``` +val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array +``` +`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) +## Array scanning +``` +val for_all : f:('a -> bool) -> 'a array -> bool +``` +`for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. +since 4.03 +``` +val exists : f:('a -> bool) -> 'a array -> bool +``` +`exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. +since 4.03 +``` +val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val mem : 'a -> set:'a array -> bool +``` +`mem a ~set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). +since 4.03 +``` +val memq : 'a -> set:'a array -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. +since 4.03 +``` +val find_opt : f:('a -> bool) -> 'a array -> 'a option +``` +`find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. +since 4.13 +``` +val find_index : f:('a -> bool) -> 'a array -> int option +``` +`find_index ~f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. +It returns `None` if there is no such element. +since 5.1 +``` +val find_map : f:('a -> 'b option) -> 'a array -> 'b option +``` +`find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. +since 4.13 +``` +val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 5.1 +## Arrays of pairs +``` +val split : ('a * 'b) array -> 'a array * 'b array +``` +`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. +since 4.13 +``` +val combine : 'a array -> 'b array -> ('a * 'b) array +``` +`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. +since 4.13 +## Sorting and shuffling +``` +val sort : cmp:('a -> 'a -> int) -> 'a array -> unit +``` +Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. +The current implementation uses Heap Sort. It runs in constant stack space. +Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : +- `cmp x y` \> 0 if and only if `cmp y x` \< 0 +- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 +When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : +- `cmp a.(i) a.(j)` \>= 0 if i \>= j +``` +val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. +The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). +``` +val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. +``` +val shuffle : rand:(int -> int) -> 'a array -> unit +``` +`shuffle ~rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. +`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). +since 5.2 +## Arrays and Sequences +``` +val to_seq : 'a array -> 'a Seq.t +``` +Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. +since 4.07 +``` +val to_seqi : 'a array -> (int * 'a) Seq.t +``` +Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a array +``` +Create an array from the generator +since 4.07 +## Arrays and concurrency safety +Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. +### Atomicity +Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. +For example, consider the following program: +```ocaml +let size = 100_000_000 +let a = ArrayLabels.make size 1 +let d1 = Domain.spawn (fun () -> + ArrayLabels.iteri ~f:(fun i x -> a.(i) <- x + 1) a +) +let d2 = Domain.spawn (fun () -> + ArrayLabels.iteri ~f:(fun i x -> a.(i) <- 2 * x + 1) a +) +let () = Domain.join d1; Domain.join d2 +``` +After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +### Data races +If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. +A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). +### Float arrays +Float arrays have two supplementary caveats in the presence of data races. +First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. +For instance, at the end of +```ocaml + let zeros = Array.make size 0. +let max_floats = Array.make size Float.max_float +let res = Array.copy zeros +let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) +let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) +let () = Domain.join d1; Domain.join d2 +``` +the `res` array might contain values that are neither `0.` nor `max_float`. +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Atomic.md b/docs/api/melange/Stdlib-Atomic.md new file mode 100644 index 000000000..22b9265cd --- /dev/null +++ b/docs/api/melange/Stdlib-Atomic.md @@ -0,0 +1,118 @@ +# Module `Stdlib.Atomic` +Atomic references. +See [the examples](./#examples) below. See 'Memory model: The hard bits' chapter in the manual. +since 4.12 +``` +type !'a t +``` +An atomic (mutable) reference to a value of type `'a`. +``` +val make : 'a -> 'a t +``` +Create an atomic reference. +Create an atomic reference that is alone on a cache line. It occupies 4-16x the memory of one allocated with `make v`. +The primary purpose is to prevent false-sharing and the resulting performance degradation. When a CPU performs an atomic operation, it temporarily takes ownership of an entire cache line that contains the atomic reference. If multiple atomic references share the same cache line, modifying these disjoint memory regions simultaneously becomes impossible, which can create a bottleneck. Hence, as a general guideline, if an atomic reference is experiencing contention, assigning it its own cache line may enhance performance. +``` +val get : 'a t -> 'a +``` +Get the current value of the atomic reference. +``` +val set : 'a t -> 'a -> unit +``` +Set a new value for the atomic reference. +``` +val exchange : 'a t -> 'a -> 'a +``` +Set a new value for the atomic reference, and return the current value. +``` +val compare_and_set : 'a t -> 'a -> 'a -> bool +``` +`compare_and_set r seen v` sets the new value of `r` to `v` only if its current value is physically equal to `seen` \-- the comparison and the set occur atomically. Returns `true` if the comparison succeeded (so the set happened) and `false` otherwise. +``` +val fetch_and_add : int t -> int -> int +``` +`fetch_and_add r n` atomically increments the value of `r` by `n`, and returns the current value (before the increment). +``` +val incr : int t -> unit +``` +`incr r` atomically increments the value of `r` by `1`. +``` +val decr : int t -> unit +``` +`decr r` atomically decrements the value of `r` by `1`. +## Examples +### Basic Thread Coordination +A basic use case is to have global counters that are updated in a thread-safe way, for example to keep some sorts of metrics over IOs performed by the program. Another basic use case is to coordinate the termination of threads in a given program, for example when one thread finds an answer, or when the program is shut down by the user. +Here, for example, we're going to try to find a number whose hash satisfies a basic property. To do that, we'll run multiple threads which will try random numbers until they find one that works. +Of course the output below is a sample run and will change every time the program is run. +```ocaml +(* use for termination *) +let stop_all_threads = Atomic.make false + +(* total number of individual attempts to find a number *) +let num_attempts = Atomic.make 0 + +(* find a number that satisfies [p], by... trying random numbers + until one fits. *) +let find_number_where (p:int -> bool) = + let rand = Random.State.make_self_init() in + while not (Atomic.get stop_all_threads) do + + let n = Random.State.full_int rand max_int in + ignore (Atomic.fetch_and_add num_attempts 1 : int); + + if p (Hashtbl.hash n) then ( + Printf.printf "found %d (hash=%d)\n%!" n (Hashtbl.hash n); + Atomic.set stop_all_threads true; (* signal all threads to stop *) + ) + done;; + + +(* run multiple domains to search for a [n] where [hash n <= 100] *) +let () = + let criterion n = n <= 100 in + let threads = + Array.init 8 + (fun _ -> Domain.spawn (fun () -> find_number_where criterion)) + in + Array.iter Domain.join threads; + Printf.printf "total number of attempts: %d\n%!" + (Atomic.get num_attempts) ;; + +- : unit = () +found 1651745641680046833 (hash=33) +total number of attempts: 30230350 +``` +### Treiber Stack +Another example is a basic [Treiber stack](https://en.wikipedia.org/wiki/Treiber_stack) (a thread-safe stack) that can be safely shared between threads. +Note how both `push` and `pop` are recursive, because they attempt to swap the new stack (with one more, or one fewer, element) with the old stack. This is optimistic concurrency: each iteration of, say, `push stack x` gets the old stack `l`, and hopes that by the time it tries to replace `l` with `x::l`, nobody else has had time to modify the list. If the `compare_and_set` fails it means we were too optimistic, and must try again. +```ocaml +type 'a stack = 'a list Atomic.t + +let rec push (stack: _ stack) elt : unit = + let cur = Atomic.get stack in + let success = Atomic.compare_and_set stack cur (elt :: cur) in + if not success then + push stack elt + +let rec pop (stack: _ stack) : _ option = + let cur = Atomic.get stack in + match cur with + | [] -> None + | x :: tail -> + let success = Atomic.compare_and_set stack cur tail in + if success then Some x + else pop stack + +# let st = Atomic.make [] +# push st 1 +- : unit = () +# push st 2 +- : unit = () +# pop st +- : int option = Some 2 +# pop st +- : int option = Some 1 +# pop st +- : int option = None +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Bool.md b/docs/api/melange/Stdlib-Bool.md new file mode 100644 index 000000000..91ffeda60 --- /dev/null +++ b/docs/api/melange/Stdlib-Bool.md @@ -0,0 +1,62 @@ +# Module `Stdlib.Bool` +Boolean values. +since 4.08 +## Booleans +``` +type t = bool = +``` +``` +| false +``` +``` +| true +``` +``` + +``` +The type of booleans (truth values). +The constructors `false` and `true` are included here so that they have paths, but they are not intended to be used in user-defined data types. +``` +val not : bool -> bool +``` +`not b` is the boolean negation of `b`. +``` +val (&&) : bool -> bool -> bool +``` +`e0 && e1` is the lazy boolean conjunction of expressions `e0` and `e1`. If `e0` evaluates to `false`, `e1` is not evaluated. Right-associative operator at precedence level 3/11. +``` +val (||) : bool -> bool -> bool +``` +`e0 || e1` is the lazy boolean disjunction of expressions `e0` and `e1`. If `e0` evaluates to `true`, `e1` is not evaluated. Right-associative operator at precedence level 2/11. +## Predicates and comparisons +``` +val equal : bool -> bool -> bool +``` +`equal b0 b1` is `true` if and only if `b0` and `b1` are both `true` or both `false`. +``` +val compare : bool -> bool -> int +``` +`compare b0 b1` is a total order on boolean values. `false` is smaller than `true`. +## Converting +``` +val to_int : bool -> int +``` +`to_int b` is `0` if `b` is `false` and `1` if `b` is `true`. +``` +val to_float : bool -> float +``` +`to_float b` is `0.` if `b` is `false` and `1.` if `b` is `true`. +``` +val to_string : bool -> string +``` +`to_string b` is `"true"` if `b` is `true` and `"false"` if `b` is `false`. +``` +val seeded_hash : int -> bool -> int +``` +A seeded hash function for booleans, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.1 +``` +val hash : bool -> int +``` +An unseeded hash function for booleans, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Buffer.md b/docs/api/melange/Stdlib-Buffer.md new file mode 100644 index 000000000..a4a8fe016 --- /dev/null +++ b/docs/api/melange/Stdlib-Buffer.md @@ -0,0 +1,222 @@ +# Module `Stdlib.Buffer` +Extensible buffers. +This module implements buffers that automatically expand as necessary. It provides accumulative concatenation of strings in linear time (instead of quadratic time when strings are concatenated pairwise). For example: +```ocaml + let concat_strings ss = + let b = Buffer.create 16 in + List.iter (Buffer.add_string b) ss; + Buffer.contents b + +``` +**Unsynchronized accesses** +Unsynchronized accesses to a buffer may lead to an invalid buffer state. Thus, concurrent accesses to a buffer must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +``` +type t +``` +The abstract type of buffers. +``` +val create : int -> t +``` +`create n` returns a fresh buffer, initially empty. The `n` parameter is the initial size of the internal byte sequence that holds the buffer contents. That byte sequence is automatically reallocated when more than `n` characters are stored in the buffer, but shrinks back to `n` characters when `reset` is called. For best performance, `n` should be of the same order of magnitude as the number of characters that are expected to be stored in the buffer (for instance, 80 for a buffer that holds one output line). Nothing bad will happen if the buffer grows beyond that limit, however. In doubt, take `n = 16` for instance. If `n` is not between 1 and [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length), it will be clipped to that interval. +``` +val contents : t -> string +``` +Return a copy of the current contents of the buffer. The buffer itself is unchanged. +``` +val to_bytes : t -> bytes +``` +Return a copy of the current contents of the buffer. The buffer itself is unchanged. +since 4.02 +``` +val sub : t -> int -> int -> string +``` +`Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off and len do not designate a valid range of b. +``` +val blit : t -> int -> bytes -> int -> int -> unit +``` +`Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if srcoff and len do not designate a valid range of src, or if dstoff and len do not designate a valid range of dst. +since 3.11.2 +``` +val nth : t -> int -> char +``` +Get the n-th character of the buffer. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if index out of bounds +``` +val length : t -> int +``` +Return the number of characters currently contained in the buffer. +``` +val clear : t -> unit +``` +Empty the buffer. +``` +val reset : t -> unit +``` +Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by [`Buffer.create`](./#val-create) `n`. For long-lived buffers that may have grown a lot, `reset` allows faster reclamation of the space used by the buffer. +``` +val output_buffer : out_channel -> t -> unit +``` +`output_buffer oc b` writes the current contents of buffer `b` on the output channel `oc`. +``` +val truncate : t -> int -> unit +``` +`truncate b len` truncates the length of `b` to `len` Note: the internal byte sequence is not shortened. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> length b. +since 4.05 +## Appending +Note: all `add_*` operations can raise `Failure` if the internal byte sequence of the buffer would need to grow beyond [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length). +``` +val add_char : t -> char -> unit +``` +`add_char b c` appends the character `c` at the end of buffer `b`. +``` +val add_utf_8_uchar : t -> Uchar.t -> unit +``` +`add_utf_8_uchar b u` appends the [UTF-8](https://tools.ietf.org/html/rfc3629) encoding of `u` at the end of buffer `b`. +since 4.06 +``` +val add_utf_16le_uchar : t -> Uchar.t -> unit +``` +`add_utf_16le_uchar b u` appends the [UTF-16LE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. +since 4.06 +``` +val add_utf_16be_uchar : t -> Uchar.t -> unit +``` +`add_utf_16be_uchar b u` appends the [UTF-16BE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. +since 4.06 +``` +val add_string : t -> string -> unit +``` +`add_string b s` appends the string `s` at the end of buffer `b`. +``` +val add_bytes : t -> bytes -> unit +``` +`add_bytes b s` appends the byte sequence `s` at the end of buffer `b`. +since 4.02 +``` +val add_substring : t -> string -> int -> int -> unit +``` +`add_substring b s ofs len` takes `len` characters from offset `ofs` in string `s` and appends them at the end of buffer `b`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. +``` +val add_subbytes : t -> bytes -> int -> int -> unit +``` +`add_subbytes b s ofs len` takes `len` characters from offset `ofs` in byte sequence `s` and appends them at the end of buffer `b`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. +since 4.02 +``` +val add_substitute : t -> (string -> string) -> string -> unit +``` +`add_substitute b f s` appends the string pattern `s` at the end of buffer `b` with substitution. The substitution process looks for variable references in the pattern and substitutes each variable reference with its value, as obtained by applying the mapping `f` to the variable name. Inside the string pattern, a variable reference is a non-escaped `$` immediately followed by a variable name, which is one of the following: +- a non empty sequence of alphanumeric or `_` characters, +- an arbitrary sequence of characters enclosed by a pair of matching parentheses or curly brackets. An escaped `$` character is a `$` that immediately follows a backslash character; the two characters together stand for a plain `$`. +``` +val add_buffer : t -> t -> unit +``` +`add_buffer b1 b2` appends the current contents of buffer `b2` at the end of buffer `b1`. `b2` is not modified. +``` +val add_channel : t -> in_channel -> int -> unit +``` +`add_channel b ic n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`. +raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if the channel contains fewer than n characters. In this case, the characters are still added to the buffer, so as to avoid loss of data. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> Sys.max\_string\_length. +## Buffers and Sequences +``` +val to_seq : t -> char Seq.t +``` +Iterate on the buffer, in increasing order. +The behavior is not specified if the buffer is modified during iteration. +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +Iterate on the buffer, in increasing order, yielding indices along chars. +The behavior is not specified if the buffer is modified during iteration. +since 4.07 +``` +val add_seq : t -> char Seq.t -> unit +``` +Add chars to the buffer +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +Create a buffer from the generator +since 4.07 +## Binary encoding of integers +The functions in this section append binary encodings of integers to buffers. +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. Functions that encode these values truncate their inputs to their least significant bytes. +``` +val add_uint8 : t -> int -> unit +``` +`add_uint8 b i` appends a binary unsigned 8-bit integer `i` to `b`. +since 4.08 +``` +val add_int8 : t -> int -> unit +``` +`add_int8 b i` appends a binary signed 8-bit integer `i` to `b`. +since 4.08 +``` +val add_uint16_ne : t -> int -> unit +``` +`add_uint16_ne b i` appends a binary native-endian unsigned 16-bit integer `i` to `b`. +since 4.08 +``` +val add_uint16_be : t -> int -> unit +``` +`add_uint16_be b i` appends a binary big-endian unsigned 16-bit integer `i` to `b`. +since 4.08 +``` +val add_uint16_le : t -> int -> unit +``` +`add_uint16_le b i` appends a binary little-endian unsigned 16-bit integer `i` to `b`. +since 4.08 +``` +val add_int16_ne : t -> int -> unit +``` +`add_int16_ne b i` appends a binary native-endian signed 16-bit integer `i` to `b`. +since 4.08 +``` +val add_int16_be : t -> int -> unit +``` +`add_int16_be b i` appends a binary big-endian signed 16-bit integer `i` to `b`. +since 4.08 +``` +val add_int16_le : t -> int -> unit +``` +`add_int16_le b i` appends a binary little-endian signed 16-bit integer `i` to `b`. +since 4.08 +``` +val add_int32_ne : t -> int32 -> unit +``` +`add_int32_ne b i` appends a binary native-endian 32-bit integer `i` to `b`. +since 4.08 +``` +val add_int32_be : t -> int32 -> unit +``` +`add_int32_be b i` appends a binary big-endian 32-bit integer `i` to `b`. +since 4.08 +``` +val add_int32_le : t -> int32 -> unit +``` +`add_int32_le b i` appends a binary little-endian 32-bit integer `i` to `b`. +since 4.08 +``` +val add_int64_ne : t -> int64 -> unit +``` +`add_int64_ne b i` appends a binary native-endian 64-bit integer `i` to `b`. +since 4.08 +``` +val add_int64_be : t -> int64 -> unit +``` +`add_int64_be b i` appends a binary big-endian 64-bit integer `i` to `b`. +since 4.08 +``` +val add_int64_le : t -> int64 -> unit +``` +`add_int64_ne b i` appends a binary little-endian 64-bit integer `i` to `b`. +since 4.08 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Bytes.md b/docs/api/melange/Stdlib-Bytes.md new file mode 100644 index 000000000..2b305f8d7 --- /dev/null +++ b/docs/api/melange/Stdlib-Bytes.md @@ -0,0 +1,527 @@ +# Module `Stdlib.Bytes` +Byte sequence operations. +A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. +Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. +Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. +Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. +Bytes are represented by the OCaml type `char`. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +since 4.02 +``` +val length : bytes -> int +``` +Return the length (number of bytes) of the argument. +``` +val get : bytes -> int -> char +``` +`get s n` returns the byte at index `n` in argument `s`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val set : bytes -> int -> char -> unit +``` +`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val create : int -> bytes +``` +`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val make : int -> char -> bytes +``` +`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> (int -> char) -> bytes +``` +`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val empty : bytes +``` +A byte sequence of size 0. +``` +val copy : bytes -> bytes +``` +Return a new byte sequence that contains the same bytes as the argument. +``` +val of_string : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. +``` +val to_string : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. +``` +val sub : bytes -> int -> int -> bytes +``` +`sub s pos len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val sub_string : bytes -> int -> int -> string +``` +Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. +``` +val extend : bytes -> int -> int -> bytes +``` +`extend s left right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val fill : bytes -> int -> int -> char -> unit +``` +`fill s pos len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val blit : bytes -> int -> bytes -> int -> int -> unit +``` +`blit src src_pos dst dst_pos len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +``` +val blit_string : string -> int -> bytes -> int -> int -> unit +``` +`blit_string src src_pos dst dst_pos len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +since 4.05 in BytesLabels +``` +val concat : bytes -> bytes list -> bytes +``` +`concat sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : bytes -> bytes -> bytes +``` +`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val iter : (char -> unit) -> bytes -> unit +``` +`iter f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. +``` +val iteri : (int -> char -> unit) -> bytes -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. +``` +val map : (char -> char) -> bytes -> bytes +``` +`map f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. +``` +val mapi : (int -> char -> char) -> bytes -> bytes +``` +`mapi f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. +``` +val fold_left : ('acc -> char -> 'acc) -> 'acc -> bytes -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. +since 4.13 +``` +val fold_right : (char -> 'acc -> 'acc) -> bytes -> 'acc -> 'acc +``` +`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. +since 4.13 +``` +val for_all : (char -> bool) -> bytes -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. +since 4.13 +``` +val exists : (char -> bool) -> bytes -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. +since 4.13 +``` +val trim : bytes -> bytes +``` +Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. +``` +val escaped : bytes -> bytes +``` +Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val index : bytes -> char -> int +``` +`index s c` returns the index of the first occurrence of byte `c` in `s`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val index_opt : bytes -> char -> int option +``` +`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. +since 4.05 +``` +val rindex : bytes -> char -> int +``` +`rindex s c` returns the index of the last occurrence of byte `c` in `s`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val rindex_opt : bytes -> char -> int option +``` +`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. +since 4.05 +``` +val index_from : bytes -> int -> char -> int +``` +`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +``` +val index_from_opt : bytes -> int -> char -> int option +``` +`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : bytes -> int -> char -> int +``` +`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +``` +val rindex_from_opt : bytes -> int -> char -> int option +``` +`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val contains : bytes -> char -> bool +``` +`contains s c` tests if byte `c` appears in `s`. +``` +val contains_from : bytes -> int -> char -> bool +``` +`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : bytes -> int -> char -> bool +``` +`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val uppercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +val lowercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +val capitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +val uncapitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +type t = bytes +``` +An alias for the type of byte sequences. +``` +val compare : t -> t -> int +``` +The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). +``` +val equal : t -> t -> bool +``` +The equality function for byte sequences. +since 4.03 (4.05 in BytesLabels) +``` +val starts_with : prefix:bytes -> bytes -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. +since 4.13 +``` +val ends_with : suffix:bytes -> bytes -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. +since 4.13 +## Unsafe conversions (for advanced users) +This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. +``` +val unsafe_to_string : bytes -> string +``` +Unsafely convert a byte sequence into a string. +To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: +- Unique ownership: the data may be accessed and mutated +- Shared ownership: the data has several owners, that may only access it, not mutate it. +Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. +`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. +There are two valid use-cases that respect this ownership discipline: +1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. +```ocaml +let string_init len f : string = + let s = Bytes.create len in + for i = 0 to len - 1 do Bytes.set s i (f i) done; + Bytes.unsafe_to_string s +``` +This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. +Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. +We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. +2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. +```ocaml +let bytes_length (s : bytes) = + String.length (Bytes.unsafe_to_string s) +``` +In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. +The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. +``` +val unsafe_of_string : string -> bytes +``` +Unsafely convert a shared string to a byte sequence that should not be mutated. +The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. +In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. +For example, string literals are implicitly shared by the compiler, so you never uniquely own them. +```ocaml +let incorrect = Bytes.unsafe_of_string "hello" +let s = Bytes.of_string "hello" +``` +The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. +Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. +The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. +``` +val split_on_char : char -> bytes -> bytes list +``` +`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. +The function's output is specified by the following invariants: +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). +- No byte sequence in the result contains the `sep` character. +since 4.13 +## Iterators +``` +val to_seq : t -> char Seq.t +``` +Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +Iterate on the string, in increasing order, yielding indices along chars +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +Create a string from the generator +since 4.07 +## UTF codecs and validations +since 4.14 +### UTF-8 +``` +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`. +``` +val set_utf_8_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. +### UTF-16BE +``` +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`. +``` +val set_utf_16be_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. +### UTF-16LE +``` +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`. +``` +val set_utf_16le_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. +## Binary encoding/decoding of integers +The functions in this section binary encode and decode integers to and from byte sequences. +All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: +- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. +- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. +``` +val get_uint8 : bytes -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int8 : bytes -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. +since 4.08 +``` +val get_uint16_ne : bytes -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_uint16_be : bytes -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_uint16_le : bytes -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int16_ne : bytes -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int16_be : bytes -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int16_le : bytes -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int32_ne : bytes -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int32_be : bytes -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int32_le : bytes -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int64_ne : bytes -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int64_be : bytes -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int64_le : bytes -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. +since 4.08 +``` +val set_uint8 : bytes -> int -> int -> unit +``` +`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int8 : bytes -> int -> int -> unit +``` +`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_uint16_ne : bytes -> int -> int -> unit +``` +`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_uint16_be : bytes -> int -> int -> unit +``` +`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_uint16_le : bytes -> int -> int -> unit +``` +`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int16_ne : bytes -> int -> int -> unit +``` +`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int16_be : bytes -> int -> int -> unit +``` +`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int16_le : bytes -> int -> int -> unit +``` +`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int32_ne : bytes -> int -> int32 -> unit +``` +`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int32_be : bytes -> int -> int32 -> unit +``` +`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int32_le : bytes -> int -> int32 -> unit +``` +`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int64_ne : bytes -> int -> int64 -> unit +``` +`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int64_be : bytes -> int -> int64 -> unit +``` +`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int64_le : bytes -> int -> int64 -> unit +``` +`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. +since 4.08 +## Byte sequences and concurrency safety +Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. +### Atomicity +Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. +For example, consider the following program: +```ocaml +let size = 100_000_000 +let b = Bytes.make size ' ' +let update b f () = + Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b +let d1 = Domain.spawn (update b (fun x -> x + 1)) +let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) +let () = Domain.join d1; Domain.join d2 +``` +the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. +After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +### Data races +If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. +A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. +### Mixed-size accesses +Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index +```ocaml +let b = Bytes.make 10 '\000' +let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) +``` +In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-BytesLabels.md b/docs/api/melange/Stdlib-BytesLabels.md new file mode 100644 index 000000000..c7a53517d --- /dev/null +++ b/docs/api/melange/Stdlib-BytesLabels.md @@ -0,0 +1,539 @@ +# Module `Stdlib.BytesLabels` +Byte sequence operations. +A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. +Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. +Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. +Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. +Bytes are represented by the OCaml type `char`. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +since 4.02 +``` +val length : bytes -> int +``` +Return the length (number of bytes) of the argument. +``` +val get : bytes -> int -> char +``` +`get s n` returns the byte at index `n` in argument `s`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val set : bytes -> int -> char -> unit +``` +`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val create : int -> bytes +``` +`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val make : int -> char -> bytes +``` +`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> f:(int -> char) -> bytes +``` +`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val empty : bytes +``` +A byte sequence of size 0. +``` +val copy : bytes -> bytes +``` +Return a new byte sequence that contains the same bytes as the argument. +``` +val of_string : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. +``` +val to_string : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. +``` +val sub : bytes -> pos:int -> len:int -> bytes +``` +`sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val sub_string : bytes -> pos:int -> len:int -> string +``` +Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. +``` +val extend : bytes -> left:int -> right:int -> bytes +``` +`extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val fill : bytes -> pos:int -> len:int -> char -> unit +``` +`fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val blit : + src:bytes -> + src_pos:int -> + dst:bytes -> + dst_pos:int -> + len:int -> + unit +``` +`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +``` +val blit_string : + src:string -> + src_pos:int -> + dst:bytes -> + dst_pos:int -> + len:int -> + unit +``` +`blit_string ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +since 4.05 in BytesLabels +``` +val concat : sep:bytes -> bytes list -> bytes +``` +`concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : bytes -> bytes -> bytes +``` +`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val iter : f:(char -> unit) -> bytes -> unit +``` +`iter ~f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. +``` +val iteri : f:(int -> char -> unit) -> bytes -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. +``` +val map : f:(char -> char) -> bytes -> bytes +``` +`map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. +``` +val mapi : f:(int -> char -> char) -> bytes -> bytes +``` +`mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. +``` +val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> bytes -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. +since 4.13 +``` +val fold_right : f:(char -> 'acc -> 'acc) -> bytes -> init:'acc -> 'acc +``` +`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. +since 4.13 +``` +val for_all : f:(char -> bool) -> bytes -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. +since 4.13 +``` +val exists : f:(char -> bool) -> bytes -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. +since 4.13 +``` +val trim : bytes -> bytes +``` +Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. +``` +val escaped : bytes -> bytes +``` +Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val index : bytes -> char -> int +``` +`index s c` returns the index of the first occurrence of byte `c` in `s`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val index_opt : bytes -> char -> int option +``` +`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. +since 4.05 +``` +val rindex : bytes -> char -> int +``` +`rindex s c` returns the index of the last occurrence of byte `c` in `s`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val rindex_opt : bytes -> char -> int option +``` +`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. +since 4.05 +``` +val index_from : bytes -> int -> char -> int +``` +`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +``` +val index_from_opt : bytes -> int -> char -> int option +``` +`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : bytes -> int -> char -> int +``` +`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +``` +val rindex_from_opt : bytes -> int -> char -> int option +``` +`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val contains : bytes -> char -> bool +``` +`contains s c` tests if byte `c` appears in `s`. +``` +val contains_from : bytes -> int -> char -> bool +``` +`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : bytes -> int -> char -> bool +``` +`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val uppercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +val lowercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +val capitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +val uncapitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in BytesLabels) +``` +type t = bytes +``` +An alias for the type of byte sequences. +``` +val compare : t -> t -> int +``` +The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). +``` +val equal : t -> t -> bool +``` +The equality function for byte sequences. +since 4.03 (4.05 in BytesLabels) +``` +val starts_with : prefix:bytes -> bytes -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. +since 4.13 +``` +val ends_with : suffix:bytes -> bytes -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. +since 4.13 +## Unsafe conversions (for advanced users) +This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. +``` +val unsafe_to_string : bytes -> string +``` +Unsafely convert a byte sequence into a string. +To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: +- Unique ownership: the data may be accessed and mutated +- Shared ownership: the data has several owners, that may only access it, not mutate it. +Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. +`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. +There are two valid use-cases that respect this ownership discipline: +1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. +```ocaml +let string_init len f : string = + let s = Bytes.create len in + for i = 0 to len - 1 do Bytes.set s i (f i) done; + Bytes.unsafe_to_string s +``` +This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. +Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. +We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. +2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. +```ocaml +let bytes_length (s : bytes) = + String.length (Bytes.unsafe_to_string s) +``` +In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. +The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. +``` +val unsafe_of_string : string -> bytes +``` +Unsafely convert a shared string to a byte sequence that should not be mutated. +The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. +In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. +For example, string literals are implicitly shared by the compiler, so you never uniquely own them. +```ocaml +let incorrect = Bytes.unsafe_of_string "hello" +let s = Bytes.of_string "hello" +``` +The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. +Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. +The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. +``` +val split_on_char : sep:char -> bytes -> bytes list +``` +`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. +The function's output is specified by the following invariants: +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). +- No byte sequence in the result contains the `sep` character. +since 4.13 +## Iterators +``` +val to_seq : t -> char Seq.t +``` +Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +Iterate on the string, in increasing order, yielding indices along chars +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +Create a string from the generator +since 4.07 +## UTF codecs and validations +since 4.14 +### UTF-8 +``` +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`. +``` +val set_utf_8_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. +### UTF-16BE +``` +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`. +``` +val set_utf_16be_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. +### UTF-16LE +``` +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`. +``` +val set_utf_16le_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. +## Binary encoding/decoding of integers +The functions in this section binary encode and decode integers to and from byte sequences. +All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: +- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. +- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. +``` +val get_uint8 : bytes -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int8 : bytes -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. +since 4.08 +``` +val get_uint16_ne : bytes -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_uint16_be : bytes -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_uint16_le : bytes -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int16_ne : bytes -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int16_be : bytes -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int16_le : bytes -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int32_ne : bytes -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int32_be : bytes -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int32_le : bytes -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int64_ne : bytes -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int64_be : bytes -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. +since 4.08 +``` +val get_int64_le : bytes -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. +since 4.08 +``` +val set_uint8 : bytes -> int -> int -> unit +``` +`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int8 : bytes -> int -> int -> unit +``` +`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_uint16_ne : bytes -> int -> int -> unit +``` +`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_uint16_be : bytes -> int -> int -> unit +``` +`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_uint16_le : bytes -> int -> int -> unit +``` +`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int16_ne : bytes -> int -> int -> unit +``` +`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int16_be : bytes -> int -> int -> unit +``` +`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int16_le : bytes -> int -> int -> unit +``` +`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int32_ne : bytes -> int -> int32 -> unit +``` +`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int32_be : bytes -> int -> int32 -> unit +``` +`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int32_le : bytes -> int -> int32 -> unit +``` +`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int64_ne : bytes -> int -> int64 -> unit +``` +`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int64_be : bytes -> int -> int64 -> unit +``` +`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. +since 4.08 +``` +val set_int64_le : bytes -> int -> int64 -> unit +``` +`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. +since 4.08 +## Byte sequences and concurrency safety +Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. +### Atomicity +Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. +For example, consider the following program: +```ocaml +let size = 100_000_000 +let b = Bytes.make size ' ' +let update b f () = + Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b +let d1 = Domain.spawn (update b (fun x -> x + 1)) +let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) +let () = Domain.join d1; Domain.join d2 +``` +the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. +After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +### Data races +If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. +A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. +### Mixed-size accesses +Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index +```ocaml +let b = Bytes.make 10 '\000' +let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) +``` +In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Char.md b/docs/api/melange/Stdlib-Char.md new file mode 100644 index 000000000..41595f5da --- /dev/null +++ b/docs/api/melange/Stdlib-Char.md @@ -0,0 +1,48 @@ +# Module `Stdlib.Char` +Character operations. +``` +val code : char -> int +``` +Return the ASCII code of the argument. +``` +val chr : int -> char +``` +Return the character with the given ASCII code. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is outside the range 0--255. +``` +val escaped : char -> string +``` +Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote. +``` +val lowercase_ascii : char -> char +``` +Convert the given character to its equivalent lowercase character, using the US-ASCII character set. +since 4.03 +``` +val uppercase_ascii : char -> char +``` +Convert the given character to its equivalent uppercase character, using the US-ASCII character set. +since 4.03 +``` +type t = char +``` +An alias for the type of characters. +``` +val compare : t -> t -> int +``` +The comparison function for characters, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Char` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). +``` +val equal : t -> t -> bool +``` +The equal function for chars. +since 4.03 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for characters, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for characters, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Complex.md b/docs/api/melange/Stdlib-Complex.md new file mode 100644 index 000000000..7829fe11f --- /dev/null +++ b/docs/api/melange/Stdlib-Complex.md @@ -0,0 +1,84 @@ +# Module `Stdlib.Complex` +Complex numbers. +This module provides arithmetic operations on complex numbers. Complex numbers are represented by their real and imaginary parts (cartesian representation). Each part is represented by a double-precision floating-point number (type `float`). +``` +type t = { +``` +`re : float;` +`im : float;` +``` +} +``` +The type of complex numbers. `re` is the real part and `im` the imaginary part. +``` +val zero : t +``` +The complex number `0`. +``` +val one : t +``` +The complex number `1`. +``` +val i : t +``` +The complex number `i`. +``` +val neg : t -> t +``` +Unary negation. +``` +val conj : t -> t +``` +Conjugate: given the complex `x + i.y`, returns `x - i.y`. +``` +val add : t -> t -> t +``` +Addition +``` +val sub : t -> t -> t +``` +Subtraction +``` +val mul : t -> t -> t +``` +Multiplication +``` +val inv : t -> t +``` +Multiplicative inverse (`1/z`). +``` +val div : t -> t -> t +``` +Division +``` +val sqrt : t -> t +``` +Square root. The result `x + i.y` is such that `x > 0` or `x = 0` and `y >= 0`. This function has a discontinuity along the negative real axis. +``` +val norm2 : t -> float +``` +Norm squared: given `x + i.y`, returns `x^2 + y^2`. +``` +val norm : t -> float +``` +Norm: given `x + i.y`, returns `sqrt(x^2 + y^2)`. +``` +val arg : t -> float +``` +Argument. The argument of a complex number is the angle in the complex plane between the positive real axis and a line passing through zero and the number. This angle ranges from `-pi` to `pi`. This function has a discontinuity along the negative real axis. +``` +val polar : float -> float -> t +``` +`polar norm arg` returns the complex having norm `norm` and argument `arg`. +``` +val exp : t -> t +``` +Exponentiation. `exp z` returns `e` to the `z` power. +``` +val log : t -> t +``` +Natural logarithm (in base `e`). +``` +val pow : t -> t -> t +``` +Power function. `pow z1 z2` returns `z1` to the `z2` power. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-BLAKE128.md b/docs/api/melange/Stdlib-Digest-BLAKE128.md new file mode 100644 index 000000000..8ac901a28 --- /dev/null +++ b/docs/api/melange/Stdlib-Digest-BLAKE128.md @@ -0,0 +1,61 @@ +# Module `Digest.BLAKE128` +`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. +since 5.2 +``` +type t = string +``` +The type of digests. +``` +val hash_length : int +``` +The length of digests, in bytes. +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). +``` +val equal : t -> t -> bool +``` +Test two digests for equality. +``` +val string : string -> t +``` +Return the digest of the given string. +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. +``` +val file : string -> t +``` +Return the digest of the file whose name is given. +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-BLAKE256.md b/docs/api/melange/Stdlib-Digest-BLAKE256.md new file mode 100644 index 000000000..a8666f993 --- /dev/null +++ b/docs/api/melange/Stdlib-Digest-BLAKE256.md @@ -0,0 +1,61 @@ +# Module `Digest.BLAKE256` +`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. +since 5.2 +``` +type t = string +``` +The type of digests. +``` +val hash_length : int +``` +The length of digests, in bytes. +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). +``` +val equal : t -> t -> bool +``` +Test two digests for equality. +``` +val string : string -> t +``` +Return the digest of the given string. +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. +``` +val file : string -> t +``` +Return the digest of the file whose name is given. +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-BLAKE512.md b/docs/api/melange/Stdlib-Digest-BLAKE512.md new file mode 100644 index 000000000..613a76602 --- /dev/null +++ b/docs/api/melange/Stdlib-Digest-BLAKE512.md @@ -0,0 +1,61 @@ +# Module `Digest.BLAKE512` +`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. +since 5.2 +``` +type t = string +``` +The type of digests. +``` +val hash_length : int +``` +The length of digests, in bytes. +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). +``` +val equal : t -> t -> bool +``` +Test two digests for equality. +``` +val string : string -> t +``` +Return the digest of the given string. +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. +``` +val file : string -> t +``` +Return the digest of the file whose name is given. +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-MD5.md b/docs/api/melange/Stdlib-Digest-MD5.md new file mode 100644 index 000000000..b881120cb --- /dev/null +++ b/docs/api/melange/Stdlib-Digest-MD5.md @@ -0,0 +1,61 @@ +# Module `Digest.MD5` +`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. +since 5.2 +``` +type t = string +``` +The type of digests. +``` +val hash_length : int +``` +The length of digests, in bytes. +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). +``` +val equal : t -> t -> bool +``` +Test two digests for equality. +``` +val string : string -> t +``` +Return the digest of the given string. +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. +``` +val file : string -> t +``` +Return the digest of the file whose name is given. +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-module-type-S.md b/docs/api/melange/Stdlib-Digest-module-type-S.md new file mode 100644 index 000000000..e553f47ae --- /dev/null +++ b/docs/api/melange/Stdlib-Digest-module-type-S.md @@ -0,0 +1,61 @@ +# Module type `Digest.S` +The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. +since 5.2 +``` +type t = string +``` +The type of digests. +``` +val hash_length : int +``` +The length of digests, in bytes. +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). +``` +val equal : t -> t -> bool +``` +Test two digests for equality. +``` +val string : string -> t +``` +Return the digest of the given string. +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. +``` +val file : string -> t +``` +Return the digest of the file whose name is given. +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest.md b/docs/api/melange/Stdlib-Digest.md new file mode 100644 index 000000000..b2e19fba1 --- /dev/null +++ b/docs/api/melange/Stdlib-Digest.md @@ -0,0 +1,91 @@ +# Module `Stdlib.Digest` +Message digest. +This module provides functions to compute 'digests', also known as 'hashes', of arbitrary-length strings or files. The supported hashing algorithms are BLAKE2 and MD5. +## Basic functions +The functions in this section use the MD5 hash function to produce 128-bit digests (16 bytes). MD5 is not cryptographically secure. Hence, these functions should not be used for security-sensitive applications. The BLAKE2 functions below are cryptographically secure. +``` +type t = string +``` +The type of digests: 16-byte strings. +``` +val compare : t -> t -> int +``` +The comparison function for 16-byte digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare) and the implementation shared with [`String.compare`](./Stdlib-String.md#val-compare). Along with the type `t`, this function `compare` allows the module `Digest` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). +since 4.00 +``` +val equal : t -> t -> bool +``` +The equal function for 16-byte digests. +since 4.03 +``` +val string : string -> t +``` +Return the digest of the given string. +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. +since 4.02 +``` +val substring : string -> int -> int -> t +``` +`Digest.substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. +``` +val subbytes : bytes -> int -> int -> t +``` +`Digest.subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. +since 4.02 +``` +val channel : in_channel -> int -> t +``` +If `len` is nonnegative, `Digest.channel ic len` reads `len` characters from channel `ic` and returns their digest, or raises `End_of_file` if end-of-file is reached before `len` characters are read. If `len` is negative, `Digest.channel ic len` reads all characters from `ic` until end-of-file is reached and return their digest. +``` +val file : string -> t +``` +Return the digest of the file whose name is given. +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 16 bytes. +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 32 hexadecimal characters. +since 5.2 +``` +val from_hex : string -> t +``` +Same function as [`Digest.of_hex`](./#val-of_hex). +since 4.00 +## Generic interface +``` +module type S = sig ... end +``` +The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. +## Specific hash functions +``` +module BLAKE128 : S +``` +`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. +``` +module BLAKE256 : S +``` +`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. +``` +module BLAKE512 : S +``` +`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. +``` +module MD5 : S +``` +`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Domain-DLS.md b/docs/api/melange/Stdlib-Domain-DLS.md new file mode 100644 index 000000000..b67997fdd --- /dev/null +++ b/docs/api/melange/Stdlib-Domain-DLS.md @@ -0,0 +1,35 @@ +# Module `Domain.DLS` +Domain-local Storage +``` +type 'a key +``` +Type of a DLS key +``` +val new_key : ?split_from_parent:('a -> 'a) -> (unit -> 'a) -> 'a key +``` +`new_key f` returns a new key bound to initialiser `f` for accessing domain-local variables. +If `split_from_parent` is not provided, the value for a new domain will be computed on-demand by the new domain: the first `get` call will call the initializer `f` and store that value. +**Warning.** `f` may be called several times if another call to `get` occurs during initialization on the same domain. Only the 'first' value computed will be used, the other now-useless values will be discarded. Your initialization function should support this situation, or contain logic to detect this case and fail. +If `split_from_parent` is provided, spawning a domain will derive the child value (for this key) from the parent value. This computation happens in the parent domain and it always happens, regardless of whether the child domain will use it. If the splitting function is expensive or requires child-side computation, consider using `'a Lazy.t key`: +```ocaml +let init () = ... + +let split_from_parent parent_value = + ... parent-side computation ...; + lazy ( + ... child-side computation ... + ) + +let key = Domain.DLS.new_key ~split_from_parent init + +let get () = Lazy.force (Domain.DLS.get key) +``` +In this case a part of the computation happens on the child domain; in particular, it can access `parent_value` concurrently with the parent domain, which may require explicit synchronization to avoid data races. +``` +val get : 'a key -> 'a +``` +`get k` returns `v` if a value `v` is associated to the key `k` on the calling domain's domain-local state. Sets `k`'s value with its initialiser and returns it otherwise. +``` +val set : 'a key -> 'a -> unit +``` +`set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. It overwrites any previous values associated to `k`, which cannot be restored later. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Domain.md b/docs/api/melange/Stdlib-Domain.md new file mode 100644 index 000000000..530280beb --- /dev/null +++ b/docs/api/melange/Stdlib-Domain.md @@ -0,0 +1,70 @@ +# Module `Stdlib.Domain` +alert unstable The Domain interface may change in incompatible ways in the future. +Domains. +See 'Parallel programming' chapter in the manual. +since 5.0 +alert unstable The Domain interface may change in incompatible ways in the future. +``` +type !'a t +``` +A domain of type `'a t` runs independently, eventually producing a result of type 'a, or an exception +``` +val spawn : (unit -> 'a) -> 'a t +``` +`spawn f` creates a new domain that runs in parallel with the current domain. +raises [`Failure`](./Stdlib.md#exception-Failure) if the program has insufficient resources to create another domain. +``` +val join : 'a t -> 'a Js.Promise.t +``` +`join d` blocks until domain `d` runs to completion. If `d` results in a value, then that is returned by `join d`. If `d` raises an uncaught exception, then that is re-raised by `join d`. +``` +type id = private int +``` +Domains have unique integer identifiers +``` +val get_id : 'a t -> id +``` +`get_id d` returns the identifier of the domain `d` +``` +val self : unit -> id +``` +`self ()` is the identifier of the currently running domain +``` +val before_first_spawn : (unit -> unit) -> unit +``` +`before_first_spawn f` registers `f` to be called before the first domain is spawned by the program. The functions registered with `before_first_spawn` are called on the main (initial) domain. The functions registered with `before_first_spawn` are called in 'first in, first out' order: the oldest function added with `before_first_spawn` is called first. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the program has already spawned a domain. +``` +val at_exit : (unit -> unit) -> unit +``` +`at_exit f` registers `f` to be called when the current domain exits. Note that `at_exit` callbacks are domain-local and only apply to the calling domain. The registered functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. An example: +```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) +``` +The snippet above creates a key that when retrieved for the first time will open a temporary file and register an `at_exit` callback to close it, thus guaranteeing the descriptor is not leaked in case the current domain exits. +``` +val cpu_relax : unit -> unit +``` +If busy-waiting, calling cpu\_relax () between iterations will improve performance on some CPU architectures +``` +val is_main_domain : unit -> bool +``` +`is_main_domain ()` returns true if called from the initial domain. +``` +val recommended_domain_count : unit -> int +``` +The recommended maximum number of domains which should be running simultaneously (including domains already running). +The value returned is at least `1`. +``` +val self_index : unit -> int +``` +The index of the current domain. It is an integer unique among currently-running domains, in the interval `0; N-1` where N is the peak number of domains running simultaneously so far. +The index of a terminated domain may be reused for a new domain. Use `(Domain.self () :> int)` instead for an identifier unique among all domains ever created by the program. +since 5.3 +``` +module DLS : sig ... end +``` +Domain-local Storage \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Dynarray.md b/docs/api/melange/Stdlib-Dynarray.md new file mode 100644 index 000000000..e2d14d0ee --- /dev/null +++ b/docs/api/melange/Stdlib-Dynarray.md @@ -0,0 +1,447 @@ +# Module `Stdlib.Dynarray` +Dynamic arrays. +The [`Array`](./Stdlib-Array.md) module provide arrays of fixed length. [`Dynarray`](#) provides arrays whose length can change over time, by adding or removing elements at the end of the array. +This is typically used to accumulate elements whose number is not known in advance or changes during computation, while also providing fast access to elements at arbitrary indices. +```ocaml + let dynarray_of_list li = + let arr = Dynarray.create () in + List.iter (fun v -> Dynarray.add_last arr v) li; + arr +``` +The [`Buffer`](./Stdlib-Buffer.md) module provides similar features, but it is specialized for accumulating characters into a dynamically-resized string. +The [`Stack`](./Stdlib-Stack.md) module provides a last-in first-out data structure that can be easily implemented on top of dynamic arrays. +since 5.2 +**Unsynchronized accesses** +Concurrent accesses to dynamic arrays must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). Unsynchronized accesses to a dynamic array are a programming error that may lead to an invalid dynamic array state, on which some operations would fail with an `Invalid_argument` exception. +## Dynamic arrays +``` +type !'a t +``` +A dynamic array containing values of type `'a`. +A dynamic array `a` provides constant-time `get` and `set` operations on indices between `0` and `Dynarray.length a - 1` included. Its [`length`](./#val-length) may change over time by adding or removing elements to the end of the array. +We say that an index into a dynarray `a` is valid if it is in `0 .. length a - 1` and invalid otherwise. +``` +val create : unit -> 'a t +``` +`create ()` is a new, empty array. +``` +val make : int -> 'a -> 'a t +``` +`make n x` is a new array of length `n`, filled with `x`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. +``` +val init : int -> (int -> 'a) -> 'a t +``` +`init n f` is a new array `a` of length `n`, such that `get a i` is `f i`. In other words, the elements of `a` are `f 0`, then `f 1`, then `f 2`... and `f (n - 1)` last, evaluated in that order. +This is similar to [`Array.init`](./Stdlib-Array.md#val-init). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. +``` +val get : 'a t -> int -> 'a +``` +`get a i` is the `i`\-th element of `a`, starting with index `0`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid +``` +val set : 'a t -> int -> 'a -> unit +``` +`set a i x` sets the `i`\-th element of `a` to be `x`. +`i` must be a valid index. `set` does not add new elements to the array \-- see [`add_last`](./#val-add_last) to add an element. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid. +``` +val length : 'a t -> int +``` +`length a` is the number of elements in the array. +``` +val is_empty : 'a t -> bool +``` +`is_empty a` is `true` if `a` is empty, that is, if `length a = 0`. +``` +val get_last : 'a t -> 'a +``` +`get_last a` is the element of `a` at index `length a - 1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if a is empty. +``` +val find_last : 'a t -> 'a option +``` +`find_last a` is `None` if `a` is empty and `Some (get_last a)` otherwise. +``` +val copy : 'a t -> 'a t +``` +`copy a` is a shallow copy of `a`, a new array containing the same elements as `a`. +## Adding elements +Note: all operations adding elements raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). +``` +val add_last : 'a t -> 'a -> unit +``` +`add_last a x` adds the element `x` at the end of the array `a`. +``` +val append_array : 'a t -> 'a array -> unit +``` +`append_array a b` adds all elements of `b` at the end of `a`, in the order they appear in `b`. +For example: +```ocaml + let a = Dynarray.of_list [1;2] in + Dynarray.append_array a [|3; 4|]; + assert (Dynarray.to_list a = [1; 2; 3; 4]) +``` +``` +val append_list : 'a t -> 'a list -> unit +``` +Like [`append_array`](./#val-append_array) but with a list. +``` +val append : 'a t -> 'a t -> unit +``` +`append a b` is like `append_array a b`, but `b` is itself a dynamic array instead of a fixed-size array. +Warning: `append a a` is a programming error because it iterates on `a` and adds elements to it at the same time \-- see the [Iteration](./#iteration) section below. It fails with `Invalid_argument`. If you really want to append a copy of `a` to itself, you can use `Dynarray.append_array a (Dynarray.to_array a)` which copies `a` into a temporary array. +``` +val append_seq : 'a t -> 'a Seq.t -> unit +``` +Like [`append_array`](./#val-append_array) but with a sequence. +Warning: `append_seq a (to_seq_reentrant a)` simultaneously traverses `a` and adds element to it; the ordering of those operations is unspecified, and may result in an infinite loop \-- the new elements may in turn be produced by `to_seq_reentrant a` and get added again and again. +``` +val append_iter : 'a t -> (('a -> unit) -> 'x -> unit) -> 'x -> unit +``` +`append_iter a iter x` adds each element of `x` to the end of `a`. This is `iter (add_last a) x`. +For example, `append_iter a List.iter [1;2;3]` would add elements `1`, `2`, and then `3` at the end of `a`. `append_iter a Queue.iter q` adds elements from the queue `q`. +``` +val blit : + src:'a t -> + src_pos:int -> + dst:'a t -> + dst_pos:int -> + len:int -> + unit +``` +`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from a source dynarray `src`, starting at index `src_pos`, to a destination dynarray `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. +Unlike [`Array.blit`](./Stdlib-Array.md#val-blit), [`Dynarray.blit`](./#val-blit) can extend the destination array with new elements: it is valid to call `blit` even when `dst_pos + len` is larger than `length dst`. The only requirement is that `dst_pos` must be at most `length dst` (included), so that there is no gap between the current elements and the blit region. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos is strictly below 0 or strictly above length dst. +## Removing elements +``` +val pop_last_opt : 'a t -> 'a option +``` +`pop_last_opt a` removes and returns the last element of `a`, or `None` if the array is empty. +``` +val pop_last : 'a t -> 'a +``` +`pop_last a` removes and returns the last element of `a`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) on an empty array. +``` +val remove_last : 'a t -> unit +``` +`remove_last a` removes the last element of `a`, if any. It does nothing if `a` is empty. +``` +val truncate : 'a t -> int -> unit +``` +`truncate a n` truncates `a` to have at most `n` elements. +It removes elements whose index is greater or equal to `n`. It does nothing if `n >= length a`. +`truncate a n` is equivalent to: +```ocaml + if n < 0 then invalid_argument "..."; + while length a > n do + remove_last a + done +``` +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. +``` +val clear : 'a t -> unit +``` +`clear a` is `truncate a 0`, it removes all the elements of `a`. +## Iteration +The iteration functions traverse the elements of a dynamic array. Traversals of `a` are computed in increasing index order: from the element of index `0` to the element of index `length a - 1`. +It is a programming error to change the length of an array (by adding or removing elements) during an iteration on the array. Any iteration function will fail with `Invalid_argument` if it detects such a length change. +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f a` calls `f` on each element of `a`. +``` +val iteri : (int -> 'a -> unit) -> 'a t -> unit +``` +`iteri f a` calls `f i x` for each `x` at index `i` in `a`. +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f a` is a new array of elements of the form `f x` for each element `x` of `a`. +For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f x0`, `f x1`, `f x2`. +``` +val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t +``` +`mapi f a` is a new array of elements of the form `f i x` for each element `x` of `a` at index `i`. +For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f 0 x0`, `f 1 x1`, `f 2 x2`. +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold_left f acc a` folds `f` over `a` in order, starting with accumulator `acc`. +For example, if the elements of `a` are `x0`, `x1`, then `fold f acc a` is +```ocaml + let acc = f acc x0 in + let acc = f acc x1 in + acc +``` +``` +val fold_right : ('a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +`fold_right f a acc` computes `f x0 (f x1 (... (f xn acc) ...))` where `x0`, `x1`, ..., `xn` are the elements of `a`. +``` +val filter : ('a -> bool) -> 'a t -> 'a t +``` +`filter f a` is a new array of all the elements of `a` that satisfy `f`. In other words, it is an array `b` such that, for each element `x` in `a` in order, `x` is added to `b` if `f x` is `true`. +For example, `filter (fun x -> x >= 0) a` is a new array of all non-negative elements of `a`, in order. +``` +val filter_map : ('a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f a` is a new array of elements `y` such that `f x` is `Some y` for an element `x` of `a`. In others words, it is an array `b` such that, for each element `x` of `a` in order: +- if `f x = Some y`, then `y` is added to `b`, +- if `f x = None`, then no element is added to `b`. +For example, `filter_map int_of_string_opt inputs` returns a new array of integers read from the strings in `inputs`, ignoring strings that cannot be converted to integers. +## Dynarray scanning +``` +val exists : ('a -> bool) -> 'a t -> bool +``` +`exists f a` is `true` if some element of `a` satisfies `f`. +For example, if the elements of `a` are `x0`, `x1`, `x2`, then `exists f a` is `f x0 || f x1 || f x2`. +``` +val for_all : ('a -> bool) -> 'a t -> bool +``` +`for_all f a` is `true` if all elements of `a` satisfy `f`. This includes the case where `a` is empty. +For example, if the elements of `a` are `x0`, `x1`, then `exists f a` is `f x0 && f x1 && f x2`. +``` +val mem : 'a -> 'a t -> bool +``` +`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). +since 5.3 +``` +val memq : 'a -> 'a t -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. +since 5.3 +``` +val find_opt : ('a -> bool) -> 'a t -> 'a option +``` +`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. +since 5.3 +``` +val find_index : ('a -> bool) -> 'a t -> int option +``` +`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. +It returns `None` if there is no such element. +since 5.3 +``` +val find_map : ('a -> 'b option) -> 'a t -> 'b option +``` +`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. +since 5.3 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 5.3 +## Comparison functions +Comparison functions iterate over their arguments; it is a programming error to change their length during the iteration, see the [Iteration](./#iteration) section above. +``` +val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal eq a b` holds when `a` and `b` have the same length, and for all indices `i` we have `eq (get a i) (get b i)`. +since 5.3 +``` +val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Provided the function `cmp` defines a preorder on elements, `compare cmp a b` compares first `a` and `b` by their length, and then, if equal, by their elements according to the lexicographic preorder. +For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). +since 5.3 +## Conversions to other data structures +Note: the `of_*` functions raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). +The `to_*` functions, except those specifically marked "reentrant", iterate on their dynarray argument. In particular it is a programming error if the length of the dynarray changes during their execution, and the conversion functions raise `Invalid_argument` if they observe such a change. +``` +val of_array : 'a array -> 'a t +``` +`of_array arr` returns a dynamic array corresponding to the fixed-sized array `a`. Operates in `O(n)` time by making a copy. +``` +val to_array : 'a t -> 'a array +``` +`to_array a` returns a fixed-sized array corresponding to the dynamic array `a`. This always allocate a new array and copies elements into it. +``` +val of_list : 'a list -> 'a t +``` +`of_list l` is the array containing the elements of `l` in the same order. +``` +val to_list : 'a t -> 'a list +``` +`to_list a` is a list with the elements contained in the array `a`. +``` +val of_seq : 'a Seq.t -> 'a t +``` +`of_seq seq` is an array containing the same elements as `seq`. +It traverses `seq` once and will terminate only if `seq` is finite. +``` +val to_seq : 'a t -> 'a Seq.t +``` +`to_seq a` is the sequence of elements `get a 0`, `get a 1`... `get a (length a - 1)`. +``` +val to_seq_reentrant : 'a t -> 'a Seq.t +``` +`to_seq_reentrant a` is a reentrant variant of [`to_seq`](./#val-to_seq), in the sense that one may still access its elements after the length of `a` has changed. +Demanding the `i`\-th element of the resulting sequence (which can happen zero, one or several times) will access the `i`\-th element of `a` at the time of the demand. The sequence stops if `a` has less than `i` elements at this point. +``` +val to_seq_rev : 'a t -> 'a Seq.t +``` +`to_seq_rev a` is the sequence of elements `get a (l - 1)`, `get a (l - 2)`... `get a 0`, where `l` is `length a` at the time `to_seq_rev` is invoked. +``` +val to_seq_rev_reentrant : 'a t -> 'a Seq.t +``` +`to_seq_rev_reentrant a` is a reentrant variant of [`to_seq_rev`](./#val-to_seq_rev), in the sense that one may still access its elements after the length of `a` has changed. +Elements that have been removed from the array by the time they are demanded in the sequence are skipped. +## Advanced topics for performance +### Backing array, capacity +Internally, a dynamic array uses a **backing array** (a fixed-size array as provided by the [`Array`](./Stdlib-Array.md) module) whose length is greater or equal to the length of the dynamic array. We define the **capacity** of a dynamic array as the length of its backing array. +The capacity of a dynamic array is relevant in advanced scenarios, when reasoning about the performance of dynamic array programs: +- The memory usage of a dynamic array is proportional to its capacity, rather than its length. +- When there is no empty space left at the end of the backing array, adding elements requires allocating a new, larger backing array. +The implementation uses a standard exponential reallocation strategy which guarantees amortized constant-time operation; in particular, the total capacity of all backing arrays allocated over the lifetime of a dynamic array is at worst proportional to the total number of elements added. +In other words, users need not care about capacity and reallocations, and they will get reasonable behavior by default. However, in some performance-sensitive scenarios the functions below can help control memory usage or guarantee an optimal number of reallocations. +``` +val capacity : 'a t -> int +``` +`capacity a` is the length of `a`'s backing array. +``` +val ensure_capacity : 'a t -> int -> unit +``` +`ensure_capacity a n` makes sure that the capacity of `a` is at least `n`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the requested capacity is outside the range 0 .. Sys.max\_array\_length. +An example would be to reimplement [`of_array`](./#val-of_array) without using [`init`](./#val-init): +```ocaml +let of_array arr = + let a = Dynarray.create () in + Dynarray.ensure_capacity a (Array.length arr); + Array.iter (fun v -> add_last a v) arr +``` +Using `ensure_capacity` guarantees that at most one reallocation will take place, instead of possibly several. +Without this `ensure_capacity` hint, the number of resizes would be logarithmic in the length of `arr`, creating a constant-factor slowdown noticeable when `arr` is large. +``` +val ensure_extra_capacity : 'a t -> int -> unit +``` +`ensure_extra_capacity a n` is `ensure_capacity a (length a + n)`, it makes sure that `a` has room for `n` extra items. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the total requested capacity is outside the range 0 .. Sys.max\_array\_length. +A use case would be to implement [`append_array`](./#val-append_array): +```ocaml +let append_array a arr = + ensure_extra_capacity a (Array.length arr); + Array.iter (fun v -> add_last a v) arr +``` +``` +val fit_capacity : 'a t -> unit +``` +`fit_capacity a` reallocates a backing array if necessary, so that the resulting capacity is exactly `length a`, with no additional empty space at the end. This can be useful to make sure there is no memory wasted on a long-lived array. +Note that calling `fit_capacity` breaks the amortized complexity guarantees provided by the default reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. +If you know that a dynamic array has reached its final length, which will remain fixed in the future, it is sufficient to call `to_array` and only keep the resulting fixed-size array. `fit_capacity` is useful when you need to keep a dynamic array for eventual future resizes. +``` +val set_capacity : 'a t -> int -> unit +``` +`set_capacity a n` reallocates a backing array if necessary, so that the resulting capacity is exactly `n`. In particular, all elements of index `n` or greater are removed. +Like [`fit_capacity`](./#val-fit_capacity), this function breaks the amortized complexity guarantees provided by the reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. +This is an advanced function; in particular, [`ensure_capacity`](./#val-ensure_capacity) should be preferred to increase the capacity, as it preserves those amortized guarantees. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. +``` +val reset : 'a t -> unit +``` +`reset a` clears `a` and replaces its backing array by an empty array. +It is equivalent to `set_capacity a 0` or `clear a; fit_capacity a`. +### No leaks: preservation of memory liveness +The user-provided values reachable from a dynamic array `a` are exactly the elements in the indices `0` to `length a - 1`. In particular, no user-provided values are "leaked" by being present in the backing array at index `length a` or later. +## Code examples +### Min-heaps for mutable priority queues +We can use dynamic arrays to implement a mutable priority queue. A priority queue provides a function to add elements, and a function to extract the minimum element \-- according to some comparison function. +```ocaml +(* We present our priority queues as a functor + parametrized on the comparison function. *) +module Heap (Elem : Map.OrderedType) : sig + type t + val create : unit -> t + val add : t -> Elem.t -> unit + val pop_min : t -> Elem.t option +end = struct + + (* Our priority queues are implemented using the standard "min heap" + data structure, a dynamic array representing a binary tree. *) + type t = Elem.t Dynarray.t + let create = Dynarray.create + + (* The node of index [i] has as children the nodes of index [2 * i + 1] + and [2 * i + 2] -- if they are valid indices in the dynarray. *) + let left_child i = 2 * i + 1 + let right_child i = 2 * i + 2 + let parent_node i = (i - 1) / 2 + + (* We use indexing operators for convenient notations. *) + let ( .!() ) = Dynarray.get + let ( .!()<- ) = Dynarray.set + + (* Auxiliary functions to compare and swap two elements + in the dynamic array. *) + let order h i j = + Elem.compare h.!(i) h.!(j) + + let swap h i j = + let v = h.!(i) in + h.!(i) <- h.!(j); + h.!(j) <- v + + (* We say that a heap respects the "heap ordering" if the value of + each node is smaller than the value of its children. The + algorithm manipulates arrays that respect the heap algorithm, + except for one node whose value may be too small or too large. + + The auxiliary functions [heap_up] and [heap_down] take + such a misplaced value, and move it "up" (respectively: "down") + the tree by permuting it with its parent value (respectively: + a child value) until the heap ordering is restored. *) + + let rec heap_up h i = + if i = 0 then () else + let parent = parent_node i in + if order h i parent < 0 then + (swap h i parent; heap_up h parent) + + and heap_down h ~len i = + let left, right = left_child i, right_child i in + if left >= len then () (* no child, stop *) else + let smallest = + if right >= len then left (* no right child *) else + if order h left right < 0 then left else right + in + if order h i smallest > 0 then + (swap h i smallest; heap_down h ~len smallest) + + let add h s = + let i = Dynarray.length h in + Dynarray.add_last h s; + heap_up h i + + let pop_min h = + if Dynarray.is_empty h then None + else begin + (* Standard trick: swap the 'best' value at index 0 + with the last value of the array. *) + let last = Dynarray.length h - 1 in + swap h 0 last; + (* At this point [pop_last] returns the 'best' value, + and leaves a heap with one misplaced element at index [0]. *) + let best = Dynarray.pop_last h in + (* Restore the heap ordering -- does nothing if the heap is empty. *) + heap_down h ~len:last 0; + Some best + end +end +``` +The production code from which this example was inspired includes logic to free the backing array when the heap becomes empty, only in the case where the capacity is above a certain threshold. This can be done by calling the following function from `pop`: +```ocaml +let shrink h = + if Dynarray.length h = 0 && Dynarray.capacity h > 1 lsl 18 then + Dynarray.reset h +``` +The `Heap` functor can be used to implement a sorting function, by adding all elements into a priority queue and then extracting them in order. +```ocaml +let heap_sort (type a) cmp li = + let module Heap = Heap(struct type t = a let compare = cmp end) in + let heap = Heap.create () in + List.iter (Heap.add heap) li; + List.map (fun _ -> Heap.pop_min heap |> Option.get) li +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Either.md b/docs/api/melange/Stdlib-Either.md new file mode 100644 index 000000000..4f31dbbec --- /dev/null +++ b/docs/api/melange/Stdlib-Either.md @@ -0,0 +1,94 @@ +# Module `Stdlib.Either` +Either type. +Either is the simplest and most generic sum/variant type: a value of `('a, 'b) Either.t` is either a `Left (v : 'a)` or a `Right (v : 'b)`. +It is a natural choice in the API of generic functions where values could fall in two different cases, possibly at different types, without assigning a specific meaning to what each case should be. +For example: +```ocaml +List.partition_map: + ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list +``` +If you are looking for a parametrized type where one alternative means success and the other means failure, you should use the more specific type [`Result.t`](./Stdlib-Result.md#type-t). +since 4.12 +``` +type ('a, 'b) t = +``` +``` +| Left of 'a +``` +``` +| Right of 'b +``` +``` + +``` +A value of `('a, 'b) Either.t` contains either a value of `'a` or a value of `'b` +``` +val left : 'a -> ('a, 'b) t +``` +`left v` is `Left v`. +``` +val right : 'b -> ('a, 'b) t +``` +`right v` is `Right v`. +``` +val is_left : ('a, 'b) t -> bool +``` +`is_left (Left v)` is `true`, `is_left (Right v)` is `false`. +``` +val is_right : ('a, 'b) t -> bool +``` +`is_right (Left v)` is `false`, `is_right (Right v)` is `true`. +``` +val find_left : ('a, 'b) t -> 'a option +``` +`find_left (Left v)` is `Some v`, `find_left (Right _)` is `None` +``` +val find_right : ('a, 'b) t -> 'b option +``` +`find_right (Right v)` is `Some v`, `find_right (Left _)` is `None` +``` +val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t +``` +`map_left f e` is `Left (f v)` if `e` is `Left v` and `e` if `e` is `Right _`. +``` +val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t +``` +`map_right f e` is `Right (f v)` if `e` is `Right v` and `e` if `e` is `Left _`. +``` +val map : + left:('a1 -> 'a2) -> + right:('b1 -> 'b2) -> + ('a1, 'b1) t -> + ('a2, 'b2) t +``` +`map ~left ~right (Left v)` is `Left (left v)`, `map ~left ~right (Right v)` is `Right (right v)`. +``` +val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c +``` +`fold ~left ~right (Left v)` is `left v`, and `fold ~left ~right (Right v)` is `right v`. +``` +val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit +``` +`iter ~left ~right (Left v)` is `left v`, and `iter ~left ~right (Right v)` is `right v`. +``` +val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool +``` +`for_all ~left ~right (Left v)` is `left v`, and `for_all ~left ~right (Right v)` is `right v`. +``` +val equal : + left:('a -> 'a -> bool) -> + right:('b -> 'b -> bool) -> + ('a, 'b) t -> + ('a, 'b) t -> + bool +``` +`equal ~left ~right e0 e1` tests equality of `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. +``` +val compare : + left:('a -> 'a -> int) -> + right:('b -> 'b -> int) -> + ('a, 'b) t -> + ('a, 'b) t -> + int +``` +`compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _ ` and `Right _`. `Left _` values are smaller than `Right _` values. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Filename.md b/docs/api/melange/Stdlib-Filename.md new file mode 100644 index 000000000..78815ae75 --- /dev/null +++ b/docs/api/melange/Stdlib-Filename.md @@ -0,0 +1,132 @@ +# Module `Stdlib.Filename` +Operations on file names. +``` +val current_dir_name : string +``` +The conventional name for the current directory (e.g. `.` in Unix). +``` +val parent_dir_name : string +``` +The conventional name for the parent of the current directory (e.g. `..` in Unix). +``` +val dir_sep : string +``` +The directory separator (e.g. `/` in Unix). +since 3.11.2 +``` +val concat : string -> string -> string +``` +`concat dir file` returns a file name that designates file `file` in directory `dir`. +``` +val is_relative : string -> bool +``` +Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. in Unix, starts with `/`). +``` +val is_implicit : string -> bool +``` +Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory. +``` +val check_suffix : string -> string -> bool +``` +`check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`. +Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. +``` +val chop_suffix : string -> string -> string +``` +`chop_suffix name suff` removes the suffix `suff` from the filename `name`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if name does not end with the suffix suff. +``` +val chop_suffix_opt : suffix:string -> string -> string option +``` +`chop_suffix_opt ~suffix filename` removes the suffix from the `filename` if possible, or returns `None` if the filename does not end with the suffix. +Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. +since 4.08 +``` +val extension : string -> string +``` +`extension name` is the shortest suffix `ext` of `name0` where: +- `name0` is the longest suffix of `name` that does not contain a directory separator; +- `ext` starts with a period; +- `ext` is preceded by at least one non-period character in `name0`. +If such a suffix does not exist, `extension name` is the empty string. +since 4.04 +``` +val remove_extension : string -> string +``` +Return the given file name without its extension, as defined in [`Filename.extension`](./#val-extension). If the extension is empty, the function returns the given file name. +The following invariant holds for any file name `s`: +`remove_extension s ^ extension s = s` +since 4.04 +``` +val chop_extension : string -> string +``` +Same as [`Filename.remove_extension`](./#val-remove_extension), but raise `Invalid_argument` if the given name has an empty extension. +``` +val basename : string -> string +``` +Split a file name into directory name / base file name. If `name` is a valid file name, then `concat (dirname name) (basename name)` returns a file name which is equivalent to `name`. Moreover, after setting the current directory to `dirname name` (with [`Sys.chdir`](./Stdlib-Sys.md#val-chdir)), references to `basename name` (which is a relative file name) designate the same file as `name` before the call to [`Sys.chdir`](./Stdlib-Sys.md#val-chdir). +This function conforms to the specification of POSIX.1-2008 for the `basename` utility. +``` +val dirname : string -> string +``` +See [`Filename.basename`](./#val-basename). This function conforms to the specification of POSIX.1-2008 for the `dirname` utility. +``` +val null : string +``` +`null` is `"/dev/null"` on POSIX and `"NUL"` on Windows. It represents a file on the OS that discards all writes and returns end of file on reads. +since 4.10 +``` +val temp_file : ?temp_dir:string -> string -> string -> string +``` +`temp_file prefix suffix` returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary file is created empty, with permissions `0o600` (readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when `temp_file` was called. +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be created. +before 3.11.2 no ?temp\_dir optional argument +``` +val open_temp_file : + ?mode:open_flag list -> + ?perms:int -> + ?temp_dir:string -> + string -> + string -> + string * out_channel +``` +Same as [`Filename.temp_file`](./#val-temp_file), but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than `temp_file`: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument `mode` is a list of additional flags to control the opening of the file. It can contain one or several of `Open_append`, `Open_binary`, and `Open_text`. The default is `[Open_text]` (open in text mode). The file is created with permissions `perms` (defaults to readable and writable only by the file owner, `0o600`). +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be opened. +before 4.03 no ?perms optional argument +before 3.11.2 no ?temp\_dir optional argument +``` +val temp_dir : ?temp_dir:string -> ?perms:int -> string -> string -> string +``` +`temp_dir prefix suffix` creates and returns the name of a fresh temporary directory with permissions `perms` (defaults to 0o700) inside `temp_dir`. The base name of the temporary directory is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary directory is created empty, with permissions `0o700` (readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when `temp_dir` was called. +If temp\_dir does not exist, this function does not create it. Instead, it raises Sys\_error. +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the directory could not be created. +since 5.1 +``` +val get_temp_dir_name : unit -> string +``` +The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the `TEMP` environment variable, or "." if the variable is not set. The temporary directory can be changed with [`Filename.set_temp_dir_name`](./#val-set_temp_dir_name). +since 4.00 +``` +val set_temp_dir_name : string -> unit +``` +Change the temporary directory returned by [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name) and used by [`Filename.temp_file`](./#val-temp_file) and [`Filename.open_temp_file`](./#val-open_temp_file). The temporary directory is a domain-local value which is inherited by child domains. +since 4.00 +``` +val quote : string -> string +``` +Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions. +``` +val quote_command : + string -> + ?stdin:string -> + ?stdout:string -> + ?stderr:string -> + string list -> + string +``` +`quote_command cmd args` returns a quoted command line, suitable for use as an argument to [`Sys.command`](./Stdlib-Sys.md#val-command), `Unix.system`, and the `Unix.open_process` functions. +The string `cmd` is the command to call. The list `args` is the list of arguments to pass to this command. It can be empty. +The optional arguments `?stdin` and `?stdout` and `?stderr` are file names used to redirect the standard input, the standard output, or the standard error of the command. If `~stdin:f` is given, a redirection `< f` is performed and the standard input of the command reads from file `f`. If `~stdout:f` is given, a redirection `> f` is performed and the standard output of the command is written to file `f`. If `~stderr:f` is given, a redirection `2> f` is performed and the standard error of the command is written to file `f`. If both `~stdout:f` and `~stderr:f` are given, with the exact same file name `f`, a `2>&1` redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file `f`. +Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using [`Filename.quote`](./#val-quote), then concatenated. Under Win32, additional quoting is performed as required by the `cmd.exe` shell that is called by [`Sys.command`](./Stdlib-Sys.md#val-command). +raises [`Failure`](./Stdlib.md#exception-Failure) if the command cannot be escaped on the current platform. +since 4.10 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Float-Array.md b/docs/api/melange/Stdlib-Float-Array.md new file mode 100644 index 000000000..4fad7c009 --- /dev/null +++ b/docs/api/melange/Stdlib-Float-Array.md @@ -0,0 +1,247 @@ +# Module `Float.Array` +Float arrays with packed representation. +``` +type t = floatarray +``` +The type of float arrays with packed representation. +since 4.08 +``` +val length : t -> int +``` +Return the length (number of elements) of the given floatarray. +``` +val get : t -> int -> float +``` +`get a n` returns the element number `n` of floatarray `a`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val set : t -> int -> float -> unit +``` +`set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val make : int -> float -> t +``` +`make n x` returns a fresh floatarray of length `n`, initialized with `x`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. +``` +val create : int -> t +``` +`create n` returns a fresh floatarray of length `n`, with uninitialized data. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. +``` +val init : int -> (int -> float) -> t +``` +`init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers `0` to `n-1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. +``` +val make_matrix : int -> int -> float -> t array +``` +`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where all elements are initialized with `e`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. +since 5.2 +``` +val init_matrix : int -> int -> (int -> int -> float) -> t array +``` +`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. +since 5.2 +``` +val append : t -> t -> t +``` +`append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_floatarray\_length. +``` +val concat : t list -> t +``` +Same as [`append`](./#val-append), but concatenates a list of floatarrays. +``` +val sub : t -> int -> int -> t +``` +`sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. +``` +val copy : t -> t +``` +`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`. +``` +val fill : t -> int -> int -> float -> unit +``` +`fill a pos len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. +``` +val blit : t -> int -> t -> int -> int -> unit +``` +`blit src src_pos dst dst_pos len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. +``` +val to_list : t -> float list +``` +`to_list a` returns the list of all the elements of `a`. +``` +val of_list : float list -> t +``` +`of_list l` returns a fresh floatarray containing the elements of `l`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_floatarray\_length. +## Iterators +``` +val iter : (float -> unit) -> t -> unit +``` +`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. +``` +val iteri : (int -> float -> unit) -> t -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied with the index of the element as first argument, and the element itself as second argument. +``` +val map : (float -> float) -> t -> t +``` +`map f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. +``` +val map_inplace : (float -> float) -> t -> unit +``` +`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. +since 5.1 +``` +val mapi : (int -> float -> float) -> t -> t +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. +``` +val mapi_inplace : (int -> float -> float) -> t -> unit +``` +Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. +since 5.1 +``` +val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc +``` +`fold_left f x init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`. +``` +val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`. +## Iterators on two arrays +``` +val iter2 : (float -> float -> unit) -> t -> t -> unit +``` +`Array.iter2 f a b` applies function `f` to all the elements of `a` and `b`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. +``` +val map2 : (float -> float -> float) -> t -> t -> t +``` +`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. +## Array scanning +``` +val for_all : (float -> bool) -> t -> bool +``` +`for_all f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. +``` +val exists : (float -> bool) -> t -> bool +``` +`exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. +``` +val mem : float -> t -> bool +``` +`mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`. +``` +val mem_ieee : float -> t -> bool +``` +Same as [`mem`](./#val-mem), but uses IEEE equality instead of structural equality. +## Array searching +``` +val find_opt : (float -> bool) -> t -> float option +``` +``` +val find_index : (float -> bool) -> t -> int option +``` +`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. +It returns `None` if there is no such element. +since 5.1 +``` +val find_map : (float -> 'a option) -> t -> 'a option +``` +``` +val find_mapi : (int -> float -> 'a option) -> t -> 'a option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 5.1 +## Sorting and shuffling +``` +val sort : (float -> float -> int) -> t -> unit +``` +Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. +The current implementation uses Heap Sort. It runs in constant stack space. +Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : +- `cmp x y` \> 0 if and only if `cmp y x` \< 0 +- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 +When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : +- `cmp a.(i) a.(j)` \>= 0 if i \>= j +``` +val stable_sort : (float -> float -> int) -> t -> unit +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. +The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of [`sort`](./#val-sort). +``` +val fast_sort : (float -> float -> int) -> t -> unit +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. +``` +val shuffle : rand:(int -> int) -> t -> unit +``` +`shuffle rand a` randomly permutes `a`'s elements using `rand` for randomness. The distribution of permutations is uniform. +`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). +since 5.2 +## Float arrays and Sequences +``` +val to_seq : t -> float Seq.t +``` +Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence. +``` +val to_seqi : t -> (int * float) Seq.t +``` +Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence. +``` +val of_seq : float Seq.t -> t +``` +Create an array from the generator. +``` +val map_to_array : (float -> 'a) -> t -> 'a array +``` +`map_to_array f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. +``` +val map_from_array : ('a -> float) -> 'a array -> t +``` +`map_from_array f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. +## Arrays and concurrency safety +Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. +### Atomicity +Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. +For example, consider the following program: +```ocaml +let size = 100_000_000 +let a = Float.Array.make size 1. +let update a f () = + Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a +let d1 = Domain.spawn (update a (fun x -> x +. 1.)) +let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.)) +let () = Domain.join d1; Domain.join d2 +``` +After executing this code, each field of the float array `a` is either `2.`, `3.`, `4.` or `5.`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +### Data races +If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. +A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions. +### Tearing +Float arrays have two supplementary caveats in the presence of data races. +First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. +For instance, at the end of +```ocaml +let zeros = Float.Array.make size 0. +let max_floats = Float.Array.make size Float.max_float +let res = Float.Array.copy zeros +let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size) +let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size) +let () = Domain.join d1; Domain.join d2 +``` +the `res` float array might contain values that are neither `0.` nor `max_float`. +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Float.md b/docs/api/melange/Stdlib-Float.md new file mode 100644 index 000000000..26062df73 --- /dev/null +++ b/docs/api/melange/Stdlib-Float.md @@ -0,0 +1,388 @@ +# Module `Stdlib.Float` +Floating-point arithmetic. +OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... +since 4.07 +``` +val zero : float +``` +The floating point 0. +since 4.08 +``` +val one : float +``` +The floating-point 1\. +since 4.08 +``` +val minus_one : float +``` +The floating-point \-1. +since 4.08 +``` +val neg : float -> float +``` +Unary negation. +``` +val add : float -> float -> float +``` +Floating-point addition. +``` +val sub : float -> float -> float +``` +Floating-point subtraction. +``` +val mul : float -> float -> float +``` +Floating-point multiplication. +``` +val div : float -> float -> float +``` +Floating-point division. +``` +val fma : float -> float -> float -> float +``` +`fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation. +On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters. +since 4.08 +``` +val rem : float -> float -> float +``` +`rem a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. +``` +val succ : float -> float +``` +`succ x` returns the floating point number right after `x` i.e., the smallest floating-point number greater than `x`. See also [`next_after`](./#val-next_after). +since 4.08 +``` +val pred : float -> float +``` +`pred x` returns the floating-point number right before `x` i.e., the greatest floating-point number smaller than `x`. See also [`next_after`](./#val-next_after). +since 4.08 +``` +val abs : float -> float +``` +`abs f` returns the absolute value of `f`. +``` +val infinity : float +``` +Positive infinity. +``` +val neg_infinity : float +``` +Negative infinity. +``` +val nan : float +``` +A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. Stands for 'not a number'. Any floating-point operation with `nan` as argument returns `nan` as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, `=`, `<`, `<=`, `>` and `>=` return `false` and `<>` returns `true` if one or both of their arguments is `nan`. +`nan` is `quiet_nan` since 5.1; it was a signaling NaN before. +``` +val signaling_nan : float +``` +Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries. +since 5.1 +``` +val quiet_nan : float +``` +Quiet NaN. +since 5.1 +``` +val pi : float +``` +The constant pi. +``` +val max_float : float +``` +The largest positive finite value of type `float`. +``` +val min_float : float +``` +The smallest positive, non-zero, non-denormalized value of type `float`. +``` +val epsilon : float +``` +The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. +``` +val is_finite : float -> bool +``` +`is_finite x` is `true` if and only if `x` is finite i.e., not infinite and not [`nan`](./#val-nan). +since 4.08 +``` +val is_infinite : float -> bool +``` +`is_infinite x` is `true` if and only if `x` is [`infinity`](./#val-infinity) or [`neg_infinity`](./#val-neg_infinity). +since 4.08 +``` +val is_nan : float -> bool +``` +`is_nan x` is `true` if and only if `x` is not a number (see [`nan`](./#val-nan)). +since 4.08 +``` +val is_integer : float -> bool +``` +`is_integer x` is `true` if and only if `x` is an integer. +since 4.08 +``` +val of_int : int -> float +``` +Convert an integer to floating-point. +``` +val to_int : float -> int +``` +Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. +``` +val of_string : string -> float +``` +Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The `_` (underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. +raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of a float. +``` +val of_string_opt : string -> float option +``` +Same as `of_string`, but returns `None` instead of raising. +``` +val to_string : float -> string +``` +Return a string representation of a floating-point number. +This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). +This function is an alias for [`Stdlib.string_of_float`](./Stdlib.md#val-string_of_float). +``` +type fpclass = fpclass = +``` +``` +| FP_normal +``` +Normal number, none of the below +``` +| FP_subnormal +``` +Number very close to 0.0, has reduced precision +``` +| FP_zero +``` +Number is 0.0 or \-0.0 +``` +| FP_infinite +``` +Number is positive or negative infinity +``` +| FP_nan +``` +Not a number: result of an undefined operation +``` + +``` +The five classes of floating-point numbers, as determined by the [`classify_float`](./#val-classify_float) function. +``` +val classify_float : float -> fpclass +``` +Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number. +``` +val pow : float -> float -> float +``` +Exponentiation. +``` +val sqrt : float -> float +``` +Square root. +``` +val cbrt : float -> float +``` +Cube root. +since 4.13 +``` +val exp : float -> float +``` +Exponential. +``` +val exp2 : float -> float +``` +Base 2 exponential function. +since 4.13 +``` +val log : float -> float +``` +Natural logarithm. +``` +val log10 : float -> float +``` +Base 10 logarithm. +``` +val log2 : float -> float +``` +Base 2 logarithm. +since 4.13 +``` +val expm1 : float -> float +``` +`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. +``` +val log1p : float -> float +``` +`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. +``` +val cos : float -> float +``` +Cosine. Argument is in radians. +``` +val sin : float -> float +``` +Sine. Argument is in radians. +``` +val tan : float -> float +``` +Tangent. Argument is in radians. +``` +val acos : float -> float +``` +Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. +``` +val asin : float -> float +``` +Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. +``` +val atan : float -> float +``` +Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. +``` +val atan2 : float -> float -> float +``` +`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. +``` +val hypot : float -> float -> float +``` +`hypot x y` returns `sqrt(x *. x +. y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. If one of `x` or `y` is infinite, returns `infinity` even if the other is `nan`. +``` +val cosh : float -> float +``` +Hyperbolic cosine. Argument is in radians. +``` +val sinh : float -> float +``` +Hyperbolic sine. Argument is in radians. +``` +val tanh : float -> float +``` +Hyperbolic tangent. Argument is in radians. +``` +val acosh : float -> float +``` +Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. +since 4.13 +``` +val asinh : float -> float +``` +Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. +since 4.13 +``` +val atanh : float -> float +``` +Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. +since 4.13 +``` +val erf : float -> float +``` +Error function. The argument ranges over the entire real line. The result is always within `[-1.0, 1.0]`. +since 4.13 +``` +val erfc : float -> float +``` +Complementary error function (`erfc x = 1 - erf x`). The argument ranges over the entire real line. The result is always within `[0.0, 2.0]`. +since 4.13 +``` +val trunc : float -> float +``` +`trunc x` rounds `x` to the nearest integer whose absolute value is less than or equal to `x`. +since 4.08 +``` +val round : float -> float +``` +`round x` rounds `x` to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If `x` is an integer, `+0.`, `-0.`, `nan`, or infinite, `x` itself is returned. +On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform. +since 4.08 +``` +val ceil : float -> float +``` +Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. +``` +val floor : float -> float +``` +Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. +``` +val next_after : float -> float -> float +``` +`next_after x y` returns the next representable floating-point value following `x` in the direction of `y`. More precisely, if `y` is greater (resp. less) than `x`, it returns the smallest (resp. largest) representable number greater (resp. less) than `x`. If `x` equals `y`, the function returns `y`. If `x` or `y` is `nan`, a `nan` is returned. Note that `next_after max_float infinity = infinity` and that `next_after 0. infinity` is the smallest denormalized positive number. If `x` is the smallest denormalized positive number, `next_after x 0. = 0.` +since 4.08 +``` +val copy_sign : float -> float -> float +``` +`copy_sign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. +``` +val sign_bit : float -> bool +``` +`sign_bit x` is `true` if and only if the sign bit of `x` is set. For example `sign_bit 1.` and `signbit 0.` are `false` while `sign_bit (-1.)` and `sign_bit (-0.)` are `true`. +since 4.08 +``` +val frexp : float -> float * int +``` +`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. +``` +val ldexp : float -> int -> float +``` +`ldexp x n` returns `x *. 2 ** n`. +``` +val modf : float -> float * float +``` +`modf f` returns the pair of the fractional and integral part of `f`. +``` +type t = float +``` +An alias for the type of floating-point numbers. +``` +val compare : t -> t -> int +``` +`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. +``` +val equal : t -> t -> bool +``` +The equal function for floating-point numbers, compared using [`compare`](./#val-compare). +``` +val min : t -> t -> t +``` +`min x y` returns the minimum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `min (-0.) (+0.) = -0.` +since 4.08 +``` +val max : float -> float -> float +``` +`max x y` returns the maximum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `max (-0.) (+0.) = +0.` +since 4.08 +``` +val min_max : float -> float -> float * float +``` +`min_max x y` is `(min x y, max x y)`, just more efficient. +since 4.08 +``` +val min_num : t -> t -> t +``` +`min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `min_num (-0.) (+0.) = -0.` +since 4.08 +``` +val max_num : t -> t -> t +``` +`max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan` `nan` is returned. Moreover `max_num (-0.) (+0.) = +0.` +since 4.08 +``` +val min_max_num : float -> float -> float * float +``` +`min_max_num x y` is `(min_num x y, max_num x y)`, just more efficient. Note that in particular `min_max_num x nan = (x, x)` and `min_max_num nan y = (y, y)`. +since 4.08 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for floats, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for floats, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +``` +module Array : sig ... end +``` +Float arrays with packed representation. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Format.md b/docs/api/melange/Stdlib-Format.md new file mode 100644 index 000000000..e8596f2ab --- /dev/null +++ b/docs/api/melange/Stdlib-Format.md @@ -0,0 +1,1100 @@ +# Module `Stdlib.Format` +Pretty-printing. +If you are new to this module, see the [examples](./#examples) below. +This module implements a pretty-printing facility to format values within ['pretty-printing boxes'](./#boxes) and ['semantic tags'](./#tags) combined with a set of [printf-like functions](./#fpp). The pretty-printer splits lines at specified [break hints](./#breaks), and indents lines according to the box structure. Similarly, [semantic tags](./#tags) can be used to decouple text presentation from its contents. +This pretty-printing facility is implemented as an overlay on top of abstract [formatters](./#formatter) which provide basic output functions. Some formatters are predefined, notably: +- [`std_formatter`](./#val-std_formatter) outputs to [stdout](./Stdlib.md#val-stdout) +- [`err_formatter`](./#val-err_formatter) outputs to [stderr](./Stdlib.md#val-stderr) +Most functions in the [`Format`](#) module come in two variants: a short version that operates on the current domain's standard formatter as obtained using [`get_std_formatter`](./#val-get_std_formatter) and the generic version prefixed by `pp_` that takes a formatter as its first argument. For the version that operates on the current domain's standard formatter, the call to [`get_std_formatter`](./#val-get_std_formatter) is delayed until the last argument is received. +More formatters can be created with [`formatter_of_out_channel`](./#val-formatter_of_out_channel), [`formatter_of_buffer`](./#val-formatter_of_buffer), [`formatter_of_symbolic_output_buffer`](./#val-formatter_of_symbolic_output_buffer) or using [custom formatters](./#formatter). +**Warning**: Since [formatters](./#formatter) contain mutable state, it is not thread-safe to use the same formatter on multiple domains in parallel without synchronization. +If multiple domains write to the same output channel using the predefined formatters (as obtained by [`get_std_formatter`](./#val-get_std_formatter) or [`get_err_formatter`](./#val-get_err_formatter)), the output from the domains will be interleaved with each other at points where the formatters are flushed, such as with [`print_flush`](./#val-print_flush). This synchronization is not performed by formatters obtained from [`formatter_of_out_channel`](./#val-formatter_of_out_channel) (on the standard out channels or others). +## Introduction +You may consider this module as providing an extension to the `printf` facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular `printf` format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function [`Format.fprintf`](./#val-fprintf). +You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise `fprintf` format strings. +For instance, the sequence `open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()` that prints `x = 1` within a pretty-printing box, can be abbreviated as `printf "@[%s@ %i@]@." "x =" 1`, or even shorter `printf "@[x =@ %i@]@." 1`. +Rule of thumb for casual users of this library: +- use simple pretty-printing boxes (as obtained by `open_box 0`); +- use simple break hints as obtained by `print_cut ()` that outputs a simple break hint, or by `print_space ()` that outputs a space indicating a break hint; +- once a pretty-printing box is open, display its material with basic printing functions (e. g. `print_int` and `print_string`); +- when the material for a pretty-printing box has been printed, call `close_box ()` to close the box; +- at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate `print_newline ()`. +The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the `open_` functions below must be closed using `close_box` for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. +In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer. +Warning: mixing calls to pretty-printing functions of this module with calls to [`Stdlib`](./Stdlib.md) low level output functions is error prone. +The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, ` Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT"; ` leads to output `<>PRETTYTEXT`. +## Formatters +``` +type formatter +``` +Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also [Defining formatters](./#formatter). +## Pretty-printing boxes +The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer. +Each different pretty-printing box kind introduces a specific line splitting policy: +- within an *horizontal* box, break hints never split the line (but the line may be split in a box nested deeper), +- within a *vertical* box, break hints always split the line, +- within an *horizontal/vertical* box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line, +- within a *compacting* box, a break hint never splits the line, unless there is no more room on the current line. +Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line. +Moreover, opening a box after the [maximum indentation limit](./#maxindent) splits the line whether or not the box would end up fitting on the line. +``` +val pp_open_box : formatter -> int -> unit +``` +``` +val open_box : int -> unit +``` +`pp_open_box ppf d` opens a new compacting pretty-printing box with offset `d` in the formatter `ppf`. +Within this box, the pretty-printer prints as much as possible material on every line. +A break hint splits the line if there is no more room on the line to print the remainder of the box. +Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting \``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line). +This box is the general purpose pretty-printing box. +If the pretty-printer splits the line in the box, offset `d` is added to the current indentation. +``` +val pp_close_box : formatter -> unit -> unit +``` +``` +val close_box : unit -> unit +``` +Closes the most recently open pretty-printing box. +``` +val pp_open_hbox : formatter -> unit -> unit +``` +``` +val open_hbox : unit -> unit +``` +`pp_open_hbox ppf ()` opens a new 'horizontal' pretty-printing box. +This box prints material on a single line. +Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper). +``` +val pp_open_vbox : formatter -> int -> unit +``` +``` +val open_vbox : int -> unit +``` +`pp_open_vbox ppf d` opens a new 'vertical' pretty-printing box with offset `d`. +This box prints material on as many lines as break hints in the box. +Every break hint in a vertical box splits the line. +If the pretty-printer splits the line in the box, `d` is added to the current indentation. +``` +val pp_open_hvbox : formatter -> int -> unit +``` +``` +val open_hvbox : int -> unit +``` +`pp_open_hvbox ppf d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`. +This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box. +If the pretty-printer splits the line in the box, `d` is added to the current indentation. +``` +val pp_open_hovbox : formatter -> int -> unit +``` +``` +val open_hovbox : int -> unit +``` +`pp_open_hovbox ppf d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`. +This box prints material as much as possible on every line. +A break hint splits the line if there is no more room on the line to print the remainder of the box. +If the pretty-printer splits the line in the box, `d` is added to the current indentation. +## Formatting functions +``` +val pp_print_string : formatter -> string -> unit +``` +``` +val print_string : string -> unit +``` +`pp_print_string ppf s` prints `s` in the current pretty-printing box. +``` +val pp_print_substring : pos:int -> len:int -> formatter -> string -> unit +``` +``` +val print_substring : pos:int -> len:int -> string -> unit +``` +`pp_print_substring ~pos ~len ppf s` prints the substring of `s` that starts at position `pos` and stops at position `pos+len` in the current pretty-printing box. +since 5.3 +``` +val pp_print_bytes : formatter -> bytes -> unit +``` +``` +val print_bytes : bytes -> unit +``` +`pp_print_bytes ppf b` prints `b` in the current pretty-printing box. +since 4.13 +``` +val pp_print_as : formatter -> int -> string -> unit +``` +``` +val print_as : int -> string -> unit +``` +`pp_print_as ppf len s` prints `s` in the current pretty-printing box. The pretty-printer formats `s` as if it were of length `len`. +``` +val pp_print_substring_as : + pos:int -> + len:int -> + formatter -> + int -> + string -> + unit +``` +``` +val print_substring_as : pos:int -> len:int -> int -> string -> unit +``` +`pp_print_substring_as ~first ~len ppf len_as s` prints the substring of `s` that starts at position `pos` and stop at position `pos+len` in the current pretty-printing box as if it were of length `len_as`. +since 5.1 +``` +val pp_print_int : formatter -> int -> unit +``` +``` +val print_int : int -> unit +``` +Print an integer in the current pretty-printing box. +``` +val pp_print_float : formatter -> float -> unit +``` +``` +val print_float : float -> unit +``` +Print a floating point number in the current pretty-printing box. +``` +val pp_print_char : formatter -> char -> unit +``` +``` +val print_char : char -> unit +``` +Print a character in the current pretty-printing box. +``` +val pp_print_bool : formatter -> bool -> unit +``` +``` +val print_bool : bool -> unit +``` +Print a boolean in the current pretty-printing box. +``` +val pp_print_nothing : formatter -> unit -> unit +``` +Print nothing. +since 5.2 +## Break hints +A 'break hint' tells the pretty-printer to output some space or split the line whichever way is more appropriate to the current pretty-printing box splitting rules. +Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items. +Simple break hints are: +- the 'space': output a space or split the line if appropriate, +- the 'cut': split the line if appropriate. +Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, \``output a space'' simply means printing a space character (ASCII code 32) and \``split the line'' means printing a newline character (ASCII code 10). +``` +val pp_print_space : formatter -> unit -> unit +``` +``` +val print_space : unit -> unit +``` +`pp_print_space ppf ()` emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space. +`pp_print_space ppf ()` is equivalent to `pp_print_break ppf 1 0`. +``` +val pp_print_cut : formatter -> unit -> unit +``` +``` +val print_cut : unit -> unit +``` +`pp_print_cut ppf ()` emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing. +`pp_print_cut ppf ()` is equivalent to `pp_print_break ppf 0 0`. +``` +val pp_print_break : formatter -> int -> int -> unit +``` +``` +val print_break : int -> int -> unit +``` +`pp_print_break ppf nspaces offset` emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints `nspaces` spaces. +If the pretty-printer splits the line, `offset` is added to the current indentation. +``` +val pp_print_custom_break : + formatter -> + fits:(string * int * string) -> + breaks:(string * int * string) -> + unit +``` +`pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4)` emits a custom break hint: the pretty-printer may split the line at this point. +If it does not split the line, then the `s1` is emitted, then `n` spaces, then `s2`. +If it splits the line, then it emits the `s3` string, then an indent (according to the box rules), then an offset of `m` spaces, then the `s4` string. +While `n` and `m` are handled by `formatter_out_functions.out_indent`, the strings will be handled by `formatter_out_functions.out_string`. This allows for a custom formatter that handles indentation distinctly, for example, outputs `
` tags or ` ` entities. +The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list ` [a; b; c] `, you might want to add a trailing semicolon when it is printed vertically: +```ocaml +[ + a; + b; + c; +] +``` +You can do this as follows: +```ocaml +printf "@[[@;<0 2>@[a;@,b;@,c@]%t]@]@\n" + (pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, "")) +``` +since 4.08 +``` +val pp_force_newline : formatter -> unit -> unit +``` +``` +val force_newline : unit -> unit +``` +Force a new line in the current pretty-printing box. +The pretty-printer must split the line at this point, +Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative. +``` +val pp_print_if_newline : formatter -> unit -> unit +``` +``` +val print_if_newline : unit -> unit +``` +Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. +## Pretty-printing termination +``` +val pp_print_flush : formatter -> unit -> unit +``` +``` +val print_flush : unit -> unit +``` +End of pretty-printing: resets the pretty-printer to initial state. +All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed. +Note: never use `print_flush` in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering. +Only consider using `print_flush` when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing. +Warning: If the output device of the pretty-printer is an output channel, repeated calls to `print_flush` means repeated calls to [`Stdlib.flush`](./Stdlib.md#val-flush) to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency. +``` +val pp_print_newline : formatter -> unit -> unit +``` +``` +val print_newline : unit -> unit +``` +End of pretty-printing: resets the pretty-printer to initial state. +All open pretty-printing boxes are closed, all pending text is printed. +Equivalent to [`print_flush`](./#val-print_flush) with a new line emitted on the pretty-printer low-level output device immediately before the device is flushed. See corresponding words of caution for [`print_flush`](./#val-print_flush). +Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box. +## Margin +``` +val pp_infinity : int +``` +`pp_infinity` is the maximal size of the margin. Its exact value is implementation dependent but is guaranteed to be greater than 109. +since 5.2 +``` +val pp_set_margin : formatter -> int -> unit +``` +``` +val set_margin : int -> unit +``` +`pp_set_margin ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to `d` means that the formatting engine aims at printing at most `d-1` characters per line. Nothing happens if `d` is smaller than 2. If `d >= `[`pp_infinity`](./#val-pp_infinity), the right margin is set to [`pp_infinity`](./#val-pp_infinity)` - 1`. If `d` is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio `max_indent/margin>=50%` and if possible the current difference `margin - max_indent`. +See also [`pp_set_geometry`](./#val-pp_set_geometry). +``` +val pp_get_margin : formatter -> unit -> int +``` +``` +val get_margin : unit -> int +``` +Returns the position of the right margin. +## Maximum indentation limit +``` +val pp_set_max_indent : formatter -> int -> unit +``` +``` +val set_max_indent : int -> unit +``` +`pp_set_max_indent ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration, +```ocaml + set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." +``` +yields +```ocaml + 123456 + 789A +``` +because the nested box `"@[7@]"` is opened after the maximum indentation limit (`7>5`) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line: +```ocaml + printf "@[123456@[7@]89@]@." +``` +or opening an intermediary box before the maximum indentation limit which fits on the current line +```ocaml + printf "@[123@[456@[7@]89@]A@]@." +``` +avoids the rejection to the left of the inner boxes and print respectively `"123456789"` and `"123456789A"` . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to `margin - 1`. Note that setting the maximum indentation limit to `margin` is invalid. +Nothing happens if `d` is smaller than 2. +If `d` is greater than the current margin, it is ignored, and the current maximum indentation limit is kept. +See also [`pp_set_geometry`](./#val-pp_set_geometry). +``` +val pp_get_max_indent : formatter -> unit -> int +``` +``` +val get_max_indent : unit -> int +``` +Return the maximum indentation limit (in characters). +## Geometry +Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maximum indentation limit. +``` +type geometry = { +``` +`max_indent : int;` +`margin : int;` +``` +} +``` +since 4.08 +``` +val check_geometry : geometry -> bool +``` +Check if the formatter geometry is valid: `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity) +since 4.08 +``` +val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit +``` +``` +val set_geometry : max_indent:int -> margin:int -> unit +``` +``` +val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit +``` +``` +val safe_set_geometry : max_indent:int -> margin:int -> unit +``` +`pp_set_geometry ppf ~max_indent ~margin` sets both the margin and maximum indentation limit for `ppf`. +When `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity), `pp_set_geometry ppf ~max_indent ~margin` is equivalent to `pp_set_margin ppf margin; pp_set_max_indent ppf max_indent`; and avoids the subtly incorrect `pp_set_max_indent ppf max_indent; pp_set_margin ppf margin`; +Outside of this domain, `pp_set_geometry` raises an invalid argument exception whereas `pp_safe_set_geometry` does nothing. +since 4.08 +``` +val pp_update_geometry : formatter -> (geometry -> geometry) -> unit +``` +`pp_update_geometry ppf (fun geo -> { geo with ... })` lets you update a formatter's geometry in a way that is robust to extension of the `geometry` record with new fields. +Raises an invalid argument exception if the returned geometry does not satisfy [`check_geometry`](./#val-check_geometry). +since 4.11 +``` +val update_geometry : (geometry -> geometry) -> unit +``` +``` +val pp_get_geometry : formatter -> unit -> geometry +``` +``` +val get_geometry : unit -> geometry +``` +Return the current geometry of the formatter +since 4.08 +## Maximum formatting depth +The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open. +Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). +``` +val pp_set_max_boxes : formatter -> int -> unit +``` +``` +val set_max_boxes : int -> unit +``` +`pp_set_max_boxes ppf max` sets the maximum number of pretty-printing boxes simultaneously open. +Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). +Nothing happens if `max` is smaller than 2. +``` +val pp_get_max_boxes : formatter -> unit -> int +``` +``` +val get_max_boxes : unit -> int +``` +Returns the maximum number of pretty-printing boxes allowed before ellipsis. +``` +val pp_over_max_boxes : formatter -> unit -> bool +``` +``` +val over_max_boxes : unit -> bool +``` +Tests if the maximum number of pretty-printing boxes allowed have already been opened. +## Tabulation boxes +A *tabulation box* prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text. +This box features command `set_tab` to define cell boundaries, and command `print_tab` to move from cell to cell and split the line when there is no more cells to print on the line. +Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module [`Format`](#). +``` +val pp_open_tbox : formatter -> unit -> unit +``` +``` +val open_tbox : unit -> unit +``` +`open_tbox ()` opens a new tabulation box. +This box prints lines separated into cells of fixed width. +Inside a tabulation box, special *tabulation markers* defines points of interest on the line (for instance to delimit cell boundaries). Function [`Format.set_tab`](./#val-set_tab) sets a tabulation marker at insertion point. +A tabulation box features specific *tabulation breaks* to move to next tabulation marker or split the line. Function [`Format.print_tbreak`](./#val-print_tbreak) prints a tabulation break. +``` +val pp_close_tbox : formatter -> unit -> unit +``` +``` +val close_tbox : unit -> unit +``` +Closes the most recently opened tabulation box. +``` +val pp_set_tab : formatter -> unit -> unit +``` +``` +val set_tab : unit -> unit +``` +Sets a tabulation marker at current insertion point. +``` +val pp_print_tab : formatter -> unit -> unit +``` +``` +val print_tab : unit -> unit +``` +`print_tab ()` emits a 'next' tabulation break hint: if not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. +It is equivalent to `print_tbreak 0 0`. +``` +val pp_print_tbreak : formatter -> int -> int -> unit +``` +``` +val print_tbreak : int -> int -> unit +``` +`print_tbreak nspaces offset` emits a 'full' tabulation break hint. +If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints `nspaces` spaces. +If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box. +If the pretty-printer splits the line, `offset` is added to the current indentation. +## Ellipsis +``` +val pp_set_ellipsis_text : formatter -> string -> unit +``` +``` +val set_ellipsis_text : string -> unit +``` +Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, `.`, by default). +``` +val pp_get_ellipsis_text : formatter -> unit -> string +``` +``` +val get_ellipsis_text : unit -> string +``` +Return the text of the ellipsis. +## Semantic tags +``` +type stag = .. +``` +*Semantic tags* (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities. +Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so: +```ocaml +type stag += RGB of {r:int;g:int;b:int} +``` +In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using [`pp_open_stag`](./#val-pp_open_stag) and [`pp_close_stag`](./#val-pp_close_stag). +Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed *tag-marking* and *tag-printing*: +- The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation. +- The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations. +Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output). +More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur: +- Tag-printing a semantic tag means calling the formatter specific function `print_open_stag` (resp. `print_close_stag`) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation). +- Tag-marking a semantic tag means calling the formatter specific function `mark_open_stag` (resp. `mark_close_stag`) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. \`tag-closing marker') for direct output into the output device of the formatter. +Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting). +Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once `set_tags` is set to `true`, the pretty-printer engine honors tags and decorates the output accordingly. +Default tag-marking functions behave the HTML way: [string tags](./#type-tag) are enclosed in "\<" and "\>" while other tags are ignored; hence, opening marker for tag string `"t"` is `""` and closing marker is `""`. +Default tag-printing functions just do nothing. +Tag-marking and tag-printing functions are user definable and can be set by calling [`set_formatter_stag_functions`](./#val-set_formatter_stag_functions). +Semantic tag operations may be set on or off with [`set_tags`](./#val-set_tags). Tag-marking operations may be set on or off with [`set_mark_tags`](./#val-set_mark_tags). Tag-printing operations may be set on or off with [`set_print_tags`](./#val-set_print_tags). +since 4.08 +``` +type tag = string +``` +``` +type stag += +``` +``` +| String_tag of tag +``` +`String_tag s` is a string tag `s`. String tags can be inserted either by explicitly using the constructor `String_tag` or by using the dedicated format syntax `"@{ ... @}"`. +since 4.08 +``` + +``` +``` +val pp_open_stag : formatter -> stag -> unit +``` +``` +val open_stag : stag -> unit +``` +`pp_open_stag ppf t` opens the semantic tag named `t`. +The `print_open_stag` tag-printing function of the formatter is called with `t` as argument; then the opening tag marker for `t`, as given by `mark_open_stag t`, is written into the output device of the formatter. +since 4.08 +``` +val pp_close_stag : formatter -> unit -> unit +``` +``` +val close_stag : unit -> unit +``` +`pp_close_stag ppf ()` closes the most recently opened semantic tag `t`. +The closing tag marker, as given by `mark_close_stag t`, is written into the output device of the formatter; then the `print_close_stag` tag-printing function of the formatter is called with `t` as argument. +since 4.08 +``` +val pp_set_tags : formatter -> bool -> unit +``` +``` +val set_tags : bool -> unit +``` +`pp_set_tags ppf b` turns on or off the treatment of semantic tags (default is off). +``` +val pp_set_print_tags : formatter -> bool -> unit +``` +``` +val set_print_tags : bool -> unit +``` +`pp_set_print_tags ppf b` turns on or off the tag-printing operations. +``` +val pp_set_mark_tags : formatter -> bool -> unit +``` +``` +val set_mark_tags : bool -> unit +``` +`pp_set_mark_tags ppf b` turns on or off the tag-marking operations. +``` +val pp_get_print_tags : formatter -> unit -> bool +``` +``` +val get_print_tags : unit -> bool +``` +Return the current status of tag-printing operations. +``` +val pp_get_mark_tags : formatter -> unit -> bool +``` +``` +val get_mark_tags : unit -> bool +``` +Return the current status of tag-marking operations. +``` +val pp_set_formatter_out_channel : formatter -> out_channel -> unit +``` +Redirecting the standard formatter output +``` +val set_formatter_out_channel : out_channel -> unit +``` +Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.) +`set_formatter_out_channel` is equivalent to [`pp_set_formatter_out_channel`](./#val-pp_set_formatter_out_channel) `std_formatter`. +``` +val pp_set_formatter_output_functions : + formatter -> + (string -> int -> int -> unit) -> + (unit -> unit) -> + unit +``` +``` +val set_formatter_output_functions : + (string -> int -> int -> unit) -> + (unit -> unit) -> + unit +``` +`pp_set_formatter_output_functions ppf out flush` redirects the standard pretty-printer output functions to the functions `out` and `flush`. +The `out` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. +The `flush` function is called whenever the pretty-printer is flushed (via conversion `%!`, or pretty-printing indications `@?` or `@.`, or using low level functions `print_flush` or `print_newline`). +``` +val pp_get_formatter_output_functions : + formatter -> + unit -> + (string -> int -> int -> unit) * (unit -> unit) +``` +``` +val get_formatter_output_functions : + unit -> + (string -> int -> int -> unit) * (unit -> unit) +``` +Return the current output functions of the standard pretty-printer. +## Redefining formatter output +The `Format` module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed\! +### Redefining output functions +``` +type formatter_out_functions = { +``` +`out_string : string -> int -> int -> unit;` +`out_flush : unit -> unit;` +`out_newline : unit -> unit;` +`out_spaces : int -> unit;` +`out_indent : int -> unit;` +since 4.06 +``` +} +``` +The set of output functions specific to a formatter: +- the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. +- the `out_flush` function flushes the pretty-printer output device. +- `out_newline` is called to open a new line when the pretty-printer splits the line. +- the `out_spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output. +- the `out_indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. +By default: +- fields `out_string` and `out_flush` are output device specific; (e.g. [`Stdlib.output_string`](./Stdlib.md#val-output_string) and [`Stdlib.flush`](./Stdlib.md#val-flush) for a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) device, or `Buffer.add_substring` and [`Stdlib.ignore`](./Stdlib.md#val-ignore) for a `Buffer.t` output device), +- field `out_newline` is equivalent to `out_string "\n" 0 1`; +- fields `out_spaces` and `out_indent` are equivalent to `out_string (String.make n ' ') 0 n`. +since 4.01 +``` +val pp_set_formatter_out_functions : + formatter -> + formatter_out_functions -> + unit +``` +``` +val set_formatter_out_functions : formatter_out_functions -> unit +``` +`pp_set_formatter_out_functions ppf out_funs` Set all the pretty-printer output functions of `ppf` to those of argument `out_funs`, +This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand). +Reasonable defaults for functions `out_spaces` and `out_newline` are respectively `out_funs.out_string (String.make n ' ') 0 n` and `out_funs.out_string "\n" 0 1`. +since 4.01 +``` +val pp_get_formatter_out_functions : + formatter -> + unit -> + formatter_out_functions +``` +``` +val get_formatter_out_functions : unit -> formatter_out_functions +``` +Return the current output functions of the pretty-printer, including line splitting and indentation functions. Useful to record the current setting and restore it afterwards. +since 4.01 +## Redefining semantic tag operations +``` +type formatter_stag_functions = { +``` +`mark_open_stag : stag -> string;` +`mark_close_stag : stag -> string;` +`print_open_stag : stag -> unit;` +`print_close_stag : stag -> unit;` +``` +} +``` +The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. `print` versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened. +since 4.08 +``` +val pp_set_formatter_stag_functions : + formatter -> + formatter_stag_functions -> + unit +``` +``` +val set_formatter_stag_functions : formatter_stag_functions -> unit +``` +`pp_set_formatter_stag_functions ppf tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`. +When opening a semantic tag with name `t`, the string `t` is passed to the opening tag-marking function (the `mark_open_stag` field of the record `tag_funs`), that must return the opening tag marker for that name. When the next call to `close_stag ()` happens, the semantic tag name `t` is sent back to the closing tag-marking function (the `mark_close_stag` field of record `tag_funs`), that must return a closing tag marker for that name. +The `print_` field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue. +since 4.08 +``` +val pp_get_formatter_stag_functions : + formatter -> + unit -> + formatter_stag_functions +``` +``` +val get_formatter_stag_functions : unit -> formatter_stag_functions +``` +Return the current semantic tag operation functions of the standard pretty-printer. +since 4.08 +## Defining formatters +Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently. +For instance, given a [`Buffer.t`](./Stdlib-Buffer.md#type-t) buffer `b`, [`formatter_of_buffer`](./#val-formatter_of_buffer) `b` returns a new formatter using buffer `b` as its output device. Similarly, given a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) output channel `oc`, [`formatter_of_out_channel`](./#val-formatter_of_out_channel) `oc` returns a new formatter using channel `oc` as its output device. +Alternatively, given `out_funs`, a complete set of output functions for a formatter, then [`formatter_of_out_functions`](./#val-formatter_of_out_functions) `out_funs` computes a new formatter using those functions for output. +``` +val formatter_of_out_channel : out_channel -> formatter +``` +`formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`. +``` +val synchronized_formatter_of_out_channel : + out_channel -> + formatter Domain.DLS.key +``` +`synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`. +When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). +alert unstable +``` +val std_formatter : formatter +``` +The initial domain's standard formatter to write to standard output. +It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stdout`](./Stdlib.md#val-stdout). +``` +val get_std_formatter : unit -> formatter +``` +`get_std_formatter ()` returns the current domain's standard formatter used to write to standard output. +since 5.0 +``` +val err_formatter : formatter +``` +The initial domain's formatter to write to standard error. +It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stderr`](./Stdlib.md#val-stderr). +``` +val get_err_formatter : unit -> formatter +``` +`get_err_formatter ()` returns the current domain's formatter used to write to standard error. +since 5.0 +``` +val formatter_of_buffer : Buffer.t -> formatter +``` +`formatter_of_buffer b` returns a new formatter writing to buffer `b`. At the end of pretty-printing, the formatter must be flushed using [`pp_print_flush`](./#val-pp_print_flush) or [`pp_print_newline`](./#val-pp_print_newline), to print all the pending material into the buffer. +``` +val stdbuf : Buffer.t +``` +The initial domain's string buffer in which `str_formatter` writes. +``` +val get_stdbuf : unit -> Buffer.t +``` +`get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes. +since 5.0 +``` +val str_formatter : formatter +``` +The initial domain's formatter to output to the [`stdbuf`](./#val-stdbuf) string buffer. +`str_formatter` is defined as [`formatter_of_buffer`](./#val-formatter_of_buffer) [`stdbuf`](./#val-stdbuf). +``` +val get_str_formatter : unit -> formatter +``` +The current domain's formatter to output to the current domains string buffer. +since 5.0 +``` +val flush_str_formatter : unit -> string +``` +Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer. +``` +val make_formatter : + (string -> int -> int -> unit) -> + (unit -> unit) -> + formatter +``` +`make_formatter out flush` returns a new formatter that outputs with function `out`, and flushes with function `flush`. +For instance, +```ocaml + make_formatter + (Stdlib.output_substring oc) + (fun () -> Stdlib.flush oc) +``` +returns a formatter to the [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) `oc`. +``` +val make_synchronized_formatter : + (string -> int -> int -> unit) -> + (unit -> unit) -> + formatter Domain.DLS.key +``` +`make_synchronized_formatter out flush` returns the key to the domain-local state that holds the domain-local formatter that outputs with function `out`, and flushes with function `flush`. +When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). +since 5.0 +alert unstable +``` +val formatter_of_out_functions : formatter_out_functions -> formatter +``` +`formatter_of_out_functions out_funs` returns a new formatter that writes with the set of output functions `out_funs`. +See definition of type [`formatter_out_functions`](./#type-formatter_out_functions) for the meaning of argument `out_funs`. +since 4.06 +### Symbolic pretty-printing +Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items. +When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations. +In practice, first define a symbolic output buffer `b` using: +- `let sob = make_symbolic_output_buffer ()`. Then define a symbolic formatter with: +- `let ppf = formatter_of_symbolic_output_buffer sob` +Use symbolic formatter `ppf` as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer `sob` with: +- `flush_symbolic_output_buffer sob`. +``` +type symbolic_output_item = +``` +``` +| Output_flush +``` +symbolic flush command +``` +| Output_newline +``` +symbolic newline command +``` +| Output_string of string +``` +`Output_string s`: symbolic output for string `s` +``` +| Output_spaces of int +``` +`Output_spaces n`: symbolic command to output `n` spaces +``` +| Output_indent of int +``` +`Output_indent i`: symbolic indentation of size `i` +``` + +``` +Items produced by symbolic pretty-printers +since 4.06 +``` +type symbolic_output_buffer +``` +The output buffer of a symbolic pretty-printer. +since 4.06 +``` +val make_symbolic_output_buffer : unit -> symbolic_output_buffer +``` +`make_symbolic_output_buffer ()` returns a fresh buffer for symbolic output. +since 4.06 +``` +val clear_symbolic_output_buffer : symbolic_output_buffer -> unit +``` +`clear_symbolic_output_buffer sob` resets buffer `sob`. +since 4.06 +``` +val get_symbolic_output_buffer : + symbolic_output_buffer -> + symbolic_output_item list +``` +`get_symbolic_output_buffer sob` returns the contents of buffer `sob`. +since 4.06 +``` +val flush_symbolic_output_buffer : + symbolic_output_buffer -> + symbolic_output_item list +``` +`flush_symbolic_output_buffer sob` returns the contents of buffer `sob` and resets buffer `sob`. `flush_symbolic_output_buffer sob` is equivalent to `let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items` +since 4.06 +``` +val add_symbolic_output_item : + symbolic_output_buffer -> + symbolic_output_item -> + unit +``` +`add_symbolic_output_item sob itm` adds item `itm` to buffer `sob`. +since 4.06 +``` +val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter +``` +`formatter_of_symbolic_output_buffer sob` returns a symbolic formatter that outputs to `symbolic_output_buffer` `sob`. +since 4.06 +## Convenience formatting functions. +``` +val pp_print_iter : + ?pp_sep:(formatter -> unit -> unit) -> + (('a -> unit) -> 'b -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'b -> + unit +``` +`pp_print_iter ~pp_sep iter pp_v ppf v` formats on `ppf` the iterations of `iter` over a collection `v` of values using `pp_v`. Iterations are separated by `pp_sep` (defaults to [`pp_print_cut`](./#val-pp_print_cut)). +since 5.1 +``` +val pp_print_list : + ?pp_sep:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a list -> + unit +``` +`pp_print_list ?pp_sep pp_v ppf l` prints items of list `l`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty lists. +since 4.02 +``` +val pp_print_array : + ?pp_sep:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a array -> + unit +``` +`pp_print_array ?pp_sep pp_v ppf a` prints items of array `a`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty arrays. +If `a` is mutated after `pp_print_array` is called, the printed values may not be what is expected because `Format` can delay the printing. This can be avoided by flushing `ppf`. +since 5.1 +``` +val pp_print_seq : + ?pp_sep:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a Seq.t -> + unit +``` +`pp_print_seq ?pp_sep pp_v ppf s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut). Does nothing on empty sequences. +This function does not terminate on infinite sequences. +since 4.12 +``` +val pp_print_text : formatter -> string -> unit +``` +`pp_print_text ppf s` prints `s` with spaces and newlines respectively printed using [`pp_print_space`](./#val-pp_print_space) and [`pp_force_newline`](./#val-pp_force_newline). +since 4.02 +``` +val pp_print_option : + ?none:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a option -> + unit +``` +`pp_print_option ?none pp_v ppf o` prints `o` on `ppf` using `pp_v` if `o` is `Some v` and `none` if it is `None`. `none` prints nothing by default. +since 4.08 +``` +val pp_print_result : + ok:(formatter -> 'a -> unit) -> + error:(formatter -> 'e -> unit) -> + formatter -> + ('a, 'e) result -> + unit +``` +`pp_print_result ~ok ~error ppf r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`. +since 4.08 +``` +val pp_print_either : + left:(formatter -> 'a -> unit) -> + right:(formatter -> 'b -> unit) -> + formatter -> + ('a, 'b) Either.t -> + unit +``` +`pp_print_either ~left ~right ppf e` prints `e` on `ppf` using `left` if `e` is `Either.Left _` and `right` if `e` is `Either.Right _`. +since 4.13 +## Formatted pretty-printing +Module `Format` provides a complete set of `printf` like functions for pretty-printing using format string specifications. +Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine. +Those annotations are introduced in the format strings using the `@` character. For instance, `@ ` means a space break, `@,` means a cut, `@[` opens a new box, and `@]` closes the last open box. +``` +val fprintf : formatter -> ('a, formatter, unit) format -> 'a +``` +`fprintf ff fmt arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `fmt`, and outputs the resulting string on the formatter `ff`. +The format string `fmt` is a character string which contains three types of objects: plain characters and conversion specifications as specified in the [`Printf`](./Stdlib-Printf.md) module, and pretty-printing indications specific to the `Format` module. +The pretty-printing indication characters are introduced by a `@` character, and their meanings are: +- `@[`: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the `<` character, followed by an optional box type indication, then an optional integer offset, and the closing `>` character. Pretty-printing box type is one of `h`, `v`, `hv`, `b`, or `hov`. '`h`' stands for an 'horizontal' pretty-printing box, '`v`' stands for a 'vertical' pretty-printing box, '`hv`' stands for an 'horizontal/vertical' pretty-printing box, '`b`' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '`hov`' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, `@[` opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with `open_hovbox 2`. For more details about pretty-printing boxes, see the various box opening functions `open_*box`. +- `@]`: close the most recently opened pretty-printing box. +- `@,`: output a 'cut' break hint, as with `print_cut ()`. +- `@ `: output a 'space' break hint, as with `print_space ()`. +- `@;`: output a 'full' break hint as with `print_break`. The `nspaces` and `offset` parameters of the break hint may be optionally specified with the following syntax: the `<` character, followed by an integer `nspaces` value, then an integer `offset`, and a closing `>` character. If no parameters are provided, the full break defaults to a 'space' break hint. +- `@.`: flush the pretty-printer and split the line, as with `print_newline ()`. +- `@`: print the following item as if it were of length `n`. Hence, `printf "@<0>%s" arg` prints `arg` as a zero length string. If `@` is not followed by a conversion specification, then the following character of the format is printed as if it were of length `n`. +- `@\{`: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the `<` character, followed by an optional string specification, and the closing `>` character. The string specification is any character string that does not contain the closing character `'>'`. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions [`open_stag`](./#val-open_stag) and [`close_stag`](./#val-close_stag). +- `@\}`: close the most recently opened semantic tag. +- `@?`: flush the pretty-printer as with `print_flush ()`. This is equivalent to the conversion `%!`. +- `@\n`: force a newline, as with `force_newline ()`, not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box. +Note: To prevent the interpretation of a `@` character as a pretty-printing indication, escape it with a `%` character. Old quotation mode `@@` is deprecated since it is not compatible with formatted input interpretation of character `'@'`. +Example: `printf "@[%s@ %d@]@." "x =" 1` is equivalent to `open_box (); print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()`. It prints `x = 1` within a pretty-printing 'horizontal-or-vertical' box. +``` +val printf : ('a, formatter, unit) format -> 'a +``` +Same as `fprintf` above, but output on `get_std_formatter ()`. +It is defined similarly to `fun fmt -> fprintf (get_std_formatter ()) fmt` but delays calling `get_std_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). +``` +val eprintf : ('a, formatter, unit) format -> 'a +``` +Same as `fprintf` above, but output on `get_err_formatter ()`. +It is defined similarly to `fun fmt -> fprintf (get_err_formatter ()) fmt` but delays calling `get_err_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). +``` +val sprintf : ('a, unit, string) format -> 'a +``` +Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of *each call* to `sprintf`. Note that if your format string contains a `%a`, you should use `asprintf`. +In case of multiple and related calls to `sprintf` to output material on a single string, you should consider using `fprintf` with the predefined formatter `str_formatter` and call `flush_str_formatter ()` to get the final result. +Alternatively, you can use `Format.fprintf` with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string. +``` +val asprintf : ('a, formatter, unit, string) format4 -> 'a +``` +Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. The type of `asprintf` is general enough to interact nicely with `%a` conversions. +since 4.01 +``` +val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a +``` +Same as [`fprintf`](./#val-fprintf), except the formatter is the last argument. `dprintf "..." a b c` is a function of type `formatter -> unit` which can be given to a format specifier `%t`. +This can be used as a replacement for [`asprintf`](./#val-asprintf) to delay formatting decisions. Using the string returned by [`asprintf`](./#val-asprintf) in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. [`dprintf`](./#val-dprintf) allows delay of formatting decisions until the final formatting context is known. For example: +```ocaml + let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in + ... + Format.printf "@[%t@]" t +``` +since 4.08 +``` +val ifprintf : formatter -> ('a, formatter, unit) format -> 'a +``` +Same as `fprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. +since 3.10 +Formatted Pretty-Printing with continuations. +``` +val kfprintf : + (formatter -> 'a) -> + formatter -> + ('b, formatter, unit, 'a) format4 -> + 'b +``` +Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing. +``` +val kdprintf : + ((formatter -> unit) -> 'a) -> + ('b, formatter, unit, 'a) format4 -> + 'b +``` +Same as [`dprintf`](./#val-dprintf) above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing. +since 4.08 +``` +val ikfprintf : + (formatter -> 'a) -> + formatter -> + ('b, formatter, unit, 'a) format4 -> + 'b +``` +Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. +since 3.12 +``` +val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b +``` +Same as `sprintf` above, but instead of returning the string, passes it to the first argument. +``` +val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b +``` +Same as `asprintf` above, but instead of returning the string, passes it to the first argument. +since 4.03 +## Examples +A few warmup examples to get an idea of how Format is used. +We have a list `l` of pairs `(int * bool)`, which the toplevel prints for us: +```ocaml +# let l = List.init 20 (fun n -> n, n mod 2 = 0) +val l : (int * bool) list = +[(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); + (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); + (12, true); (13, false); (14, true); (15, false); (16, true); (17, false); + (18, true); (19, false)] +``` +If we want to print it ourself without the toplevel magic, we can try this: +```ocaml +# let pp_pair out (x,y) = Format.fprintf out "(%d, %b)" x y +val pp_pair : Format.formatter -> int * bool -> unit = +# Format.printf "l: [@[%a@]]@." + Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out ";@ ") pp_pair) l + l: [(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); + (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); + (12, true); (13, false); (14, true); (15, false); (16, true); + (17, false); (18, true); (19, false)] + +``` +What this does, briefly, is: +- `pp_pair` prints a pair `bool*int` surrounded in "(" ")". It takes a formatter (into which formatting happens), and the pair itself. When printing is done it returns `()`. +- `Format.printf "l = [@[%a@]]@." ... l` is like `printf`, but with additional formatting instructions (denoted with "@"). The pair "`@[`" and "`@]`" is a "horizontal-or-vertical box". +- "@." ends formatting with a newline. It is similar to "\\n" but is also aware of the `Format.formatter`'s state. Do not use "\\n" with `Format`. +- "%a" is a formatting instruction, like "%d" or "%s" for `printf`. However, where "%d" prints an integer and "%s" prints a string, "%a" takes a printer (of type `Format.formatter -> 'a -> unit`) and a value (of type `'a`) and applies the printer to the value. This is key to compositionality of printers. +- We build a list printer using `Format.pp_print_list ~pp_sep:(...) pp_pair`. `pp_print_list` takes an element printer and returns a list printer. The `?pp_sep` optional argument, if provided, is called in between each element to print a separator. +- Here, for a separator, we use `(fun out () -> Format.fprintf out ";@ ")`. It prints ";", and then "@ " which is a breaking space (either it prints " ", or it prints a newline if the box is about to overflow). This "@ " is responsible for the list printing splitting into several lines. +If we omit "@ ", we get an ugly single-line print: +```ocaml + # Format.printf "l: [@[%a@]]@." + Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out "; ") pp_pair) l + l: [(0, true); (1, false); (2, true); (* ... *); (18, true); (19, false)] +- : unit = () +``` +Generally, it is good practice to define custom printers for important types in your program. If, for example, you were to define basic geometry types like so: +```ocaml +type point = { + x: float; + y: float; +} + +type rectangle = { + ll: point; (* lower left *) + ur: point; (* upper right *) +} +``` +For debugging purpose, or to display information in logs, or on the console, it would be convenient to define printers for these types. Here is an example of to do it. Note that "%.3f" is a `float` printer up to 3 digits of precision after the dot; "%f" would print as many digits as required, which is somewhat verbose; "%h" is an hexadecimal float printer. +```ocaml +let pp_point out (p:point) = + Format.fprintf out "{ @[x=%.3f;@ y=%.3f@] }" p.x p.y + +let pp_rectangle out (r:rectangle) = + Format.fprintf out "{ @[ll=%a;@ ur=%a@] }" + pp_point r.ll pp_point r.ur +``` +In the `.mli` file, we could have: +```ocaml + val pp_point : Format.formatter -> point -> unit + + val pp_rectangle : Format.formatter -> rectangle -> unit +``` +These printers can now be used with "%a" inside other printers. +```ocaml + # Format.printf "some rectangle: %a@." + (Format.pp_print_option pp_rectangle) + (Some {ll={x=1.; y=2.}; ur={x=42.; y=500.12345}}) +some rectangle: { l={ x=1.000; y=2.000 }; ur={ x=42.000; y=500.123 } } + +# Format.printf "no rectangle: %a@." + (Format.pp_option pp_rectangle) + None +no rectangle: +``` +See how we combine `pp_print_option` (option printer) and our newly defined rectangle printer, like we did with `pp_print_list` earlier. +For a more extensive tutorial, see ["Using the Format module"](https://caml.inria.fr/resources/doc/guides/format.en.html). +A final note: the `Format` module is a starting point. The OCaml ecosystem has libraries that makes formatting easier and more expressive, with more combinators, more concise names, etc. An example of such a library is [Fmt](https://erratique.ch/software/fmt). +Automatic deriving of pretty-printers from type definitions is also possible, using [https://github.com/ocaml-ppx/ppx\_deriving](ppx_deriving.show) or similar ppx derivers. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Fun.md b/docs/api/melange/Stdlib-Fun.md new file mode 100644 index 000000000..e8ecb4be4 --- /dev/null +++ b/docs/api/melange/Stdlib-Fun.md @@ -0,0 +1,36 @@ +# Module `Stdlib.Fun` +Function manipulation. +since 4.08 +## Combinators +``` +val id : 'a -> 'a +``` +`id` is the identity function. For any argument `x`, `id x` is `x`. +``` +val const : 'a -> _ -> 'a +``` +`const c` is a function that always returns the value `c`. For any argument `x`, `(const c) x` is `c`. +``` +val compose : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c +``` +`compose f g` is a function composition of applying `g` then `f`. For any arguments `f`, `g`, and `x`, `compose f g x` is `f (g x)`. +since 5.2 +``` +val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c +``` +`flip f` reverses the argument order of the binary function `f`. For any arguments `x` and `y`, `(flip f) x y` is `f y x`. +``` +val negate : ('a -> bool) -> 'a -> bool +``` +`negate p` is the negation of the predicate function `p`. For any argument `x`, `(negate p) x` is `not (p x)`. +## Exception handling +``` +val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a +``` +`protect ~finally work` invokes `work ()` and then `finally ()` before `work ()` returns with its value or an exception. In the latter case the exception is re-raised after `finally ()`. If `finally ()` raises an exception, then the exception [`Finally_raised`](./#exception-Finally_raised) is raised instead. +`protect` can be used to enforce local invariants whether `work ()` returns normally or raises an exception. However, it does not protect against unexpected exceptions raised inside `finally ()` such as [`Stdlib.Out_of_memory`](./Stdlib.md#exception-Out_of_memory), [`Stdlib.Stack_overflow`](./Stdlib.md#exception-Stack_overflow), or asynchronous exceptions raised by signal handlers (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)). +Note: It is a *programming error* if other kinds of exceptions are raised by `finally`, as any exception raised in `work ()` will be lost in the event of a [`Finally_raised`](./#exception-Finally_raised) exception. Therefore, one should make sure to handle those inside the finally. +``` +exception Finally_raised of exn +``` +`Finally_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally_raised` exception except as part of a catch-all handler. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Gc-Memprof.md b/docs/api/melange/Stdlib-Gc-Memprof.md new file mode 100644 index 000000000..2514bb54d --- /dev/null +++ b/docs/api/melange/Stdlib-Gc-Memprof.md @@ -0,0 +1,84 @@ +# Module `Gc.Memprof` +`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. +Since blocks are composed of several words, a block can potentially be sampled several times. If a block is sampled several times, then each of the callbacks is called once for each event of this block: the multiplicity is given in the `n_samples` field of the `allocation` structure. +This engine makes it possible to implement a low-overhead memory profiler as an OCaml library. +Note: this API is EXPERIMENTAL. It may change without prior notice. +``` +type t +``` +the type of a profile +``` +type allocation_source = +``` +``` +| Normal +``` +``` +| Marshal +``` +``` +| Custom +``` +``` + +``` +``` +type allocation = private { +``` +`n_samples : int;` +The number of samples in this block (\>= 1\). +`size : int;` +The size of the block, in words, excluding the header. +`source : allocation_source;` +The cause of the allocation. +`callstack : Printexc.raw_backtrace;` +The callstack for the allocation. +``` +} +``` +The type of metadata associated with allocations. This is the type of records passed to the callback triggered by the sampling of an allocation. +``` +type ('minor, 'major) tracker = { +``` +`alloc_minor : allocation -> 'minor option;` +`alloc_major : allocation -> 'major option;` +`promote : 'minor -> 'major option;` +`dealloc_minor : 'minor -> unit;` +`dealloc_major : 'major -> unit;` +``` +} +``` +A `('minor, 'major) tracker` describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: `'minor` is the type of metadata to keep for minor blocks, and `'major` the type of metadata for major blocks. +The member functions in a `tracker` are called callbacks. +If an allocation or promotion callback raises an exception or returns `None`, memprof stops tracking the corresponding block. +``` +val null_tracker : ('minor, 'major) tracker +``` +Default callbacks simply return `None` or `()` +``` +val start : + sampling_rate:float -> + ?callstack_size:int -> + ('minor, 'major) tracker -> + t +``` +Start a profile with the given parameters. Raises an exception if a profile is already sampling in the current domain. +Sampling begins immediately. The parameter `sampling_rate` is the sampling rate in samples per word (including headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on performance, and 1e-3 causes the program to run a few percent slower. 0.0 \<= sampling\_rate \<= 1\.0. +The parameter `callstack_size` is the length of the callstack recorded at every sample. Its default is `max_int`. +The parameter `tracker` determines how to track sampled blocks over their lifetime in the minor and major heap. +Sampling and running callbacks are temporarily disabled on the current thread when calling a callback, so callbacks do not need to be re-entrant if the program is single-threaded and single-domain. However, if threads or multiple domains are used, it is possible that several callbacks will run in parallel. In this case, callback functions must be re-entrant. +Note that a callback may be postponed slightly after the actual event. The callstack passed to an allocation callback always accurately reflects the allocation, but the program state may have evolved between the allocation and the call to the callback. +If a new thread or domain is created when the current domain is sampling for a profile, the child thread or domain joins that profile (using the same `sampling_rate`, `callstack_size`, and `tracker` callbacks). +An allocation callback is always run by the thread which allocated the block. If the thread exits or the profile is stopped before the callback is called, the allocation callback is not called and the block is not tracked. +Each subsequent callback is generally run by the domain which allocated the block. If the domain terminates or the profile is stopped before the callback is called, the callback may be run by a different domain. +Different domains may sample for different profiles simultaneously. +``` +val stop : unit -> unit +``` +Stop sampling for the current profile. Fails if no profile is sampling in the current domain. Stops sampling in all threads and domains sharing the profile. +Promotion and deallocation callbacks from a profile may run after `stop` is called, until `discard` is applied to the profile. +A profile is implicitly stopped (but not discarded) if all domains and threads sampling for it are terminated. +``` +val discard : t -> unit +``` +Discards all profiling state for a stopped profile, which prevents any more callbacks for it. Raises an exception if called on a profile which has not been stopped. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Gc.md b/docs/api/melange/Stdlib-Gc.md new file mode 100644 index 000000000..098c3e3df --- /dev/null +++ b/docs/api/melange/Stdlib-Gc.md @@ -0,0 +1,222 @@ +# Module `Stdlib.Gc` +Memory management control and statistics; finalised values. +``` +type stat = { +``` +`minor_words : float;` +Number of words allocated in the minor heap since the program was started. +`promoted_words : float;` +Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap since the program was started. +`major_words : float;` +Number of words allocated in the major heap, including the promoted words, since the program was started. +`minor_collections : int;` +Number of minor collections since the program was started. +`major_collections : int;` +Number of major collection cycles completed since the program was started. +`heap_words : int;` +Total size of the major heap, in words. +`heap_chunks : int;` +Number of contiguous pieces of memory that make up the major heap. This metric is currently not available in OCaml 5: the field value is always `0`. +`live_words : int;` +Number of words of live data in the major heap, including the header words. +Note that "live" words refers to every word in the major heap that isn't currently known to be collectable, which includes words that have become unreachable by the program after the start of the previous gc cycle. It is typically much simpler and more predictable to call [`Gc.full_major`](./#val-full_major) (or [`Gc.compact`](./#val-compact)) then computing gc stats, as then "live" words has the simple meaning of "reachable by the program". One caveat is that a single call to [`Gc.full_major`](./#val-full_major) will not reclaim values that have a finaliser from [`Gc.finalise`](./#val-finalise) (this does not apply to [`Gc.finalise_last`](./#val-finalise_last)). If this caveat matters, simply call [`Gc.full_major`](./#val-full_major) twice instead of once. +`live_blocks : int;` +Number of live blocks in the major heap. +See `live_words` for a caveat about what "live" means. +`free_words : int;` +Number of words in the free list. +`free_blocks : int;` +Number of blocks in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. +`largest_free : int;` +Size (in words) of the largest block in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. +`fragments : int;` +Number of wasted words due to fragmentation. These are 1-words free blocks placed between two live blocks. They are not available for allocation. +`compactions : int;` +Number of heap compactions since the program was started. +`top_heap_words : int;` +Maximum size reached by the major heap, in words. +`stack_size : int;` +Current size of the stack, in words. This metric is currently not available in OCaml 5: the field value is always `0`. +since 3.12 +`forced_major_collections : int;` +Number of forced full major collections completed since the program was started. +since 4.12 +``` +} +``` +The memory management counters are returned in a `stat` record. These counters give values for the whole program. +The total amount of memory allocated by the program since it was started is (in words) `minor_words + major_words - promoted_words`. Multiply by the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes. +``` +type control = { +``` +`minor_heap_size : int;` +The size (in words) of the minor heap. Changing this parameter will trigger a minor collection. The total size of the minor heap used by this program is the sum of the heap sizes of the active domains. Default: 256k. +`major_heap_increment : int;` +How much to add to the major heap when increasing it. If this number is less than or equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will double the heap size at each increase). If it is more than 1000, it is a fixed number of words that will be added to the heap. +This field is currently not available in OCaml 5: the field value is always `0`. +`space_overhead : int;` +The major GC speed is computed from this parameter. This is the memory that will be "wasted" because the GC does not immediately collect unreachable blocks. It is expressed as a percentage of the memory used for live data. The GC will work more (use more CPU time and collect blocks more eagerly) if `space_overhead` is smaller. Default: 120. +`verbose : int;` +This value controls the GC messages on standard error output. It is a sum of some of the following flags, to print messages on the corresponding events: +- `0x001` Start and end of major GC cycle. +- `0x002` Minor collection and major GC slice. +- `0x004` Growing and shrinking of the heap. +- `0x008` Resizing of stacks and memory manager tables. +- `0x010` Heap compaction. +- `0x020` Change of GC parameters. +- `0x040` Computation of major GC slice size. +- `0x080` Calling of finalisation functions. +- `0x100` Bytecode executable and shared library search at start-up. +- `0x200` Computation of compaction-triggering condition. +- `0x400` Output GC statistics at program exit. Default: 0. +`max_overhead : int;` +Heap compaction is triggered when the estimated amount of "wasted" memory is more than `max_overhead` percent of the amount of live data. If `max_overhead` is set to 0, heap compaction is triggered at the end of each major GC cycle (this setting is intended for testing purposes only). If `max_overhead >= 1000000`, compaction is never triggered. +This field is currently not available in OCaml 5: the field value is always `0`. +`stack_limit : int;` +The maximum size of the fiber stacks (in words). Default: 128M. +`allocation_policy : int;` +The policy used for allocating in the major heap. +This field is currently not available in OCaml 5: the field value is always `0`. +Prior to OCaml 5.0, possible values were 0, 1 and 2. +- 0 was the next-fit policy +- 1 was the first-fit policy (since OCaml 3.11) +- 2 was the best-fit policy (since OCaml 4.10) +since 3.11 +`window_size : int;` +The size of the window used by the major GC for smoothing out variations in its workload. This is an integer between 1 and 50. +since 4.03 +This field is currently not available in OCaml 5: the field value is always `0`. +`custom_major_ratio : int;` +Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. The default value keeps the out-of-heap floating garbage about the same size as the in-heap overhead. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 44. +since 4.08 +`custom_minor_ratio : int;` +Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 100. +since 4.08 +`custom_minor_max_size : int;` +Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. Custom values that hold more than this many bytes are allocated on the major heap. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 70000 bytes. +since 4.08 +``` +} +``` +The GC parameters are given as a `control` record. Note that these parameters can also be initialised by setting the OCAMLRUNPARAM environment variable. See the documentation of `ocamlrun`. +``` +val stat : unit -> stat +``` +Return the current values of the memory management counters in a `stat` record that represents the program's total memory stats. The `heap_chunks`, `free_blocks`, `largest_free`, and `stack_size` metrics are currently not available in OCaml 5: their returned field values are therefore `0`. This function causes a full major collection. +``` +val quick_stat : unit -> stat +``` +Returns a record with the current values of the memory management counters like `stat`. Unlike `stat`, `quick_stat` does not perform a full major collection, and hence, is much faster. However, `quick_stat` reports the counters sampled at the last minor collection or at the end of the last major collection cycle (whichever is the latest). Hence, the memory stats returned by `quick_stat` are not instantaneously accurate. +``` +val counters : unit -> float * float * float +``` +Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. This function is as fast as `quick_stat`. +``` +val minor_words : unit -> float +``` +Number of words allocated in the minor heap by this domain or potentially previous domains. This number is accurate in byte-code programs, but only an approximation in programs compiled to native code. +In native code this function does not allocate. +since 4.04 +``` +val get : unit -> control +``` +Return the current values of the GC parameters in a `control` record. +The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: their returned field values are therefore `0`. +alert unsynchronized\_access GC parameters are a mutable global state. +``` +val set : control -> unit +``` +`set r` changes the GC parameters according to the `control` record `r`. The normal usage is: `Gc.set { (Gc.get()) with Gc.verbose = 0x00d }` +The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: setting them therefore has no effect. +alert unsynchronized\_access GC parameters are a mutable global state. +``` +val minor : unit -> unit +``` +Trigger a minor collection. +``` +val major_slice : int -> int +``` +`major_slice n` Do a minor collection and a slice of major collection. `n` is the size of the slice: the GC will do enough work to free (on average) `n` words of memory. If `n` \= 0, the GC will try to do enough work to ensure that the next automatic slice has no work to do. This function returns an unspecified integer (currently: 0). +``` +val major : unit -> unit +``` +Do a minor collection and finish the current major collection cycle. +``` +val full_major : unit -> unit +``` +Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. This will collect all currently unreachable blocks. +``` +val compact : unit -> unit +``` +Perform a full major collection and compact the heap. Note that heap compaction is a lengthy operation. +``` +val print_stat : out_channel -> unit +``` +Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument. +``` +val allocated_bytes : unit -> float +``` +Return the number of bytes allocated by this domain and potentially a previous domain. It is returned as a `float` to avoid overflow problems with `int` on 32-bit machines. +``` +val get_minor_free : unit -> int +``` +Return the current size of the free space inside the minor heap of this domain. +since 4.03 +``` +val finalise : ('a -> unit) -> 'a -> unit +``` +`finalise f v` registers `f` as a finalisation function for `v`. `v` must be heap-allocated. `f` will be called with `v` as argument at some point between the first time `v` becomes unreachable (including through weak pointers) and the time `v` is collected by the GC. Several functions can be registered for the same value, or even several instances of the same function. Each instance will be called once (or never, if the program terminates before `v` becomes unreachable). +The GC will call the finalisation functions in the order of deallocation. When several values become unreachable at the same time (i.e. during the same GC cycle), the finalisation functions will be called in the reverse order of the corresponding calls to `finalise`. If `finalise` is called in the same order as the values are allocated, that means each value is finalised before the values it depends upon. Of course, this becomes false if additional dependencies are introduced by assignments. +In the presence of multiple OCaml threads it should be assumed that any particular finaliser may be executed in any of the threads. +Anything reachable from the closure of finalisation functions is considered reachable, so the following code will not work as expected: +- ` let v = ... in Gc.finalise (fun _ -> ...v...) v ` +Instead you should make sure that `v` is not in the closure of the finalisation function by writing: +- ` let f = fun x -> ... let v = ... in Gc.finalise f v ` +The `f` function can use all features of OCaml, including assignments that make the value reachable again. It can also loop forever (in this case, the other finalisation functions will not be called during the execution of f, unless it calls `finalise_release`). It can call `finalise` on `v` or other values to register other functions or even itself. It can raise an exception; in this case the exception will interrupt whatever the program was doing when the function was called. +`finalise` will raise `Invalid_argument` if `v` is not guaranteed to be heap-allocated. Some examples of values that are not heap-allocated are integers, constant constructors, booleans, the empty array, the empty list, the unit value. The exact list of what is heap-allocated or not is implementation-dependent. Some constant values can be heap-allocated but never deallocated during the lifetime of the program, for example a list of integer constants; this is also implementation-dependent. Note that values of types `float` are sometimes allocated and sometimes not, so finalising them is unsafe, and `finalise` will also raise `Invalid_argument` for them. Values of type `'a Lazy.t` (for any `'a`) are like `float` in this respect, except that the compiler sometimes optimizes them in a way that prevents `finalise` from detecting them. In this case, it will not raise `Invalid_argument`, but you should still avoid calling `finalise` on lazy values. +The results of calling [`String.make`](./Stdlib-String.md#val-make), [`Bytes.make`](./Stdlib-Bytes.md#val-make), [`Bytes.create`](./Stdlib-Bytes.md#val-create), [`Array.make`](./Stdlib-Array.md#val-make), and [`Stdlib.ref`](./Stdlib.md#val-ref) are guaranteed to be heap-allocated and non-constant except when the length argument is `0`. +``` +val finalise_last : (unit -> unit) -> 'a -> unit +``` +same as [`finalise`](./#val-finalise) except the value is not given as argument. So you can't use the given value for the computation of the finalisation function. The benefit is that the function is called after the value is unreachable for the last time instead of the first time. So contrary to [`finalise`](./#val-finalise) the value will never be reachable again or used again. In particular every weak pointer and ephemeron that contained this value as key or data is unset before running the finalisation function. Moreover the finalisation functions attached with [`finalise`](./#val-finalise) are always called before the finalisation functions attached with [`finalise_last`](./#val-finalise_last). +since 4.04 +``` +val finalise_release : unit -> unit +``` +A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return. +``` +type alarm +``` +An alarm is a piece of data that calls a user function at the end of major GC cycle. The following functions are provided to create and delete alarms. +``` +val create_alarm : (unit -> unit) -> alarm +``` +`create_alarm f` will arrange for `f` to be called at the end of major GC cycles, not caused by `f` itself, starting with the current cycle or the next one. `f` will run on the same domain that created the alarm, until the domain exits or `delete_alarm` is called. A value of type `alarm` is returned that you can use to call `delete_alarm`. +It is not guaranteed that the Gc alarm runs at the end of every major GC cycle, but it is guaranteed that it will run eventually. +As an example, here is a crude way to interrupt a function if the memory consumption of the program exceeds a given `limit` in MB, suitable for use in the toplevel: +```ocaml +let run_with_memory_limit (limit : int) (f : unit -> 'a) : 'a = + let limit_memory () = + let mem = Gc.(quick_stat ()).heap_words in + if mem / (1024 * 1024) > limit / (Sys.word_size / 8) then + raise Out_of_memory + in + let alarm = Gc.create_alarm limit_memory in + Fun.protect f ~finally:(fun () -> Gc.delete_alarm alarm ; Gc.compact ()) +``` +``` +val delete_alarm : alarm -> unit +``` +`delete_alarm a` will stop the calls to the function associated to `a`. Calling `delete_alarm a` again has no effect. +``` +val eventlog_pause : unit -> unit +``` +deprecated Use Runtime\_events.pause instead. +``` +val eventlog_resume : unit -> unit +``` +deprecated Use Runtime\_events.resume instead. +``` +module Memprof : sig ... end +``` +`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md b/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md new file mode 100644 index 000000000..492b57f0f --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md @@ -0,0 +1,16 @@ +# Parameter `Make.H` +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-Make.md b/docs/api/melange/Stdlib-Hashtbl-Make.md new file mode 100644 index 000000000..887725936 --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-Make.md @@ -0,0 +1,89 @@ +# Module `Hashtbl.Make` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. +## Parameters +``` +module H : HashedType +``` +## Signature +``` +type key = H.t +``` +``` +type !'a t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md new file mode 100644 index 000000000..7f8d54ae8 --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md @@ -0,0 +1,13 @@ +# Parameter `MakeSeeded.H` +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md new file mode 100644 index 000000000..af7731734 --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md @@ -0,0 +1,88 @@ +# Module `Hashtbl.MakeSeeded` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-Hashtbl.md#val-randomize)). +since 4.00 +## Parameters +``` +module H : SeededHashedType +``` +## Signature +``` +type key = H.t +``` +``` +type !'a t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md b/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md new file mode 100644 index 000000000..aae1e09a4 --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md @@ -0,0 +1,17 @@ +# Module type `Hashtbl.HashedType` +The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-S.md b/docs/api/melange/Stdlib-Hashtbl-module-type-S.md new file mode 100644 index 000000000..2720a929a --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-S.md @@ -0,0 +1,84 @@ +# Module type `Hashtbl.S` +The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). +``` +type key +``` +``` +type !'a t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md new file mode 100644 index 000000000..e96072c4a --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md @@ -0,0 +1,15 @@ +# Module type `Hashtbl.SeededHashedType` +The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 4.00 +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md new file mode 100644 index 000000000..b811c5912 --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md @@ -0,0 +1,83 @@ +# Module type `Hashtbl.SeededS` +The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 4.00 +``` +type key +``` +``` +type !'a t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl.md b/docs/api/melange/Stdlib-Hashtbl.md new file mode 100644 index 000000000..fa2b5865c --- /dev/null +++ b/docs/api/melange/Stdlib-Hashtbl.md @@ -0,0 +1,301 @@ +# Module `Stdlib.Hashtbl` +Hash tables and hash functions. +Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-Map.md). +The functors [`Make`](./Stdlib-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. +**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. +The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. +See [the examples section](./#examples). +**Unsynchronized accesses** +Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +## Generic interface +``` +type (!'a, !'b) t +``` +The type of hash tables from type `'a` to type `'b`. +``` +val create : ?random:bool -> int -> ('a, 'b) t +``` +`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. +A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. +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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. +before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. +``` +val clear : ('a, 'b) t -> unit +``` +Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. +``` +val reset : ('a, 'b) t -> unit +``` +Empty a hash table and shrink the size of the bucket table to its initial size. +since 4.00 +``` +val copy : ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. +``` +val add : ('a, 'b) t -> 'a -> 'b -> unit +``` +`Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`. +**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) +If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). +``` +val find : ('a, 'b) t -> 'a -> 'b +``` +`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. +``` +val find_opt : ('a, 'b) t -> 'a -> 'b option +``` +`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. +since 4.05 +``` +val find_all : ('a, 'b) t -> 'a -> 'b list +``` +`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. +``` +val mem : ('a, 'b) t -> 'a -> bool +``` +`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. +``` +val remove : ('a, 'b) t -> 'a -> unit +``` +`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. +``` +val replace : ('a, 'b) t -> 'a -> 'b -> unit +``` +`Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. +``` +val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit +``` +`Hashtbl.iter f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. +The behavior is not specified if the hash table is modified by `f` during the iteration. +``` +val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit +``` +`Hashtbl.filter_map_inplace f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. +Other comments for [`iter`](./#val-iter) apply as well. +since 4.03 +``` +val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc +``` +`Hashtbl.fold f tbl init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. +The behavior is not specified if the hash table is modified by `f` during the iteration. +``` +val length : ('a, 'b) t -> int +``` +`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. +``` +val randomize : unit -> unit +``` +After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. +It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. +Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. +since 4.00 +``` +val is_randomized : unit -> bool +``` +Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. +since 4.03 +``` +val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. +[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. +since 4.12 +``` +type statistics = { +``` +`num_bindings : int;` +Number of bindings present in the table. Same value as returned by [`length`](./#val-length). +`num_buckets : int;` +Number of buckets in the table. +`max_bucket_length : int;` +Maximal number of bindings per bucket. +`bucket_histogram : int array;` +Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. +``` +} +``` +since 4.00 +``` +val stats : ('a, 'b) t -> statistics +``` +`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. +since 4.00 +## Hash tables and Sequences +``` +val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t +``` +Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. +The behavior is not specified if the hash table is modified during the iteration. +since 4.07 +``` +val to_seq_keys : ('a, _) t -> 'a Seq.t +``` +Same as `Seq.map fst (to_seq m)` +since 4.07 +``` +val to_seq_values : (_, 'b) t -> 'b Seq.t +``` +Same as `Seq.map snd (to_seq m)` +since 4.07 +``` +val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`add`](./#val-add) +since 4.07 +``` +val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`replace`](./#val-replace) +since 4.07 +``` +val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t +``` +Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. +since 4.07 +## Functorial interface +The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. +For instance, one might want to specialize a table for integer keys: +```ocaml + module IntHash = + struct + type t = int + let equal i j = i=j + let hash i = i land max_int + end + + module IntHashtbl = Hashtbl.Make(IntHash) + + let h = IntHashtbl.create 17 in + IntHashtbl.add h 12 "hello" +``` +This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. +Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. +``` +module type HashedType = sig ... end +``` +The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). +``` +module type S = sig ... end +``` +The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). +``` +module Make (H : HashedType) : S with type key = H.t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. +``` +module type SeededHashedType = sig ... end +``` +The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +``` +module type SeededS = sig ... end +``` +The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +``` +module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). +## The polymorphic hash functions +``` +val hash : 'a -> int +``` +`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. +``` +val seeded_hash : int -> 'a -> int +``` +A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. +since 4.00 +``` +val hash_param : int -> int -> 'a -> int +``` +`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. +``` +val seeded_hash_param : int -> int -> int -> 'a -> int +``` +A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. +since 4.00 +## 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 + 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 +``` +### Counting Elements +Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. +Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. +```ocaml + # module Char_tbl = Hashtbl.Make(struct + type t = char + let equal = Char.equal + let hash = Hashtbl.hash + end) + + (* count distinct occurrences of chars in [seq] *) + # let count_chars (seq : char Seq.t) : _ list = + let counts = Char_tbl.create 16 in + Seq.iter + (fun c -> + let count_c = + Char_tbl.find_opt counts c + |> Option.value ~default:0 + in + Char_tbl.replace counts c (count_c + 1)) + seq; + (* turn into a list *) + Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] + |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) + val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = + + (* basic seq from a string *) + # let seq = String.to_seq "hello world, and all the camels in it!" + val seq : char Seq.t = + + # count_chars seq + - : (Char.t * int) list = + [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); + ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); + ('s', 1); ('t', 2); ('w', 1)] + + (* "abcabcabc..." *) + # let seq2 = + Seq.cycle (String.to_seq "abc") |> Seq.take 31 + val seq2 : char Seq.t = + + # String.of_seq seq2 + - : String.t = "abcabcabcabcabcabcabcabcabcabca" + + # count_chars seq2 + - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] + +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-In_channel.md b/docs/api/melange/Stdlib-In_channel.md new file mode 100644 index 000000000..97608184b --- /dev/null +++ b/docs/api/melange/Stdlib-In_channel.md @@ -0,0 +1,176 @@ +# Module `Stdlib.In_channel` +Input channels. +This module provides functions for working with input channels. +See [the example section](./#examples) below. +since 4.14 +## Channels +``` +type t = in_channel +``` +The type of input channel. +``` +type open_flag = open_flag = +``` +``` +| Open_rdonly +``` +open for reading. +``` +| Open_wronly +``` +open for writing. +``` +| Open_append +``` +open for appending: always write at end of file. +``` +| Open_creat +``` +create the file if it does not exist. +``` +| Open_trunc +``` +empty the file if it already exists. +``` +| Open_excl +``` +fail if Open\_creat and the file already exists. +``` +| Open_binary +``` +open in binary mode (no conversion). +``` +| Open_text +``` +open in text mode (may perform conversions). +``` +| Open_nonblock +``` +open in non-blocking mode. +``` + +``` +Opening modes for [`open_gen`](./#val-open_gen). +``` +val stdin : t +``` +The standard input for the process. +``` +val open_bin : string -> t +``` +Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. +``` +val open_text : string -> t +``` +Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). +``` +val open_gen : open_flag list -> int -> string -> t +``` +`open_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. +``` +val with_open_bin : string -> (t -> 'a) -> 'a +``` +`with_open_bin fn f` opens a channel `ic` on file `fn` and returns `f ic`. After `f` returns, either with a value or by raising an exception, `ic` is guaranteed to be closed. +``` +val with_open_text : string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). +``` +val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). +``` +val close : t -> unit +``` +Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except [`close`](./#val-close), which does nothing when applied to an already closed channel. +``` +val close_noerr : t -> unit +``` +Same as [`close`](./#val-close), but ignore all errors. +## Input +``` +val input_char : t -> char option +``` +Read one character from the given input channel. Returns `None` if there are no more characters to read. +``` +val input_byte : t -> int option +``` +Same as [`input_char`](./#val-input_char), but return the 8-bit integer representing the character. Returns `None` if the end of file was reached. +``` +val input_line : t -> string option +``` +`input_line ic` reads characters from `ic` until a newline or the end of file is reached. Returns the string of all characters read, without the newline (if any). Returns `None` if the end of the file has been reached. In particular, this will be the case if the last line of input is empty. +A newline is the character `\n` unless the file is open in text mode and [`Sys.win32`](./Stdlib-Sys.md#val-win32) is `true` in which case it is the sequence of characters `\r\n`. +``` +val really_input_string : t -> int -> string option +``` +`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. Returns `None` if the end of file is reached before `len` characters have been read. +If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. +``` +val input_all : t -> string +``` +`input_all ic` reads all remaining data from `ic`. +If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. +``` +val input_lines : t -> string list +``` +`input_lines ic` reads lines using [`input_line`](./#val-input_line) until the end of file is reached. It returns the list of all lines read, in the order they were read. The newline characters that terminate lines are not included in the returned strings. Empty lines produce empty strings. +since 5.1 +## Advanced input +``` +val input : t -> bytes -> int -> int -> int +``` +`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. +Use [`really_input`](./#val-really_input) to read exactly `len` characters. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val really_input : t -> bytes -> int -> int -> unit option +``` +`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. +Returns `None` if the end of file is reached before `len` characters have been read. +If the same channel is read concurrently by multiple threads, the bytes read by `really_input` are not guaranteed to be contiguous. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val fold_lines : ('acc -> string -> 'acc) -> 'acc -> t -> 'acc +``` +`fold_lines f init ic` reads lines from `ic` using [`input_line`](./#val-input_line) until the end of file is reached, and successively passes each line to function `f` in the style of a fold. More precisely, if lines `l1, ..., lN` are read, `fold_lines f init ic` computes `f (... (f (f init l1) l2) ...) lN`. If `f` has no side effects, this is equivalent to `List.fold_left f init (In_channel.input_lines ic)`, but is more efficient since it does not construct the list of all lines read. +since 5.1 +## Seeking +``` +val seek : t -> int64 -> unit +``` +`seek chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. +``` +val pos : t -> int64 +``` +Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. +## Attributes +``` +val length : t -> int64 +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. +``` +val set_binary_mode : t -> bool -> unit +``` +`set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input. +`set_binary_mode ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. +This function has no effect under operating systems that do not distinguish between text mode and binary mode. +``` +val is_binary_mode : t -> bool +``` +`is_binary_mode ic` returns whether the channel `ic` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). +since 5.2 +``` +val isatty : t -> bool +``` +`isatty ic` is `true` if `ic` refers to a terminal or console window, `false` otherwise. +since 5.1 +## Examples +Reading the contents of a file: +```ocaml + let read_file file = In_channel.with_open_bin file In_channel.input_all +``` +Reading a line from stdin: +```ocaml + let user_input () = In_channel.input_line In_channel.stdin +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Int.md b/docs/api/melange/Stdlib-Int.md new file mode 100644 index 000000000..9f46e5b77 --- /dev/null +++ b/docs/api/melange/Stdlib-Int.md @@ -0,0 +1,135 @@ +# Module `Stdlib.Int` +Integer values. +Integers are [`Sys.int_size`](./Stdlib-Sys.md#val-int_size) bits wide and use two's complement representation. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. +since 4.08 +## Integers +``` +type t = int +``` +The type for integer values. +``` +val zero : int +``` +`zero` is the integer `0`. +``` +val one : int +``` +`one` is the integer `1`. +``` +val minus_one : int +``` +`minus_one` is the integer `-1`. +``` +val neg : int -> int +``` +`neg x` is `~-x`. +``` +val add : int -> int -> int +``` +`add x y` is the addition `x + y`. +``` +val sub : int -> int -> int +``` +`sub x y` is the subtraction `x - y`. +``` +val mul : int -> int -> int +``` +`mul x y` is the multiplication `x * y`. +``` +val div : int -> int -> int +``` +`div x y` is the division `x / y`. See [`Stdlib.(/)`](./Stdlib.md#val-\(/\)) for details. +``` +val rem : int -> int -> int +``` +`rem x y` is the remainder `x mod y`. See [`Stdlib.(mod)`](./Stdlib.md#val-\(mod\)) for details. +``` +val succ : int -> int +``` +`succ x` is `add x 1`. +``` +val pred : int -> int +``` +`pred x` is `sub x 1`. +``` +val abs : int -> int +``` +`abs x` is the absolute value of `x`. That is `x` if `x` is positive and `neg x` if `x` is negative. **Warning.** This may be negative if the argument is [`min_int`](./#val-min_int). +``` +val max_int : int +``` +`max_int` is the greatest representable integer, `2``Sys.int_size - 1``-1`. +``` +val min_int : int +``` +`min_int` is the smallest representable integer, `-2``Sys.int_size - 1`. +``` +val logand : int -> int -> int +``` +`logand x y` is the bitwise logical and of `x` and `y`. +``` +val logor : int -> int -> int +``` +`logor x y` is the bitwise logical or of `x` and `y`. +``` +val logxor : int -> int -> int +``` +`logxor x y` is the bitwise logical exclusive or of `x` and `y`. +``` +val lognot : int -> int +``` +`lognot x` is the bitwise logical negation of `x`. +``` +val shift_left : int -> int -> int +``` +`shift_left x n` shifts `x` to the left by `n` bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). +``` +val shift_right : int -> int -> int +``` +`shift_right x n` shifts `x` to the right by `n` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). +``` +val shift_right_logical : int -> int -> int +``` +`shift_right x n` shifts `x` to the right by `n` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). +## Predicates and comparisons +``` +val equal : int -> int -> bool +``` +`equal x y` is `true` if and only if `x = y`. +``` +val compare : int -> int -> int +``` +`compare x y` is [`Stdlib.compare`](./Stdlib.md#val-compare)` x y` but more efficient. +``` +val min : int -> int -> int +``` +Return the smaller of the two arguments. +since 4.13 +``` +val max : int -> int -> int +``` +Return the greater of the two arguments. +since 4.13 +## Converting +``` +val to_float : int -> float +``` +`to_float x` is `x` as a floating point number. +``` +val of_float : float -> int +``` +`of_float x` truncates `x` to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. +``` +val to_string : int -> string +``` +`to_string x` is the written representation of `x` in decimal. +``` +val seeded_hash : int -> int -> int +``` +A seeded hash function for ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.1 +``` +val hash : int -> int +``` +An unseeded hash function for ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Int32.md b/docs/api/melange/Stdlib-Int32.md new file mode 100644 index 000000000..e1d0ca0ab --- /dev/null +++ b/docs/api/melange/Stdlib-Int32.md @@ -0,0 +1,188 @@ +# Module `Stdlib.Int32` +32-bit integers. +This module provides operations on the type `int32` of signed 32-bit integers. Unlike the built-in `int` type, the type `int32` is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over `int32` are taken modulo 232. +Performance notice: values of type `int32` occupy more memory space than values of type `int`, and arithmetic operations on `int32` are generally slower than those on `int`. Use `int32` only when the application requires exact 32-bit arithmetic. +Literals for 32-bit integers are suffixed by l: +```ocaml + let zero: int32 = 0l + let one: int32 = 1l + let m_one: int32 = -1l +``` +``` +val zero : int32 +``` +The 32-bit integer 0. +``` +val one : int32 +``` +The 32-bit integer 1\. +``` +val minus_one : int32 +``` +The 32-bit integer \-1. +``` +val neg : int32 -> int32 +``` +Unary negation. +``` +val add : int32 -> int32 -> int32 +``` +Addition. +``` +val sub : int32 -> int32 -> int32 +``` +Subtraction. +``` +val mul : int32 -> int32 -> int32 +``` +Multiplication. +``` +val div : int32 -> int32 -> int32 +``` +Integer division. This division rounds the real quotient of its arguments towards zero, as specified for [`Stdlib.(/)`](./Stdlib.md#val-\(/\)). +raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. +``` +val unsigned_div : int32 -> int32 -> int32 +``` +Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 32-bit integers. +since 4.08 +``` +val rem : int32 -> int32 -> int32 +``` +Integer remainder. If `y` is not zero, the result of `Int32.rem x y` satisfies the following property: `x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)`. If `y = 0`, `Int32.rem x y` raises `Division_by_zero`. +``` +val unsigned_rem : int32 -> int32 -> int32 +``` +Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 32-bit integers. +since 4.08 +``` +val succ : int32 -> int32 +``` +Successor. `Int32.succ x` is `Int32.add x Int32.one`. +``` +val pred : int32 -> int32 +``` +Predecessor. `Int32.pred x` is `Int32.sub x Int32.one`. +``` +val abs : int32 -> int32 +``` +`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. +``` +val max_int : int32 +``` +The greatest representable 32-bit integer, 231 \- 1\. +``` +val min_int : int32 +``` +The smallest representable 32-bit integer, \-231. +``` +val logand : int32 -> int32 -> int32 +``` +Bitwise logical and. +``` +val logor : int32 -> int32 -> int32 +``` +Bitwise logical or. +``` +val logxor : int32 -> int32 -> int32 +``` +Bitwise logical exclusive or. +``` +val lognot : int32 -> int32 +``` +Bitwise logical negation. +``` +val shift_left : int32 -> int -> int32 +``` +`Int32.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 32`. +``` +val shift_right : int32 -> int -> int32 +``` +`Int32.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 32`. +``` +val shift_right_logical : int32 -> int -> int32 +``` +`Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 32`. +``` +val of_int : int -> int32 +``` +Convert the given integer (type `int`) to a 32-bit integer (type `int32`). On 64-bit platforms, the argument is taken modulo 232. +``` +val to_int : int32 -> int +``` +Convert the given 32-bit integer (type `int32`) to an integer (type `int`). On 32-bit platforms, the 32-bit integer is taken modulo 231, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. +``` +val unsigned_to_int : int32 -> int option +``` +Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. +since 4.08 +``` +val of_float : float -> int32 +``` +Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int32.min_int`](./#val-min_int), [`Int32.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. +``` +val to_float : int32 -> float +``` +Convert the given 32-bit integer to a floating-point number. +``` +val of_string : string -> int32 +``` +Convert the given string to a 32-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. +The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int32.max_int+1]`. If the input exceeds [`Int32.max_int`](./#val-max_int) it is converted to the signed integer `Int32.min_int + input - Int32.max_int - 1`. +The `_` (underscore) character can appear anywhere in the string and is ignored. +raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int32. +``` +val of_string_opt : string -> int32 option +``` +Same as `of_string`, but return `None` instead of raising. +since 4.05 +``` +val to_string : int32 -> string +``` +Return the string representation of its argument, in signed decimal. +``` +val bits_of_float : float -> int32 +``` +Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa. +``` +val float_of_bits : int32 -> float +``` +Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`. +``` +type t = int32 +``` +An alias for the type of 32-bit integers. +``` +val compare : t -> t -> int +``` +The comparison function for 32-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). +``` +val unsigned_compare : t -> t -> int +``` +Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 32-bit integers. +since 4.08 +``` +val equal : t -> t -> bool +``` +The equal function for int32s. +since 4.03 +``` +val min : t -> t -> t +``` +Return the smaller of the two arguments. +since 4.13 +``` +val max : t -> t -> t +``` +Return the greater of the two arguments. +since 4.13 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for 32-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for 32-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Int64.md b/docs/api/melange/Stdlib-Int64.md new file mode 100644 index 000000000..676e377b0 --- /dev/null +++ b/docs/api/melange/Stdlib-Int64.md @@ -0,0 +1,204 @@ +# Module `Stdlib.Int64` +64-bit integers. +This module provides operations on the type `int64` of signed 64-bit integers. Unlike the built-in `int` type, the type `int64` is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over `int64` are taken modulo 264 +Performance notice: values of type `int64` occupy more memory space than values of type `int`, and arithmetic operations on `int64` are generally slower than those on `int`. Use `int64` only when the application requires exact 64-bit arithmetic. +Literals for 64-bit integers are suffixed by L: +```ocaml + let zero: int64 = 0L + let one: int64 = 1L + let m_one: int64 = -1L +``` +``` +val zero : int64 +``` +The 64-bit integer 0. +``` +val one : int64 +``` +The 64-bit integer 1\. +``` +val minus_one : int64 +``` +The 64-bit integer \-1. +``` +val neg : int64 -> int64 +``` +Unary negation. +``` +val add : int64 -> int64 -> int64 +``` +Addition. +``` +val sub : int64 -> int64 -> int64 +``` +Subtraction. +``` +val mul : int64 -> int64 -> int64 +``` +Multiplication. +``` +val div : int64 -> int64 -> int64 +``` +Integer division. +raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/). +``` +val unsigned_div : int64 -> int64 -> int64 +``` +Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 64-bit integers. +since 4.08 +``` +val rem : int64 -> int64 -> int64 +``` +Integer remainder. If `y` is not zero, the result of `Int64.rem x y` satisfies the following property: `x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)`. If `y = 0`, `Int64.rem x y` raises `Division_by_zero`. +``` +val unsigned_rem : int64 -> int64 -> int64 +``` +Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 64-bit integers. +since 4.08 +``` +val succ : int64 -> int64 +``` +Successor. `Int64.succ x` is `Int64.add x Int64.one`. +``` +val pred : int64 -> int64 +``` +Predecessor. `Int64.pred x` is `Int64.sub x Int64.one`. +``` +val abs : int64 -> int64 +``` +`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. +``` +val max_int : int64 +``` +The greatest representable 64-bit integer, 263 \- 1\. +``` +val min_int : int64 +``` +The smallest representable 64-bit integer, \-263. +``` +val logand : int64 -> int64 -> int64 +``` +Bitwise logical and. +``` +val logor : int64 -> int64 -> int64 +``` +Bitwise logical or. +``` +val logxor : int64 -> int64 -> int64 +``` +Bitwise logical exclusive or. +``` +val lognot : int64 -> int64 +``` +Bitwise logical negation. +``` +val shift_left : int64 -> int -> int64 +``` +`Int64.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 64`. +``` +val shift_right : int64 -> int -> int64 +``` +`Int64.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 64`. +``` +val shift_right_logical : int64 -> int -> int64 +``` +`Int64.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 64`. +``` +val of_int : int -> int64 +``` +Convert the given integer (type `int`) to a 64-bit integer (type `int64`). +``` +val to_int : int64 -> int +``` +Convert the given 64-bit integer (type `int64`) to an integer (type `int`). On 64-bit platforms, the 64-bit integer is taken modulo 263, i.e. the high-order bit is lost during the conversion. On 32-bit platforms, the 64-bit integer is taken modulo 231, i.e. the top 33 bits are lost during the conversion. +``` +val unsigned_to_int : int64 -> int option +``` +Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. +since 4.08 +``` +val of_float : float -> int64 +``` +Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int64.min_int`](./#val-min_int), [`Int64.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. +``` +val to_float : int64 -> float +``` +Convert the given 64-bit integer to a floating-point number. +``` +val of_int32 : int32 -> int64 +``` +Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`). +``` +val to_int32 : int64 -> int32 +``` +Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). The 64-bit integer is taken modulo 232, i.e. the top 32 bits are lost during the conversion. +``` +val of_nativeint : nativeint -> int64 +``` +Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`). +``` +val to_nativeint : int64 -> nativeint +``` +Convert the given 64-bit integer (type `int64`) to a native integer. On 32-bit platforms, the 64-bit integer is taken modulo 232. On 64-bit platforms, the conversion is exact. +``` +val of_string : string -> int64 +``` +Convert the given string to a 64-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. +The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int64.max_int+1]`. If the input exceeds [`Int64.max_int`](./#val-max_int) it is converted to the signed integer `Int64.min_int + input - Int64.max_int - 1`. +The `_` (underscore) character can appear anywhere in the string and is ignored. +raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int64. +``` +val of_string_opt : string -> int64 option +``` +Same as `of_string`, but return `None` instead of raising. +since 4.05 +``` +val to_string : int64 -> string +``` +Return the string representation of its argument, in decimal. +``` +val bits_of_float : float -> int64 +``` +Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. Bit 63 of the result represents the sign of the float; bits 62 to 52 represent the (biased) exponent; bits 51 to 0 represent the mantissa. +``` +val float_of_bits : int64 -> float +``` +Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`. +``` +type t = int64 +``` +An alias for the type of 64-bit integers. +``` +val compare : t -> t -> int +``` +The comparison function for 64-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int64` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). +``` +val unsigned_compare : t -> t -> int +``` +Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 64-bit integers. +since 4.08 +``` +val equal : t -> t -> bool +``` +The equal function for int64s. +since 4.03 +``` +val min : t -> t -> t +``` +Return the smaller of the two arguments. +since 4.13 +``` +val max : t -> t -> t +``` +Return the greater of the two arguments. +since 4.13 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for 64-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for 64-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-LargeFile.md b/docs/api/melange/Stdlib-LargeFile.md new file mode 100644 index 000000000..2c120e4de --- /dev/null +++ b/docs/api/melange/Stdlib-LargeFile.md @@ -0,0 +1,20 @@ +# Module `Stdlib.LargeFile` +Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. +``` +val seek_out : out_channel -> int64 -> unit +``` +``` +val pos_out : out_channel -> int64 +``` +``` +val out_channel_length : out_channel -> int64 +``` +``` +val seek_in : in_channel -> int64 -> unit +``` +``` +val pos_in : in_channel -> int64 +``` +``` +val in_channel_length : in_channel -> int64 +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Lazy.md b/docs/api/melange/Stdlib-Lazy.md new file mode 100644 index 000000000..9c36975cf --- /dev/null +++ b/docs/api/melange/Stdlib-Lazy.md @@ -0,0 +1,66 @@ +# Module `Stdlib.Lazy` +Deferred computations. +``` +type 'a t = 'a CamlinternalLazy.t +``` +A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. The special expression syntax `lazy (expr)` makes a suspension of the computation of `expr`, without computing `expr` itself yet. "Forcing" the suspension will then compute `expr` and return its result. Matching a suspension with the special pattern syntax `lazy(pattern)` also computes the underlying expression and tries to bind it to `pattern`: +```ocaml + let lazy_option_map f x = + match x with + | lazy (Some x) -> Some (Lazy.force f x) + | _ -> None +``` +Note: If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may be forced even outside of the case ultimately selected by the pattern matching. In the example above, the suspension `x` is always computed. +Note: `lazy_t` is the built-in type constructor used by the compiler for the `lazy` keyword. You should not use it directly. Always use `Lazy.t` instead. +Note: `Lazy.force` is not concurrency-safe. If you use this module with multiple fibers, systhreads or domains, then you will need to add some locks. The module however ensures memory-safety, and hence, concurrently accessing this module will not lead to a crash but the behaviour is unspecified. +Note: if the program is compiled with the `-rectypes` option, ill-founded recursive definitions of the form `let rec x = lazy x` or `let rec x = lazy(lazy(...(lazy x)))` are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the `-rectypes` option, such ill-founded recursive definitions are rejected by the type-checker. +``` +exception Undefined +``` +Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or when the suspension tries to force itself recursively. +``` +val force : 'a t -> 'a +``` +`force x` forces the suspension `x` and returns its result. If `x` has already been forced, `Lazy.force x` returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. +raises [`Undefined`](./#exception-Undefined) (see Undefined). +## Iterators +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f x` returns a suspension that, when forced, forces `x` and applies `f` to its value. +It is equivalent to `lazy (f (Lazy.force x))`. +since 4.13 +## Reasoning on already-forced suspensions +``` +val is_val : 'a t -> bool +``` +`is_val x` returns `true` if `x` has already been forced and did not raise an exception. +since 4.00 +``` +val from_val : 'a -> 'a t +``` +`from_val v` evaluates `v` first (as any function would) and returns an already-forced suspension of its result. It is the same as `let x = v in lazy x`, but uses dynamic tests to optimize suspension creation in some cases. +since 4.00 +``` +val map_val : ('a -> 'b) -> 'a t -> 'b t +``` +`map_val f x` applies `f` directly if `x` is already forced, otherwise it behaves as `map f x`. +When `x` is already forced, this behavior saves the construction of a suspension, but on the other hand it performs more work eagerly that may not be useful if you never force the function result. +If `f` raises an exception, it will be raised immediately when `is_val x`, or raised only when forcing the thunk otherwise. +If `map_val f x` does not raise an exception, then `is_val (map_val f x)` is equal to `is_val x`. +since 4.13 +## Advanced +The following definitions are for advanced uses only; they require familiarity with the lazy compilation scheme to be used appropriately. +``` +val from_fun : (unit -> 'a) -> 'a t +``` +`from_fun f` is the same as `lazy (f ())` but slightly more efficient. +It should only be used if the function `f` is already defined. In particular it is always less efficient to write `from_fun (fun () -> expr)` than `lazy expr`. +since 4.00 +``` +val force_val : 'a t -> 'a +``` +`force_val x` forces the suspension `x` and returns its result. If `x` has already been forced, `force_val x` returns the same value again without recomputing it. +If the computation of `x` raises an exception, it is unspecified whether `force_val x` raises the same exception or [`Undefined`](./#exception-Undefined). +raises [`Undefined`](./#exception-Undefined) if the forcing of x tries to force x itself recursively. +raises [`Undefined`](./#exception-Undefined) (see Undefined). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Lexing.md b/docs/api/melange/Stdlib-Lexing.md new file mode 100644 index 000000000..adf419b31 --- /dev/null +++ b/docs/api/melange/Stdlib-Lexing.md @@ -0,0 +1,104 @@ +# Module `Stdlib.Lexing` +The run-time library for lexers generated by `ocamllex`. +## Positions +``` +type position = { +``` +`pos_fname : string;` +`pos_lnum : int;` +`pos_bol : int;` +`pos_cnum : int;` +``` +} +``` +A value of type `position` describes a point in a source file. `pos_fname` is the file name; `pos_lnum` is the line number; `pos_bol` is the offset of the beginning of the line (number of characters between the beginning of the lexbuf and the beginning of the line); `pos_cnum` is the offset of the position (number of characters between the beginning of the lexbuf and the position). The difference between `pos_cnum` and `pos_bol` is the character offset within the line (i.e. the column number, assuming each character is one column wide). +See the documentation of type `lexbuf` for information about how the lexing engine will manage positions. +``` +val dummy_pos : position +``` +A value of type `position`, guaranteed to be different from any valid position. +## Lexer buffers +``` +type lexbuf = { +``` +`refill_buff : lexbuf -> unit;` +`mutable lex_buffer : bytes;` +`mutable lex_buffer_len : int;` +`mutable lex_abs_pos : int;` +`mutable lex_start_pos : int;` +`mutable lex_curr_pos : int;` +`mutable lex_last_pos : int;` +`mutable lex_last_action : int;` +`mutable lex_eof_reached : bool;` +`mutable lex_mem : int array;` +`mutable lex_start_p : position;` +`mutable lex_curr_p : position;` +``` +} +``` +The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input. +Lexers can optionally maintain the `lex_curr_p` and `lex_start_p` position fields. This "position tracking" mode is the default, and it corresponds to passing `~with_position:true` to functions that create lexer buffers. In this mode, the lexing engine and lexer actions are co-responsible for properly updating the position fields, as described in the next paragraph. When the mode is explicitly disabled (with `~with_position:false`), the lexing engine will not touch the position fields and the lexer actions should be careful not to do it either; the `lex_curr_p` and `lex_start_p` field will then always hold the `dummy_pos` invalid position. Not tracking positions avoids allocations and memory writes and can significantly improve the performance of the lexer in contexts where `lex_start_p` and `lex_curr_p` are not needed. +Position tracking mode works as follows. At each token, the lexing engine will copy `lex_curr_p` to `lex_start_p`, then change the `pos_cnum` field of `lex_curr_p` by updating it with the number of characters read since the start of the `lexbuf`. The other fields are left unchanged by the lexing engine. In order to keep them accurate, they must be initialised before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end of line \-- see also `new_line`). +``` +val from_channel : ?with_positions:bool -> in_channel -> lexbuf +``` +Create a lexer buffer on the given input channel. `Lexing.from_channel inchan` returns a lexer buffer which reads from the input channel `inchan`, at the current reading position. +``` +val from_string : ?with_positions:bool -> string -> lexbuf +``` +Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached. +``` +val from_function : ?with_positions:bool -> (bytes -> int -> int) -> lexbuf +``` +Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a byte sequence `s` and a byte count `n`. The function should put `n` bytes or fewer in `s`, starting at index 0, and return the number of bytes provided. A return value of 0 means end of input. +``` +val set_position : lexbuf -> position -> unit +``` +Set the initial tracked input position for `lexbuf` to a custom value. Ignores `pos_fname`. See [`set_filename`](./#val-set_filename) for changing this field. +since 4.11 +``` +val set_filename : lexbuf -> string -> unit +``` +Set filename in the initial tracked position to `file` in `lexbuf`. +since 4.11 +``` +val with_positions : lexbuf -> bool +``` +Tell whether the lexer buffer keeps track of position fields `lex_curr_p` / `lex_start_p`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`). +When `with_positions` is `false`, lexer actions should not modify position fields. Doing it nevertheless could re-enable the `with_position` mode and degrade performances. +## Functions for lexer semantic actions +The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument `lexbuf`, which, in the code generated by `ocamllex`, is bound to the lexer buffer passed to the parsing function. +``` +val lexeme : lexbuf -> string +``` +`Lexing.lexeme lexbuf` returns the string matched by the regular expression. +``` +val lexeme_char : lexbuf -> int -> char +``` +`Lexing.lexeme_char lexbuf i` returns character number `i` in the matched string. +``` +val lexeme_start : lexbuf -> int +``` +`Lexing.lexeme_start lexbuf` returns the offset in the input stream of the first character of the matched string. The first character of the stream has offset 0. +``` +val lexeme_end : lexbuf -> int +``` +`Lexing.lexeme_end lexbuf` returns the offset in the input stream of the character following the last character of the matched string. The first character of the stream has offset 0. +``` +val lexeme_start_p : lexbuf -> position +``` +Like `lexeme_start`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. +``` +val lexeme_end_p : lexbuf -> position +``` +Like `lexeme_end`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. +``` +val new_line : lexbuf -> unit +``` +Update the `lex_curr_p` field of the lexbuf to reflect the start of a new line. You can call this function in the semantic action of the rule that matches the end-of-line character. The function does nothing when position tracking is disabled. +since 3.11 +## Miscellaneous functions +``` +val flush_input : lexbuf -> unit +``` +Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-List.md b/docs/api/melange/Stdlib-List.md new file mode 100644 index 000000000..b5c404618 --- /dev/null +++ b/docs/api/melange/Stdlib-List.md @@ -0,0 +1,377 @@ +# Module `Stdlib.List` +List operations. +Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. +The above considerations can usually be ignored if your lists are not longer than about 10000 elements. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +``` +type 'a t = 'a list = +``` +``` +| [] +``` +``` +| :: of 'a * 'a list +``` +``` + +``` +An alias for the type of lists. +``` +val length : 'a list -> int +``` +Return the length (number of elements) of the given list. +``` +val compare_lengths : 'a list -> 'b list -> int +``` +Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. +since 4.05 +``` +val compare_length_with : 'a list -> int -> int +``` +Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. +since 4.05 +``` +val is_empty : 'a list -> bool +``` +`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. +since 5.1 +``` +val cons : 'a -> 'a list -> 'a list +``` +`cons x xs` is `x :: xs` +since 4.03 (4.05 in ListLabels) +``` +val hd : 'a list -> 'a +``` +Return the first element of the given list. +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val tl : 'a list -> 'a list +``` +Return the given list without its first element. +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val nth : 'a list -> int -> 'a +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +``` +val nth_opt : 'a list -> int -> 'a option +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.05 +``` +val rev : 'a list -> 'a list +``` +List reversal. +``` +val init : int -> (int -> 'a) -> 'a list +``` +`init len f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. +since 4.06 +``` +val append : 'a list -> 'a list -> 'a list +``` +`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. +since 5.1 this function is tail-recursive. +``` +val rev_append : 'a list -> 'a list -> 'a list +``` +`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. +``` +val concat : 'a list list -> 'a list +``` +Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). +``` +val flatten : 'a list list -> 'a list +``` +Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). +## Comparison +``` +val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool +``` +`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. +Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. +since 4.12 +``` +val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int +``` +`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): +- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` +- the empty list `[]` is strictly smaller than non-empty lists +Note: the `cmp` function will be called even if the lists have different lengths. +since 4.12 +## Iterators +``` +val iter : ('a -> unit) -> 'a list -> unit +``` +`iter f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. +``` +val iteri : (int -> 'a -> unit) -> 'a list -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 4.00 +``` +val map : ('a -> 'b) -> 'a list -> 'b list +``` +`map f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. +``` +val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 4.00 +``` +val rev_map : ('a -> 'b) -> 'a list -> 'b list +``` +`rev_map f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. +``` +val filter_map : ('a -> 'b option) -> 'a list -> 'b list +``` +`filter_map f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. +since 4.08 +``` +val concat_map : ('a -> 'b list) -> 'a list -> 'b list +``` +`concat_map f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. +since 4.10 +``` +val fold_left_map : + ('acc -> 'a -> 'acc * 'b) -> + 'acc -> + 'a list -> + 'acc * 'b list +``` +`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. +since 4.11 +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc +``` +`fold_left f init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. +``` +val fold_right : ('a -> 'acc -> 'acc) -> 'a list -> 'acc -> 'acc +``` +`fold_right f [a1; ...; an] init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. +## Iterators on two lists +``` +val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit +``` +`iter2 f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`map2 f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`rev_map2 f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. +``` +val fold_left2 : + ('acc -> 'a -> 'b -> 'acc) -> + 'acc -> + 'a list -> + 'b list -> + 'acc +``` +`fold_left2 f init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val fold_right2 : + ('a -> 'b -> 'acc -> 'acc) -> + 'a list -> + 'b list -> + 'acc -> + 'acc +``` +`fold_right2 f [a1; ...; an] [b1; ...; bn] init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. +## List scanning +``` +val for_all : ('a -> bool) -> 'a list -> bool +``` +`for_all f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. +``` +val exists : ('a -> bool) -> 'a list -> bool +``` +`exists f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. +``` +val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val mem : 'a -> 'a list -> bool +``` +`mem a set` is true if and only if `a` is equal to an element of `set`. +``` +val memq : 'a -> 'a list -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. +## List searching +``` +val find : ('a -> bool) -> 'a list -> 'a +``` +`find f l` returns the first element of the list `l` that satisfies the predicate `f`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. +``` +val find_opt : ('a -> bool) -> 'a list -> 'a option +``` +`find f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. +since 4.05 +``` +val find_index : ('a -> bool) -> 'a list -> int option +``` +`find_index f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. +It returns `None` if there is no such element. +since 5.1 +``` +val find_map : ('a -> 'b option) -> 'a list -> 'b option +``` +`find_map f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. +since 4.10 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a list -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 5.1 +``` +val filter : ('a -> bool) -> 'a list -> 'a list +``` +`filter f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. +``` +val find_all : ('a -> bool) -> 'a list -> 'a list +``` +`find_all` is another name for [`filter`](./#val-filter). +``` +val filteri : (int -> 'a -> bool) -> 'a list -> 'a list +``` +Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 4.11 +## List manipulation +``` +val take : int -> 'a list -> 'a list +``` +`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. +`n` must be nonnegative. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val drop : int -> 'a list -> 'a list +``` +`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. +`n` must be nonnegative. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val take_while : ('a -> bool) -> 'a list -> 'a list +``` +`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. +since 5.3 +``` +val drop_while : ('a -> bool) -> 'a list -> 'a list +``` +`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. +since 5.3 +``` +val partition : ('a -> bool) -> 'a list -> 'a list * 'a list +``` +`partition f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. +``` +val partition_map : ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list +``` +`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: +- if `f x` is `Left y1`, then `y1` is in `l1`, and +- if `f x` is `Right y2`, then `y2` is in `l2`. +The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. +In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. +since 4.12 +## Association lists +``` +val assoc : 'a -> ('a * 'b) list -> 'b +``` +`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. +``` +val assoc_opt : 'a -> ('a * 'b) list -> 'b option +``` +`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. +since 4.05 +``` +val assq : 'a -> ('a * 'b) list -> 'b +``` +Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. +``` +val assq_opt : 'a -> ('a * 'b) list -> 'b option +``` +Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. +since 4.05 +``` +val mem_assoc : 'a -> ('a * 'b) list -> bool +``` +Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. +``` +val mem_assq : 'a -> ('a * 'b) list -> bool +``` +Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. +``` +val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. +``` +val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. +## Lists of pairs +``` +val split : ('a * 'b) list -> 'a list * 'b list +``` +Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. +``` +val combine : 'a list -> 'b list -> ('a * 'b) list +``` +Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. +## Sorting +``` +val sort : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. +``` +val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. +``` +val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. +``` +val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but also remove duplicates. +since 4.02 (4.03 in ListLabels) +``` +val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list +``` +Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). +## Lists and Sequences +``` +val to_seq : 'a list -> 'a Seq.t +``` +Iterate on the list. +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a list +``` +Create a list from a sequence. +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-ListLabels.md b/docs/api/melange/Stdlib-ListLabels.md new file mode 100644 index 000000000..2ea636627 --- /dev/null +++ b/docs/api/melange/Stdlib-ListLabels.md @@ -0,0 +1,377 @@ +# Module `Stdlib.ListLabels` +List operations. +Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. +The above considerations can usually be ignored if your lists are not longer than about 10000 elements. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +``` +type 'a t = 'a list = +``` +``` +| [] +``` +``` +| :: of 'a * 'a list +``` +``` + +``` +An alias for the type of lists. +``` +val length : 'a list -> int +``` +Return the length (number of elements) of the given list. +``` +val compare_lengths : 'a list -> 'b list -> int +``` +Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. +since 4.05 +``` +val compare_length_with : 'a list -> len:int -> int +``` +Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. +since 4.05 +``` +val is_empty : 'a list -> bool +``` +`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. +since 5.1 +``` +val cons : 'a -> 'a list -> 'a list +``` +`cons x xs` is `x :: xs` +since 4.03 (4.05 in ListLabels) +``` +val hd : 'a list -> 'a +``` +Return the first element of the given list. +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val tl : 'a list -> 'a list +``` +Return the given list without its first element. +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val nth : 'a list -> int -> 'a +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +``` +val nth_opt : 'a list -> int -> 'a option +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.05 +``` +val rev : 'a list -> 'a list +``` +List reversal. +``` +val init : len:int -> f:(int -> 'a) -> 'a list +``` +`init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. +since 4.06 +``` +val append : 'a list -> 'a list -> 'a list +``` +`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. +since 5.1 this function is tail-recursive. +``` +val rev_append : 'a list -> 'a list -> 'a list +``` +`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. +``` +val concat : 'a list list -> 'a list +``` +Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). +``` +val flatten : 'a list list -> 'a list +``` +Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). +## Comparison +``` +val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool +``` +`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. +Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. +since 4.12 +``` +val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int +``` +`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): +- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` +- the empty list `[]` is strictly smaller than non-empty lists +Note: the `cmp` function will be called even if the lists have different lengths. +since 4.12 +## Iterators +``` +val iter : f:('a -> unit) -> 'a list -> unit +``` +`iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. +``` +val iteri : f:(int -> 'a -> unit) -> 'a list -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 4.00 +``` +val map : f:('a -> 'b) -> 'a list -> 'b list +``` +`map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. +``` +val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 4.00 +``` +val rev_map : f:('a -> 'b) -> 'a list -> 'b list +``` +`rev_map ~f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. +``` +val filter_map : f:('a -> 'b option) -> 'a list -> 'b list +``` +`filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. +since 4.08 +``` +val concat_map : f:('a -> 'b list) -> 'a list -> 'b list +``` +`concat_map ~f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. +since 4.10 +``` +val fold_left_map : + f:('acc -> 'a -> 'acc * 'b) -> + init:'acc -> + 'a list -> + 'acc * 'b list +``` +`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. +since 4.11 +``` +val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc +``` +`fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. +``` +val fold_right : f:('a -> 'acc -> 'acc) -> 'a list -> init:'acc -> 'acc +``` +`fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. +## Iterators on two lists +``` +val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit +``` +`iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`rev_map2 ~f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. +``` +val fold_left2 : + f:('acc -> 'a -> 'b -> 'acc) -> + init:'acc -> + 'a list -> + 'b list -> + 'acc +``` +`fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val fold_right2 : + f:('a -> 'b -> 'acc -> 'acc) -> + 'a list -> + 'b list -> + init:'acc -> + 'acc +``` +`fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. +## List scanning +``` +val for_all : f:('a -> bool) -> 'a list -> bool +``` +`for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. +``` +val exists : f:('a -> bool) -> 'a list -> bool +``` +`exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. +``` +val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val mem : 'a -> set:'a list -> bool +``` +`mem a ~set` is true if and only if `a` is equal to an element of `set`. +``` +val memq : 'a -> set:'a list -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. +## List searching +``` +val find : f:('a -> bool) -> 'a list -> 'a +``` +`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. +``` +val find_opt : f:('a -> bool) -> 'a list -> 'a option +``` +`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. +since 4.05 +``` +val find_index : f:('a -> bool) -> 'a list -> int option +``` +`find_index ~f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. +It returns `None` if there is no such element. +since 5.1 +``` +val find_map : f:('a -> 'b option) -> 'a list -> 'b option +``` +`find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. +since 4.10 +``` +val find_mapi : f:(int -> 'a -> 'b option) -> 'a list -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 5.1 +``` +val filter : f:('a -> bool) -> 'a list -> 'a list +``` +`filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. +``` +val find_all : f:('a -> bool) -> 'a list -> 'a list +``` +`find_all` is another name for [`filter`](./#val-filter). +``` +val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list +``` +Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +since 4.11 +## List manipulation +``` +val take : int -> 'a list -> 'a list +``` +`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. +`n` must be nonnegative. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val drop : int -> 'a list -> 'a list +``` +`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. +`n` must be nonnegative. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val take_while : f:('a -> bool) -> 'a list -> 'a list +``` +`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. +since 5.3 +``` +val drop_while : f:('a -> bool) -> 'a list -> 'a list +``` +`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. +since 5.3 +``` +val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list +``` +`partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. +``` +val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list +``` +`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: +- if `f x` is `Left y1`, then `y1` is in `l1`, and +- if `f x` is `Right y2`, then `y2` is in `l2`. +The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. +In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. +since 4.12 +## Association lists +``` +val assoc : 'a -> ('a * 'b) list -> 'b +``` +`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. +``` +val assoc_opt : 'a -> ('a * 'b) list -> 'b option +``` +`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. +since 4.05 +``` +val assq : 'a -> ('a * 'b) list -> 'b +``` +Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. +``` +val assq_opt : 'a -> ('a * 'b) list -> 'b option +``` +Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. +since 4.05 +``` +val mem_assoc : 'a -> map:('a * 'b) list -> bool +``` +Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. +``` +val mem_assq : 'a -> map:('a * 'b) list -> bool +``` +Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. +``` +val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. +``` +val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. +## Lists of pairs +``` +val split : ('a * 'b) list -> 'a list * 'b list +``` +Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. +``` +val combine : 'a list -> 'b list -> ('a * 'b) list +``` +Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. +## Sorting +``` +val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. +``` +val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. +``` +val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. +``` +val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but also remove duplicates. +since 4.02 (4.03 in ListLabels) +``` +val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list +``` +Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). +## Lists and Sequences +``` +val to_seq : 'a list -> 'a Seq.t +``` +Iterate on the list. +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a list +``` +Create a list from a sequence. +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md new file mode 100644 index 000000000..6fcf99036 --- /dev/null +++ b/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md @@ -0,0 +1,9 @@ +# Parameter `Make.Ord` +``` +type t +``` +The type of the map keys. +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map-Make.md b/docs/api/melange/Stdlib-Map-Make.md new file mode 100644 index 000000000..712cb4188 --- /dev/null +++ b/docs/api/melange/Stdlib-Map-Make.md @@ -0,0 +1,246 @@ +# Module `Map.Make` +Functor building an implementation of the map structure given a totally ordered type. +## Parameters +``` +module Ord : OrderedType +``` +## Signature +## Maps +``` +type key = Ord.t +``` +The type of the map keys. +``` +type !+'a t +``` +The type of maps from type `key` to type `'a`. +``` +val empty : 'a t +``` +The empty map. +``` +val add : key -> 'a -> 'a t -> 'a t +``` +`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key -> 'a -> 'a list t -> 'a list t +``` +`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. +since 5.1 +``` +val update : key -> ('a option -> 'a option) -> 'a t -> 'a t +``` +`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +before 4.03 Physical equality was not ensured. +``` +val merge : + (key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. +since 3.12 +``` +val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. +since 3.12 +## Bindings +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 4.05 +## Searching +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. +since 4.05 +``` +val find_first : (key -> bool) -> 'a t -> key * 'a +``` +`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. +since 4.05 +``` +val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +``` +val find_last : (key -> bool) -> 'a t -> key * 'a +``` +`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. +since 4.05 +``` +val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +## Traversing +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +## Transforming +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. +``` +val filter : (key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. +since 4.11 +``` +val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +since 3.12 +## Predicates and comparisons +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. +``` +val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. +``` +val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. +``` +val for_all : (key -> 'a -> bool) -> 'a t -> bool +``` +`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. +since 3.12 +``` +val exists : (key -> 'a -> bool) -> 'a t -> bool +``` +`exists f m` checks if at least one binding of the map satisfies the predicate `f`. +since 3.12 +## Converting +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map-module-type-OrderedType.md b/docs/api/melange/Stdlib-Map-module-type-OrderedType.md new file mode 100644 index 000000000..5e6859113 --- /dev/null +++ b/docs/api/melange/Stdlib-Map-module-type-OrderedType.md @@ -0,0 +1,10 @@ +# Module type `Map.OrderedType` +Input signature of the functor [`Make`](./Stdlib-Map-Make.md). +``` +type t +``` +The type of the map keys. +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map-module-type-S.md b/docs/api/melange/Stdlib-Map-module-type-S.md new file mode 100644 index 000000000..cc3c77be4 --- /dev/null +++ b/docs/api/melange/Stdlib-Map-module-type-S.md @@ -0,0 +1,241 @@ +# Module type `Map.S` +Output signature of the functor [`Make`](./Stdlib-Map-Make.md). +## Maps +``` +type key +``` +The type of the map keys. +``` +type !+'a t +``` +The type of maps from type `key` to type `'a`. +``` +val empty : 'a t +``` +The empty map. +``` +val add : key -> 'a -> 'a t -> 'a t +``` +`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key -> 'a -> 'a list t -> 'a list t +``` +`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. +since 5.1 +``` +val update : key -> ('a option -> 'a option) -> 'a t -> 'a t +``` +`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +before 4.03 Physical equality was not ensured. +``` +val merge : + (key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. +since 3.12 +``` +val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. +since 3.12 +## Bindings +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-Map-Make.md). +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 4.05 +## Searching +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. +since 4.05 +``` +val find_first : (key -> bool) -> 'a t -> key * 'a +``` +`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. +since 4.05 +``` +val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +``` +val find_last : (key -> bool) -> 'a t -> key * 'a +``` +`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. +since 4.05 +``` +val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +## Traversing +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +## Transforming +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. +``` +val filter : (key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. +since 4.11 +``` +val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +since 3.12 +## Predicates and comparisons +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. +``` +val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. +``` +val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. +``` +val for_all : (key -> 'a -> bool) -> 'a t -> bool +``` +`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. +since 3.12 +``` +val exists : (key -> 'a -> bool) -> 'a t -> bool +``` +`exists f m` checks if at least one binding of the map satisfies the predicate `f`. +since 3.12 +## Converting +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map.md b/docs/api/melange/Stdlib-Map.md new file mode 100644 index 000000000..1593aa278 --- /dev/null +++ b/docs/api/melange/Stdlib-Map.md @@ -0,0 +1,31 @@ +# Module `Stdlib.Map` +Association tables over ordered types. +This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. +For instance: +```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") +``` +This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-Map-Make.md). +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-Map-Make.md). +``` +module Make (Ord : OrderedType) : S with type key = Ord.t +``` +Functor building an implementation of the map structure given a totally ordered type. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Marshal.md b/docs/api/melange/Stdlib-Marshal.md new file mode 100644 index 000000000..af037840f --- /dev/null +++ b/docs/api/melange/Stdlib-Marshal.md @@ -0,0 +1,78 @@ +# Module `Stdlib.Marshal` +Marshaling of data structures. +This module provides functions to encode arbitrary data structures as sequences of bytes, which can then be written on a file or sent over a pipe or network connection. The bytes can then be read back later, possibly in another process, and decoded back into a data structure. The format for the byte sequences is compatible across all machines for a given version of OCaml. +Warning: marshaling is currently not type-safe. The type of marshaled data is not transmitted along the value of the data, making it impossible to check that the data read back possesses the type expected by the context. In particular, the result type of the `Marshal.from_*` functions is given as `'a`, but this is misleading: the returned OCaml value does not possess type `'a` for all `'a`; it has one, unique type which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax: +- `(Marshal.from_channel chan : type)`. Anything can happen at run-time if the object in the file does not belong to the given type. +Values of extensible variant types, for example exceptions (of extensible type `exn`), returned by the unmarshaller should not be pattern-matched over through `match ... with` or `try ... with`, because unmarshalling does not preserve the information required for matching their constructors. Structural equalities with other extensible variant values does not work either. Most other uses such as Printexc.to\_string, will still work as expected. +The representation of marshaled values is not human-readable, and uses bytes that are not printable characters. Therefore, input and output channels used in conjunction with `Marshal.to_channel` and `Marshal.from_channel` must be opened in binary mode, using e.g. `open_out_bin` or `open_in_bin`; channels opened in text mode will cause unmarshaling errors on platforms where text channels behave differently than binary channels, e.g. Windows. +``` +type extern_flags = +``` +``` +| No_sharing +``` +Don't preserve sharing +``` +| Closures +``` +Send function closures +``` +| Compat_32 +``` +Ensure 32-bit compatibility +``` + +``` +The flags to the `Marshal.to_*` functions below. +``` +val to_channel : out_channel -> 'a -> extern_flags list -> unit +``` +`Marshal.to_channel chan v flags` writes the representation of `v` on channel `chan`. The `flags` argument is a possibly empty list of flags that governs the marshaling behavior with respect to sharing, functional values, and compatibility between 32- and 64-bit platforms. +If `flags` does not contain `Marshal.No_sharing`, circularities and sharing inside the value `v` are detected and preserved in the sequence of bytes produced. In particular, this guarantees that marshaling always terminates. Sharing between values marshaled by successive calls to `Marshal.to_channel` is neither detected nor preserved, though. If `flags` contains `Marshal.No_sharing`, sharing is ignored. This results in faster marshaling if `v` contains no shared substructures, but may cause slower marshaling and larger byte representations if `v` actually contains sharing, or even non-termination if `v` contains cycles. +If `flags` does not contain `Marshal.Closures`, marshaling fails when it encounters a functional value inside `v`: only 'pure' data structures, containing neither functions nor objects, can safely be transmitted between different programs. If `flags` contains `Marshal.Closures`, functional values will be marshaled as a the position in the code of the program together with the values corresponding to the free variables captured in the closure. In this case, the output of marshaling can only be read back in processes that run exactly the same program, with exactly the same compiled code. (This is checked at un-marshaling time, using an MD5 digest of the code transmitted along with the code position.) +The exact definition of which free variables are captured in a closure is not specified and can vary between bytecode and native code (and according to optimization flags). In particular, a function value accessing a global reference may or may not include the reference in its closure. If it does, unmarshaling the corresponding closure will create a new reference, different from the global one. +If `flags` contains `Marshal.Compat_32`, marshaling fails when it encounters an integer value outside the range `-2``30`, `2``30``-1` of integers that are representable on a 32-bit platform. This ensures that marshaled data generated on a 64-bit platform can be safely read back on a 32-bit platform. If `flags` does not contain `Marshal.Compat_32`, integer values outside the range `-2``30`, `2``30``-1` are marshaled, and can be read back on a 64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit platform. The `Mashal.Compat_32` flag only matters when marshaling is performed on a 64-bit platform; it has no effect if marshaling is performed on a 32-bit platform. +raises [`Failure`](./Stdlib.md#exception-Failure) if chan is not in binary mode. +``` +val to_bytes : 'a -> extern_flags list -> bytes +``` +`Marshal.to_bytes v flags` returns a byte sequence containing the representation of `v`. The `flags` argument has the same meaning as for [`Marshal.to_channel`](./#val-to_channel). +since 4.02 +``` +val to_string : 'a -> extern_flags list -> string +``` +Same as `to_bytes` but return the result as a string instead of a byte sequence. +``` +val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int +``` +`Marshal.to_buffer buff ofs len v flags` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. It returns the number of bytes actually written to the sequence. If the byte representation of `v` does not fit in `len` characters, the exception `Failure` is raised. +``` +val from_channel : in_channel -> 'a +``` +`Marshal.from_channel chan` reads from channel `chan` the byte representation of a structured value, as produced by one of the `Marshal.to_*` functions, and reconstructs and returns the corresponding value. +raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if chan is already at the end of the file. +raises [`Failure`](./Stdlib.md#exception-Failure) if the end of the file is reached during unmarshalling itself or if chan is not in binary mode. +``` +val from_bytes : bytes -> int -> 'a +``` +`Marshal.from_bytes buff ofs` unmarshals a structured value like [`Marshal.from_channel`](./#val-from_channel) does, except that the byte representation is not read from a channel, but taken from the byte sequence `buff`, starting at position `ofs`. The byte sequence is not mutated. +since 4.02 +``` +val from_string : string -> int -> 'a +``` +Same as `from_bytes` but take a string as argument instead of a byte sequence. +``` +val header_size : int +``` +The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header. [`Marshal.header_size`](./#val-header_size) is the size, in bytes, of the header. [`Marshal.data_size`](./#val-data_size)` buff ofs` is the size, in bytes, of the data part, assuming a valid header is stored in `buff` starting at position `ofs`. Finally, [`Marshal.total_size`](./#val-total_size) `buff ofs` is the total size, in bytes, of the marshaled value. Both [`Marshal.data_size`](./#val-data_size) and [`Marshal.total_size`](./#val-total_size) raise `Failure` if `buff`, `ofs` does not contain a valid header. +To read the byte representation of a marshaled value into a byte sequence, the program needs to read first [`Marshal.header_size`](./#val-header_size) bytes into the sequence, then determine the length of the remainder of the representation using [`Marshal.data_size`](./#val-data_size), make sure the sequence is large enough to hold the remaining data, then read it, and finally call [`Marshal.from_bytes`](./#val-from_bytes) to unmarshal the value. +``` +val data_size : bytes -> int -> int +``` +See [`Marshal.header_size`](./#val-header_size). +``` +val total_size : bytes -> int -> int +``` +See [`Marshal.header_size`](./#val-header_size). +## Marshal and domain safety +Care must be taken when marshaling a mutable value that may be modified by a different domain. Mutating a value that is being marshaled (i.e., turned into a sequence of bytes) is a programming error and might result in surprising values (when unmarshaling) due to tearing, since marshaling involves byte-per-byte copy. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md new file mode 100644 index 000000000..492b57f0f --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md @@ -0,0 +1,16 @@ +# Parameter `Make.H` +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md new file mode 100644 index 000000000..cd745f1cb --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md @@ -0,0 +1,89 @@ +# Module `Hashtbl.Make` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. +## Parameters +``` +module H : HashedType +``` +## Signature +``` +type key = H.t +``` +``` +type 'a t = 'a Hashtbl.Make(H).t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md new file mode 100644 index 000000000..e0b262332 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md @@ -0,0 +1,13 @@ +# Parameter `MakeSeeded.H` +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md new file mode 100644 index 000000000..39a9f6885 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md @@ -0,0 +1,88 @@ +# Module `Hashtbl.MakeSeeded` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-MoreLabels-Hashtbl.md#val-randomize)). +since 4.00 +## Parameters +``` +module H : SeededHashedType +``` +## Signature +``` +type key = H.t +``` +``` +type 'a t = 'a Hashtbl.MakeSeeded(H).t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md new file mode 100644 index 000000000..0a6c34cdd --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md @@ -0,0 +1,17 @@ +# Module type `Hashtbl.HashedType` +The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md new file mode 100644 index 000000000..772d73ee6 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md @@ -0,0 +1,84 @@ +# Module type `Hashtbl.S` +The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). +``` +type key +``` +``` +type !'a t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md new file mode 100644 index 000000000..3cdf7fe07 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md @@ -0,0 +1,15 @@ +# Module type `Hashtbl.SeededHashedType` +The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). +since 4.00 +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md new file mode 100644 index 000000000..044f1bf40 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md @@ -0,0 +1,83 @@ +# Module type `Hashtbl.SeededS` +The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). +since 4.00 +``` +type key +``` +``` +type !'a t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md new file mode 100644 index 000000000..e8a2e3f9d --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md @@ -0,0 +1,312 @@ +# Module `MoreLabels.Hashtbl` +Hash tables and hash functions. +Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-MoreLabels-Map.md). +The functors [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. +**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. +The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. +See [the examples section](./#examples). +**Unsynchronized accesses** +Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +## Generic interface +``` +type (!'a, !'b) t = ('a, 'b) Hashtbl.t +``` +The type of hash tables from type `'a` to type `'b`. +``` +val create : ?random:bool -> int -> ('a, 'b) t +``` +`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. +A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. +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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. +before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. +``` +val clear : ('a, 'b) t -> unit +``` +Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. +``` +val reset : ('a, 'b) t -> unit +``` +Empty a hash table and shrink the size of the bucket table to its initial size. +since 4.00 +``` +val copy : ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. +``` +val add : ('a, 'b) t -> key:'a -> data:'b -> unit +``` +`Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`. +**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) +If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). +``` +val find : ('a, 'b) t -> 'a -> 'b +``` +`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. +``` +val find_opt : ('a, 'b) t -> 'a -> 'b option +``` +`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. +since 4.05 +``` +val find_all : ('a, 'b) t -> 'a -> 'b list +``` +`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. +``` +val mem : ('a, 'b) t -> 'a -> bool +``` +`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. +``` +val remove : ('a, 'b) t -> 'a -> unit +``` +`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. +``` +val replace : ('a, 'b) t -> key:'a -> data:'b -> unit +``` +`Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. +``` +val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit +``` +`Hashtbl.iter ~f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. +The behavior is not specified if the hash table is modified by `f` during the iteration. +``` +val filter_map_inplace : + f:(key:'a -> data:'b -> 'b option) -> + ('a, 'b) t -> + unit +``` +`Hashtbl.filter_map_inplace ~f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. +Other comments for [`iter`](./#val-iter) apply as well. +since 4.03 +``` +val fold : + f:(key:'a -> data:'b -> 'acc -> 'acc) -> + ('a, 'b) t -> + init:'acc -> + 'acc +``` +`Hashtbl.fold ~f tbl ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. +The behavior is not specified if the hash table is modified by `f` during the iteration. +``` +val length : ('a, 'b) t -> int +``` +`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. +``` +val randomize : unit -> unit +``` +After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. +It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. +Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. +since 4.00 +``` +val is_randomized : unit -> bool +``` +Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. +since 4.03 +``` +val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. +[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. +since 4.12 +``` +type statistics = Hashtbl.statistics = { +``` +`num_bindings : int;` +Number of bindings present in the table. Same value as returned by [`length`](./#val-length). +`num_buckets : int;` +Number of buckets in the table. +`max_bucket_length : int;` +Maximal number of bindings per bucket. +`bucket_histogram : int array;` +Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. +``` +} +``` +since 4.00 +``` +val stats : ('a, 'b) t -> statistics +``` +`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. +since 4.00 +## Hash tables and Sequences +``` +val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t +``` +Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. +The behavior is not specified if the hash table is modified during the iteration. +since 4.07 +``` +val to_seq_keys : ('a, _) t -> 'a Seq.t +``` +Same as `Seq.map fst (to_seq m)` +since 4.07 +``` +val to_seq_values : (_, 'b) t -> 'b Seq.t +``` +Same as `Seq.map snd (to_seq m)` +since 4.07 +``` +val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`add`](./#val-add) +since 4.07 +``` +val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`replace`](./#val-replace) +since 4.07 +``` +val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t +``` +Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. +since 4.07 +## Functorial interface +The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. +For instance, one might want to specialize a table for integer keys: +```ocaml + module IntHash = + struct + type t = int + let equal i j = i=j + let hash i = i land max_int + end + + module IntHashtbl = Hashtbl.Make(IntHash) + + let h = IntHashtbl.create 17 in + IntHashtbl.add h 12 "hello" +``` +This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. +Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. +``` +module type HashedType = sig ... end +``` +The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). +``` +module type S = sig ... end +``` +The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). +``` +module Make + (H : HashedType) : + S with type key = H.t and type 'a t = 'a Hashtbl.Make(H).t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. +``` +module type SeededHashedType = sig ... end +``` +The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). +``` +module type SeededS = sig ... end +``` +The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). +``` +module MakeSeeded + (H : SeededHashedType) : + SeededS with type key = H.t and type 'a t = 'a Hashtbl.MakeSeeded(H).t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). +## The polymorphic hash functions +``` +val hash : 'a -> int +``` +`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. +``` +val seeded_hash : int -> 'a -> int +``` +A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. +since 4.00 +``` +val hash_param : int -> int -> 'a -> int +``` +`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. +``` +val seeded_hash_param : int -> int -> int -> 'a -> int +``` +A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. +since 4.00 +## 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 + 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 +``` +### Counting Elements +Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. +Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. +```ocaml + # module Char_tbl = Hashtbl.Make(struct + type t = char + let equal = Char.equal + let hash = Hashtbl.hash + end) + + (* count distinct occurrences of chars in [seq] *) + # let count_chars (seq : char Seq.t) : _ list = + let counts = Char_tbl.create 16 in + Seq.iter + (fun c -> + let count_c = + Char_tbl.find_opt counts c + |> Option.value ~default:0 + in + Char_tbl.replace counts c (count_c + 1)) + seq; + (* turn into a list *) + Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] + |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) + val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = + + (* basic seq from a string *) + # let seq = String.to_seq "hello world, and all the camels in it!" + val seq : char Seq.t = + + # count_chars seq + - : (Char.t * int) list = + [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); + ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); + ('s', 1); ('t', 2); ('w', 1)] + + (* "abcabcabc..." *) + # let seq2 = + Seq.cycle (String.to_seq "abc") |> Seq.take 31 + val seq2 : char Seq.t = + + # String.of_seq seq2 + - : String.t = "abcabcabcabcabcabcabcabcabcabca" + + # count_chars seq2 + - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] + +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md new file mode 100644 index 000000000..6fcf99036 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md @@ -0,0 +1,9 @@ +# Parameter `Make.Ord` +``` +type t +``` +The type of the map keys. +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-Make.md b/docs/api/melange/Stdlib-MoreLabels-Map-Make.md new file mode 100644 index 000000000..d056acc17 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Map-Make.md @@ -0,0 +1,246 @@ +# Module `Map.Make` +Functor building an implementation of the map structure given a totally ordered type. +## Parameters +``` +module Ord : OrderedType +``` +## Signature +## Maps +``` +type key = Ord.t +``` +The type of the map keys. +``` +type 'a t = 'a Map.Make(Ord).t +``` +The type of maps from type `key` to type `'a`. +``` +val empty : 'a t +``` +The empty map. +``` +val add : key:key -> data:'a -> 'a t -> 'a t +``` +`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t +``` +`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. +since 5.1 +``` +val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t +``` +`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +before 4.03 Physical equality was not ensured. +``` +val merge : + f:(key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. +since 3.12 +``` +val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. +since 3.12 +## Bindings +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 4.05 +## Searching +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. +since 4.05 +``` +val find_first : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. +since 4.05 +``` +val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +``` +val find_last : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. +since 4.05 +``` +val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +## Traversing +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +## Transforming +``` +val map : f:('a -> 'b) -> 'a t -> 'b t +``` +`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. +``` +val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. +since 4.11 +``` +val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +since 3.12 +## Predicates and comparisons +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. +``` +val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. +``` +val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. +``` +val for_all : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. +since 3.12 +``` +val exists : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. +since 3.12 +## Converting +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md new file mode 100644 index 000000000..c8268b5ae --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md @@ -0,0 +1,10 @@ +# Module type `Map.OrderedType` +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). +``` +type t +``` +The type of the map keys. +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md new file mode 100644 index 000000000..2444c85f0 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md @@ -0,0 +1,241 @@ +# Module type `Map.S` +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). +## Maps +``` +type key +``` +The type of the map keys. +``` +type !+'a t +``` +The type of maps from type `key` to type `'a`. +``` +val empty : 'a t +``` +The empty map. +``` +val add : key:key -> data:'a -> 'a t -> 'a t +``` +`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t +``` +`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. +since 5.1 +``` +val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t +``` +`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). +before 4.03 Physical equality was not ensured. +``` +val merge : + f:(key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. +since 3.12 +``` +val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. +since 3.12 +## Bindings +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-MoreLabels-Map-Make.md). +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. +since 4.05 +## Searching +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. +since 4.05 +``` +val find_first : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. +since 4.05 +``` +val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +``` +val find_last : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. +since 4.05 +``` +val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. +since 4.05 +## Traversing +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. +## Transforming +``` +val map : f:('a -> 'b) -> 'a t -> 'b t +``` +`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. +``` +val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. +``` +val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. +since 4.11 +``` +val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. +since 3.12 +## Predicates and comparisons +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. +``` +val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. +``` +val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. +``` +val for_all : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. +since 3.12 +``` +val exists : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. +since 3.12 +## Converting +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Map.md b/docs/api/melange/Stdlib-MoreLabels-Map.md new file mode 100644 index 000000000..c331af125 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Map.md @@ -0,0 +1,33 @@ +# Module `MoreLabels.Map` +Association tables over ordered types. +This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. +For instance: +```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") +``` +This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). +``` +module Make + (Ord : OrderedType) : + S with type key = Ord.t and type 'a t = 'a Map.Make(Ord).t +``` +Functor building an implementation of the map structure given a totally ordered type. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md new file mode 100644 index 000000000..bce17bb85 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md @@ -0,0 +1,9 @@ +# Parameter `Make.Ord` +``` +type t +``` +The type of the set elements. +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-Make.md b/docs/api/melange/Stdlib-MoreLabels-Set-Make.md new file mode 100644 index 000000000..7a13ff86d --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Set-Make.md @@ -0,0 +1,225 @@ +# Module `Set.Make` +Functor building an implementation of the set structure given a totally ordered type. +## Parameters +``` +module Ord : OrderedType +``` +## Signature +## Sets +``` +type elt = Ord.t +``` +The type of the set elements. +``` +type t = Set.Make(Ord).t +``` +The type of sets. +``` +val empty : t +``` +The empty set. +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. +``` +val inter : t -> t -> t +``` +Set intersection. +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. +``` +val cardinal : t -> int +``` +Return the number of elements of a set. +## Elements +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +since 4.05 +## Searching +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. +since 4.05 +``` +val find_first : f:(elt -> bool) -> t -> elt +``` +`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. +since 4.05 +``` +val find_first_opt : f:(elt -> bool) -> t -> elt option +``` +`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +``` +val find_last : f:(elt -> bool) -> t -> elt +``` +`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +since 4.05 +``` +val find_last_opt : f:(elt -> bool) -> t -> elt option +``` +`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +## Traversing +``` +val iter : f:(elt -> unit) -> t -> unit +``` +`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. +``` +val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc +``` +`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. +## Transforming +``` +val map : f:(elt -> elt) -> t -> t +``` +`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) +since 4.04 +``` +val filter : f:(elt -> bool) -> t -> t +``` +`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(elt -> elt option) -> t -> t +``` +`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. +For example, +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. +since 4.11 +``` +val partition : f:(elt -> bool) -> t -> t * t +``` +`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. +## Predicates and comparisons +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. +``` +val for_all : f:(elt -> bool) -> t -> bool +``` +`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. +``` +val exists : f:(elt -> bool) -> t -> bool +``` +`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. +## Converting +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md new file mode 100644 index 000000000..7e93c469f --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md @@ -0,0 +1,10 @@ +# Module type `Set.OrderedType` +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). +``` +type t +``` +The type of the set elements. +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md new file mode 100644 index 000000000..1de8581e3 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md @@ -0,0 +1,220 @@ +# Module type `Set.S` +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). +## Sets +``` +type elt +``` +The type of the set elements. +``` +type t +``` +The type of sets. +``` +val empty : t +``` +The empty set. +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. +``` +val inter : t -> t -> t +``` +Set intersection. +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. +``` +val cardinal : t -> int +``` +Return the number of elements of a set. +## Elements +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-MoreLabels-Set-Make.md). +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +since 4.05 +## Searching +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. +since 4.05 +``` +val find_first : f:(elt -> bool) -> t -> elt +``` +`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. +since 4.05 +``` +val find_first_opt : f:(elt -> bool) -> t -> elt option +``` +`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +``` +val find_last : f:(elt -> bool) -> t -> elt +``` +`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +since 4.05 +``` +val find_last_opt : f:(elt -> bool) -> t -> elt option +``` +`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +## Traversing +``` +val iter : f:(elt -> unit) -> t -> unit +``` +`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. +``` +val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc +``` +`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. +## Transforming +``` +val map : f:(elt -> elt) -> t -> t +``` +`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) +since 4.04 +``` +val filter : f:(elt -> bool) -> t -> t +``` +`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(elt -> elt option) -> t -> t +``` +`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. +For example, +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. +since 4.11 +``` +val partition : f:(elt -> bool) -> t -> t * t +``` +`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. +## Predicates and comparisons +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. +``` +val for_all : f:(elt -> bool) -> t -> bool +``` +`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. +``` +val exists : f:(elt -> bool) -> t -> bool +``` +`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. +## Converting +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Set.md b/docs/api/melange/Stdlib-MoreLabels-Set.md new file mode 100644 index 000000000..5a9665c53 --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels-Set.md @@ -0,0 +1,33 @@ +# Module `MoreLabels.Set` +Sets over ordered types. +This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. +The [`Make`](./Stdlib-MoreLabels-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: +```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 PairsSet = Set.Make(IntPairs) + + let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) +``` +This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). +``` +module Make + (Ord : OrderedType) : + S with type elt = Ord.t and type t = Set.Make(Ord).t +``` +Functor building an implementation of the set structure given a totally ordered type. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels.md b/docs/api/melange/Stdlib-MoreLabels.md new file mode 100644 index 000000000..8037ad8cb --- /dev/null +++ b/docs/api/melange/Stdlib-MoreLabels.md @@ -0,0 +1,22 @@ +# Module `Stdlib.MoreLabels` +Extra labeled libraries. +This meta-module provides labelized versions of the [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md) and [`Set`](./Stdlib-MoreLabels-Set.md) modules. +This module is intended to be used through `open MoreLabels` which replaces [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md), and [`Set`](./Stdlib-MoreLabels-Set.md) with their labeled counterparts. +For example: +```ocaml + open MoreLabels + + Hashtbl.iter ~f:(fun ~key ~data -> g key data) table +``` +``` +module Hashtbl : sig ... end +``` +Hash tables and hash functions. +``` +module Map : sig ... end +``` +Association tables over ordered types. +``` +module Set : sig ... end +``` +Sets over ordered types. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Mutex.md b/docs/api/melange/Stdlib-Mutex.md new file mode 100644 index 000000000..6f93f481d --- /dev/null +++ b/docs/api/melange/Stdlib-Mutex.md @@ -0,0 +1,38 @@ +# Module `Stdlib.Mutex` +Locks for mutual exclusion. +Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if `m` is the mutex associated with the data structure `D`): +```ocaml + Mutex.lock m; + (* Critical section that operates over D *); + Mutex.unlock m +``` +``` +type t +``` +The type of mutexes. +``` +val create : unit -> t +``` +Return a new mutex. +``` +val lock : t -> unit +``` +Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex. +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is already locked by the thread calling Mutex.lock. +before 4.12 Sys\_error was not raised for recursive locking (platform-dependent behaviour) +``` +val try_lock : t -> bool +``` +Same as [`Mutex.lock`](./#val-lock), but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. If the mutex is unlocked, lock it and return `true`. +``` +val unlock : t -> unit +``` +Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. The mutex must have been previously locked by the thread that calls [`Mutex.unlock`](./#val-unlock). +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is unlocked or was locked by another thread. +before 4.12 Sys\_error was not raised when unlocking an unlocked mutex or when unlocking a mutex from a different thread. +``` +val protect : t -> (unit -> 'a) -> 'a +``` +`protect mutex f` runs `f()` in a critical section where `mutex` is locked (using [`lock`](./#val-lock)); it then takes care of releasing `mutex`, whether `f()` returned a value or raised an exception. +The unlocking operation is guaranteed to always takes place, even in the event an asynchronous exception (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)) is raised in some signal handler. +since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Obj-Ephemeron.md b/docs/api/melange/Stdlib-Obj-Ephemeron.md new file mode 100644 index 000000000..80b05826d --- /dev/null +++ b/docs/api/melange/Stdlib-Obj-Ephemeron.md @@ -0,0 +1,58 @@ +# Module `Obj.Ephemeron` +Ephemeron with arbitrary arity and untyped +``` +type obj_t = t +``` +alias for [`Obj.t`](./Stdlib-Obj.md#type-t) +``` +type t +``` +an ephemeron cf [`Ephemeron`](#) +``` +val create : int -> t +``` +`create n` returns an ephemeron with `n` keys. All the keys and the data are initially empty. The argument `n` must be between zero and [`max_ephe_length`](./#val-max_ephe_length) (limits included). +``` +val length : t -> int +``` +return the number of keys +``` +val get_key : t -> int -> obj_t option +``` +``` +val get_key_copy : t -> int -> obj_t option +``` +``` +val set_key : t -> int -> obj_t -> unit +``` +``` +val unset_key : t -> int -> unit +``` +``` +val check_key : t -> int -> bool +``` +``` +val blit_key : t -> int -> t -> int -> int -> unit +``` +``` +val get_data : t -> obj_t option +``` +``` +val get_data_copy : t -> obj_t option +``` +``` +val set_data : t -> obj_t -> unit +``` +``` +val unset_data : t -> unit +``` +``` +val check_data : t -> bool +``` +``` +val blit_data : t -> t -> unit +``` +``` +val max_ephe_length : int +``` +Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Obj-Extension_constructor.md b/docs/api/melange/Stdlib-Obj-Extension_constructor.md new file mode 100644 index 000000000..a008cdace --- /dev/null +++ b/docs/api/melange/Stdlib-Obj-Extension_constructor.md @@ -0,0 +1,13 @@ +# Module `Obj.Extension_constructor` +``` +type t = extension_constructor +``` +``` +val of_val : 'a -> t +``` +``` +val name : t -> string +``` +``` +val id : t -> int +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Obj.md b/docs/api/melange/Stdlib-Obj.md new file mode 100644 index 000000000..c2eeffd0f --- /dev/null +++ b/docs/api/melange/Stdlib-Obj.md @@ -0,0 +1,130 @@ +# Module `Stdlib.Obj` +Operations on internal representations of values. +Not for the casual user. +``` +type t +``` +``` +type raw_data = nativeint +``` +``` +val repr : 'a -> t +``` +``` +val obj : t -> 'a +``` +``` +val magic : 'a -> 'b +``` +``` +val is_block : t -> bool +``` +``` +val is_int : t -> bool +``` +``` +val tag : t -> int +``` +``` +val size : t -> int +``` +``` +val reachable_words : t -> int +``` +Computes the total size (in words, including the headers) of all heap blocks accessible from the argument. Statically allocated blocks are included. +since 4.04 +``` +val field : t -> int -> t +``` +``` +val set_field : t -> int -> t -> unit +``` +When using flambda: +`set_field` MUST NOT be called on immutable blocks. (Blocks allocated in C stubs, or with `new_block` below, are always considered mutable.) +The same goes for `set_double_field`. +For experts only: `set_field` et al can be made safe by first wrapping the block in [`Sys.opaque_identity`](./Stdlib-Sys.md#val-opaque_identity), so any information about its contents will not be propagated. +``` +val double_field : t -> int -> float +``` +``` +val set_double_field : t -> int -> float -> unit +``` +``` +val raw_field : t -> int -> raw_data +``` +``` +val set_raw_field : t -> int -> raw_data -> unit +``` +``` +val new_block : int -> int -> t +``` +``` +val dup : t -> t +``` +``` +val add_offset : t -> Int32.t -> t +``` +``` +val with_tag : int -> t -> t +``` +``` +val first_non_constant_constructor_tag : int +``` +``` +val last_non_constant_constructor_tag : int +``` +``` +val forcing_tag : int +``` +``` +val cont_tag : int +``` +``` +val lazy_tag : int +``` +``` +val closure_tag : int +``` +``` +val object_tag : int +``` +``` +val infix_tag : int +``` +``` +val forward_tag : int +``` +``` +val no_scan_tag : int +``` +``` +val abstract_tag : int +``` +``` +val string_tag : int +``` +``` +val double_tag : int +``` +``` +val double_array_tag : int +``` +``` +val custom_tag : int +``` +``` +val int_tag : int +``` +``` +val out_of_heap_tag : int +``` +``` +val unaligned_tag : int +``` +``` +module Extension_constructor : sig ... end +``` +``` +module Ephemeron : sig ... end +``` +Ephemeron with arbitrary arity and untyped \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Oo.md b/docs/api/melange/Stdlib-Oo.md new file mode 100644 index 000000000..24f735eb0 --- /dev/null +++ b/docs/api/melange/Stdlib-Oo.md @@ -0,0 +1,11 @@ +# Module `Stdlib.Oo` +Operations on objects +``` +val copy : < .. > as 'a -> 'a +``` +`Oo.copy o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`. +alert unsynchronized\_access Unsynchronized accesses to mutable objects are a programming error. +``` +val id : < .. > -> int +``` +Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Option.md b/docs/api/melange/Stdlib-Option.md new file mode 100644 index 000000000..06d5b4134 --- /dev/null +++ b/docs/api/melange/Stdlib-Option.md @@ -0,0 +1,85 @@ +# Module `Stdlib.Option` +Option values. +Option values explicitly indicate the presence or absence of a value. +since 4.08 +## Options +``` +type 'a t = 'a option = +``` +``` +| None +``` +``` +| Some of 'a +``` +``` + +``` +The type for option values. Either `None` or a value `Some v`. +``` +val none : 'a option +``` +`none` is `None`. +``` +val some : 'a -> 'a option +``` +`some v` is `Some v`. +``` +val value : 'a option -> default:'a -> 'a +``` +`value o ~default` is `v` if `o` is `Some v` and `default` otherwise. +``` +val get : 'a option -> 'a +``` +`get o` is `v` if `o` is `Some v` and raise otherwise. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if o is None. +``` +val bind : 'a option -> ('a -> 'b option) -> 'b option +``` +`bind o f` is `f v` if `o` is `Some v` and `None` if `o` is `None`. +``` +val join : 'a option option -> 'a option +``` +`join oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise. +``` +val map : ('a -> 'b) -> 'a option -> 'b option +``` +`map f o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`. +``` +val fold : none:'a -> some:('b -> 'a) -> 'b option -> 'a +``` +`fold ~none ~some o` is `none` if `o` is `None` and `some v` if `o` is `Some v`. +``` +val iter : ('a -> unit) -> 'a option -> unit +``` +`iter f o` is `f v` if `o` is `Some v` and `()` otherwise. +## Predicates and comparisons +``` +val is_none : 'a option -> bool +``` +`is_none o` is `true` if and only if `o` is `None`. +``` +val is_some : 'a option -> bool +``` +`is_some o` is `true` if and only if `o` is `Some o`. +``` +val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool +``` +`equal eq o0 o1` is `true` if and only if `o0` and `o1` are both `None` or if they are `Some v0` and `Some v1` and `eq v0 v1` is `true`. +``` +val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int +``` +`compare cmp o0 o1` is a total order on options using `cmp` to compare values wrapped by `Some _`. `None` is smaller than `Some _` values. +## Converting +``` +val to_result : none:'e -> 'a option -> ('a, 'e) result +``` +`to_result ~none o` is `Ok v` if `o` is `Some v` and `Error none` otherwise. +``` +val to_list : 'a option -> 'a list +``` +`to_list o` is `[]` if `o` is `None` and `[v]` if `o` is `Some v`. +``` +val to_seq : 'a option -> 'a Seq.t +``` +`to_seq o` is `o` as a sequence. `None` is the empty sequence and `Some v` is the singleton sequence containing `v`. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Out_channel.md b/docs/api/melange/Stdlib-Out_channel.md new file mode 100644 index 000000000..5d27942bf --- /dev/null +++ b/docs/api/melange/Stdlib-Out_channel.md @@ -0,0 +1,177 @@ +# Module `Stdlib.Out_channel` +Output channels. +This module provides functions for working with output channels. +See [the example section](./#examples) below. +since 4.14 +## Channels +``` +type t = out_channel +``` +The type of output channel. +``` +type open_flag = open_flag = +``` +``` +| Open_rdonly +``` +open for reading. +``` +| Open_wronly +``` +open for writing. +``` +| Open_append +``` +open for appending: always write at end of file. +``` +| Open_creat +``` +create the file if it does not exist. +``` +| Open_trunc +``` +empty the file if it already exists. +``` +| Open_excl +``` +fail if Open\_creat and the file already exists. +``` +| Open_binary +``` +open in binary mode (no conversion). +``` +| Open_text +``` +open in text mode (may perform conversions). +``` +| Open_nonblock +``` +open in non-blocking mode. +``` + +``` +Opening modes for [`open_gen`](./#val-open_gen). +``` +val stdout : t +``` +The standard output for the process. +``` +val stderr : t +``` +The standard error output for the process. +``` +val open_bin : string -> t +``` +Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. +``` +val open_text : string -> t +``` +Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). +``` +val open_gen : open_flag list -> int -> string -> t +``` +`open_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. +``` +val with_open_bin : string -> (t -> 'a) -> 'a +``` +`with_open_bin fn f` opens a channel `oc` on file `fn` and returns `f oc`. After `f` returns, either with a value or by raising an exception, `oc` is guaranteed to be closed. +``` +val with_open_text : string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). +``` +val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). +``` +val close : t -> unit +``` +Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except [`close`](./#val-close) and [`flush`](./#val-flush), which do nothing when applied to an already closed channel. Note that [`close`](./#val-close) may raise `Sys_error` if the operating system signals an error when flushing or closing. +``` +val close_noerr : t -> unit +``` +Same as [`close`](./#val-close), but ignore all errors. +## Output +``` +val output_char : t -> char -> unit +``` +Write the character on the given output channel. +``` +val output_byte : t -> int -> unit +``` +Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. +``` +val output_string : t -> string -> unit +``` +Write the string on the given output channel. +``` +val output_bytes : t -> bytes -> unit +``` +Write the byte sequence on the given output channel. +## Advanced output +``` +val output : t -> bytes -> int -> int -> unit +``` +`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val output_substring : t -> string -> int -> int -> unit +``` +Same as [`output`](./#val-output) but take a string as argument instead of a byte sequence. +## Flushing +``` +val flush : t -> unit +``` +Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. +``` +val flush_all : unit -> unit +``` +Flush all open output channels; ignore errors. +## Seeking +``` +val seek : t -> int64 -> unit +``` +`seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. +``` +val pos : t -> int64 +``` +Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). +For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. +## Attributes +``` +val length : t -> int64 +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. +``` +val set_binary_mode : t -> bool -> unit +``` +`set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output. +`set_binary_mode oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. +This function has no effect under operating systems that do not distinguish between text mode and binary mode. +``` +val is_binary_mode : t -> bool +``` +`is_binary_mode oc` returns whether the channel `oc` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). +since 5.2 +``` +val set_buffered : t -> bool -> unit +``` +`set_buffered oc true` sets the channel `oc` to *buffered* mode. In this mode, data output on `oc` will be buffered until either the internal buffer is full or the function [`flush`](./#val-flush) or [`flush_all`](./#val-flush_all) is called, at which point it will be sent to the output device. +`set_buffered oc false` sets the channel `oc` to *unbuffered* mode. In this mode, data output on `oc` will be sent to the output device immediately. +All channels are open in *buffered* mode by default. +``` +val is_buffered : t -> bool +``` +`is_buffered oc` returns whether the channel `oc` is buffered (see [`set_buffered`](./#val-set_buffered)). +``` +val isatty : t -> bool +``` +`isatty oc` is `true` if `oc` refers to a terminal or console window, `false` otherwise. +since 5.1 +## Examples +Writing the contents of a file: +```ocaml + let write_file file s = + Out_channel.with_open_bin file + (fun oc -> Out_channel.output_string oc s)) +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Parsing.md b/docs/api/melange/Stdlib-Parsing.md new file mode 100644 index 000000000..6f77c29ea --- /dev/null +++ b/docs/api/melange/Stdlib-Parsing.md @@ -0,0 +1,47 @@ +# Module `Stdlib.Parsing` +The run-time library for parsers generated by `ocamlyacc`. +``` +val symbol_start : unit -> int +``` +`symbol_start` and [`Parsing.symbol_end`](./#val-symbol_end) are to be called in the action part of a grammar rule only. They return the offset of the string that matches the left-hand side of the rule: `symbol_start()` returns the offset of the first character; `symbol_end()` returns the offset after the last character. The first character in a file is at offset 0. +``` +val symbol_end : unit -> int +``` +See [`Parsing.symbol_start`](./#val-symbol_start). +``` +val rhs_start : int -> int +``` +Same as [`Parsing.symbol_start`](./#val-symbol_start) and [`Parsing.symbol_end`](./#val-symbol_end), but return the offset of the string matching the `n`th item on the right-hand side of the rule, where `n` is the integer parameter to `rhs_start` and `rhs_end`. `n` is 1 for the leftmost item. +``` +val rhs_end : int -> int +``` +See [`Parsing.rhs_start`](./#val-rhs_start). +``` +val symbol_start_pos : unit -> Lexing.position +``` +Same as `symbol_start`, but return a `position` instead of an offset. +``` +val symbol_end_pos : unit -> Lexing.position +``` +Same as `symbol_end`, but return a `position` instead of an offset. +``` +val rhs_start_pos : int -> Lexing.position +``` +Same as `rhs_start`, but return a `position` instead of an offset. +``` +val rhs_end_pos : int -> Lexing.position +``` +Same as `rhs_end`, but return a `position` instead of an offset. +``` +val clear_parser : unit -> unit +``` +Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs. +``` +exception Parse_error +``` +Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery. +``` +val set_trace : bool -> bool +``` +Control debugging support for `ocamlyacc`\-generated parsers. After `Parsing.set_trace true`, the pushdown automaton that executes the parsers prints a trace of its actions (reading a token, shifting a state, reducing by a rule) on standard output. `Parsing.set_trace false` turns this debugging trace off. The boolean returned is the previous state of the trace flag. +since 3.11 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Printexc-Slot.md b/docs/api/melange/Stdlib-Printexc-Slot.md new file mode 100644 index 000000000..95d9ea422 --- /dev/null +++ b/docs/api/melange/Stdlib-Printexc-Slot.md @@ -0,0 +1,35 @@ +# Module `Printexc.Slot` +since 4.02 +``` +type t = backtrace_slot +``` +``` +val is_raise : t -> bool +``` +`is_raise slot` is `true` when `slot` refers to a raising point in the code, and `false` when it comes from a simple function call. +since 4.02 +``` +val is_inline : t -> bool +``` +`is_inline slot` is `true` when `slot` refers to a call that got inlined by the compiler, and `false` when it comes from any other context. +since 4.04 +``` +val location : t -> location option +``` +`location slot` returns the location information of the slot, if available, and `None` otherwise. +Some possible reasons for failing to return a location are as follow: +- the slot corresponds to a compiler-inserted raise +- the slot corresponds to a part of the program that has not been compiled with debug information (`-g`) +since 4.02 +``` +val name : t -> string option +``` +`name slot` returns the name of the function or definition enclosing the location referred to by the slot. +`name slot` returns None if the name is unavailable, which may happen for the same reasons as `location` returning None. +since 4.11 +``` +val format : int -> t -> string option +``` +`format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`\-th element of the backtrace: the `0`\-th element is pretty-printed differently than the others. +Whole-backtrace printing functions also skip some uninformative slots; in that case, `format pos slot` returns `None`. +since 4.02 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Printexc.md b/docs/api/melange/Stdlib-Printexc.md new file mode 100644 index 000000000..ca31fd509 --- /dev/null +++ b/docs/api/melange/Stdlib-Printexc.md @@ -0,0 +1,216 @@ +# Module `Stdlib.Printexc` +Facilities for printing exceptions and inspecting current call stack. +``` +type t = exn = .. +``` +The type of exception values. +``` +val to_string : exn -> string +``` +`Printexc.to_string e` returns a string representation of the exception `e`. +``` +val to_string_default : exn -> string +``` +`Printexc.to_string_default e` returns a string representation of the exception `e`, ignoring all registered exception printers. +since 4.09 +``` +val print : ('a -> 'b) -> 'a -> 'b +``` +`Printexc.print fn x` applies `fn` to `x` and returns the result. If the evaluation of `fn x` raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application. +``` +val catch : ('a -> 'b) -> 'a -> 'b +``` +`Printexc.catch fn x` is similar to [`Printexc.print`](./#val-print), but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as `Printexc.catch` does. Moreover, calling `Printexc.catch` makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use `Printexc.catch` in new code. +deprecated This function is no longer needed. +``` +val print_backtrace : out_channel -> unit +``` +`Printexc.print_backtrace oc` prints an exception backtrace on the output channel `oc`. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls. +If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one. +since 3.11 +``` +val get_backtrace : unit -> string +``` +`Printexc.get_backtrace ()` returns a string containing the same exception backtrace that `Printexc.print_backtrace` would print. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). +since 3.11 +``` +val record_backtrace : bool -> unit +``` +`Printexc.record_backtrace b` turns recording of exception backtraces on (if `b = true`) or off (if `b = false`). Initially, backtraces are not recorded, unless the `b` flag is given to the program through the `OCAMLRUNPARAM` variable. +since 3.11 +``` +val backtrace_status : unit -> bool +``` +`Printexc.backtrace_status()` returns `true` if exception backtraces are currently recorded, `false` if not. +since 3.11 +``` +val register_printer : (exn -> string option) -> unit +``` +`Printexc.register_printer fn` registers `fn` as an exception printer. The printer should return `None` or raise an exception if it does not know how to convert the passed exception, and `Some s` with `s` the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored. +When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a `Some s` value (if no such printer exists, the runtime will use a generic printer). +When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to `fn` should not use the backtrace if it has itself raised an exception before. +since 3.11.2 +``` +val use_printers : exn -> string option +``` +`Printexc.use_printers e` returns `None` if there are no registered printers and `Some s` with `s` the resulting string otherwise. +since 4.09 +## Raw backtraces +``` +type raw_backtrace +``` +The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below. +Converting backtraces to `backtrace_slot`s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use `raw_backtrace` to avoid or delay conversion. +Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the `backtrace_slots` function of the next section. +since 4.01 +``` +type raw_backtrace_entry = private int +``` +A `raw_backtrace_entry` is an element of a `raw_backtrace`. +Each `raw_backtrace_entry` is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary. +A `raw_backtrace_entry` can be converted to a usable form using `backtrace_slots_of_raw_entry` below. Note that, due to inlining, a single `raw_backtrace_entry` may convert to several `backtrace_slot`s. Since the values of a `raw_backtrace_entry` are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them. +Again due to inlining, there may be multiple distinct raw\_backtrace\_entry values that convert to equal `backtrace_slot`s. However, if two `raw_backtrace_entry`s are equal as integers, then they represent the same `backtrace_slot`s. +since 4.12 +``` +val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array +``` +since 4.12 +``` +val get_raw_backtrace : unit -> raw_backtrace +``` +`Printexc.get_raw_backtrace ()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). +since 4.01 +``` +val print_raw_backtrace : out_channel -> raw_backtrace -> unit +``` +Print a raw backtrace in the same format `Printexc.print_backtrace` uses. +since 4.01 +``` +val raw_backtrace_to_string : raw_backtrace -> string +``` +Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses. +since 4.01 +``` +val raise_with_backtrace : exn -> raw_backtrace -> 'a +``` +Reraise the exception using the given raw\_backtrace for the origin of the exception +since 4.05 +## Current call stack +``` +val get_callstack : int -> raw_backtrace +``` +`Printexc.get_callstack n` returns a description of the top of the call stack on the current program point (for the current thread), with at most `n` entries. (Note: this function is not related to exceptions at all, despite being part of the `Printexc` module.) +since 4.01 +## Uncaught exceptions +``` +val default_uncaught_exception_handler : exn -> raw_backtrace -> unit +``` +`Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output. +since 4.11 +``` +val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit +``` +`Printexc.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. The default handler is [`Printexc.default_uncaught_exception_handler`](./#val-default_uncaught_exception_handler). +Note that when `fn` is called all the functions registered with [`Stdlib.at_exit`](./Stdlib.md#val-at_exit) have already been called. Because of this you must make sure any output channel `fn` writes on is flushed. +Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself. +If `fn` raises an exception, both the exceptions passed to `fn` and raised by `fn` will be printed with their respective backtrace. +since 4.02 +## Manipulation of backtrace information +These functions are used to traverse the slots of a raw backtrace and extract information from them in a programmer-friendly format. +``` +type backtrace_slot +``` +The abstract type `backtrace_slot` represents a single slot of a backtrace. +since 4.02 +``` +val backtrace_slots : raw_backtrace -> backtrace_slot array option +``` +Returns the slots of a raw backtrace, or `None` if none of them contain useful information. +In the return array, the slot at index `0` corresponds to the most recent function call, raise, or primitive `get_backtrace` call in the trace. +Some possible reasons for returning `None` are as follow: +- none of the slots in the trace come from modules compiled with debug information (`-g`) +- the program is a bytecode program that has not been linked with debug information enabled (`ocamlc -g`) +since 4.02 +``` +val backtrace_slots_of_raw_entry : + raw_backtrace_entry -> + backtrace_slot array option +``` +Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information. +Slots are returned in the same order as `backtrace_slots`: the slot at index `0` is the most recent call, raise, or primitive, and subsequent slots represent callers. +since 4.12 +``` +type location = { +``` +`filename : string;` +`line_number : int;` +`start_char : int;` +`end_char : int;` +`end_line : int;` +since 5.2 +`end_col : int;` +since 5.2 +``` +} +``` +The type of location information found in backtraces. `start_char` and `end_char` are positions relative to the beginning of `line_number`. `end_col` is relative to the beginning of `end_line`. +since 4.02 +``` +module Slot : sig ... end +``` +## Raw backtrace slots +``` +type raw_backtrace_slot +``` +This type is used to iterate over the slots of a `raw_backtrace`. For most purposes, `backtrace_slots_of_raw_entry` is easier to use. +Like `raw_backtrace_entry`, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior). +Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example). +since 4.02 +``` +val raw_backtrace_length : raw_backtrace -> int +``` +`raw_backtrace_length bckt` returns the number of slots in the backtrace `bckt`. +since 4.02 +``` +val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot +``` +`get_raw_backtrace_slot bckt pos` returns the slot in position `pos` in the backtrace `bckt`. +since 4.02 +``` +val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot +``` +Extracts the user-friendly `backtrace_slot` from a low-level `raw_backtrace_slot`. +since 4.02 +``` +val get_raw_backtrace_next_slot : + raw_backtrace_slot -> + raw_backtrace_slot option +``` +`get_raw_backtrace_next_slot slot` returns the next slot inlined, if any. +Sample code to iterate over all frames (inlined and non-inlined): +```ocaml + (* Iterate over inlined frames *) + let rec iter_raw_backtrace_slot f slot = + f slot; + match get_raw_backtrace_next_slot slot with + | None -> () + | Some slot' -> iter_raw_backtrace_slot f slot' + + (* Iterate over stack frames *) + let iter_raw_backtrace f bt = + for i = 0 to raw_backtrace_length bt - 1 do + iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i) + done +``` +since 4.04 +## Exception slots +``` +val exn_slot_id : exn -> int +``` +`Printexc.exn_slot_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime). +since 4.02 +``` +val exn_slot_name : exn -> string +``` +`Printexc.exn_slot_name exn` returns the internal name of the constructor used to create the exception value `exn`. +since 4.02 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Printf.md b/docs/api/melange/Stdlib-Printf.md new file mode 100644 index 000000000..15da09c35 --- /dev/null +++ b/docs/api/melange/Stdlib-Printf.md @@ -0,0 +1,117 @@ +# Module `Stdlib.Printf` +Formatted output functions. +``` +val fprintf : out_channel -> ('a, out_channel, unit) format -> 'a +``` +`fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`. +The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments. +Conversion specifications have the following form: +`% [flags] [width] [.precision] type` +In short, a conversion specification consists in the `%` character, followed by optional modifiers and a type which is made of one or two characters. +The types and their meanings are: +- `d`, `i`: convert an integer argument to signed decimal. The flag `#` adds underscores to large values for readability. +- `u`, `n`, `l`, `L`, or `N`: convert an integer argument to unsigned decimal. Warning: `n`, `l`, `L`, and `N` are used for `scanf`, and should not be used for `printf`. The flag `#` adds underscores to large values for readability. +- `x`: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag `#` adds a `0x` prefix to non zero values. +- `X`: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag `#` adds a `0X` prefix to non zero values. +- `o`: convert an integer argument to unsigned octal. The flag `#` adds a `0` prefix to non zero values. +- `s`: insert a string argument. +- `S`: convert a string argument to OCaml syntax (double quotes, escapes). +- `c`: insert a character argument. +- `C`: convert a character argument to OCaml syntax (single quotes, escapes). +- `f`: convert a floating-point argument to decimal notation, in the style `dddd.ddd`. +- `F`: convert a floating-point argument to OCaml syntax (`dddd.` or `dddd.ddd` or `d.ddd e+-dd`). Converts to hexadecimal with the `#` flag (see `h`). +- `e` or `E`: convert a floating-point argument to decimal notation, in the style `d.ddd e+-dd` (mantissa and exponent). +- `g` or `G`: convert a floating-point argument to decimal notation, in style `f` or `e`, `E` (whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining. +- `h` or `H`: convert a floating-point argument to hexadecimal notation, in the style `0xh.hhhh p+-dd` (hexadecimal mantissa, exponent in decimal and denotes a power of 2). +- `B`: convert a boolean argument to the string `true` or `false` +- `b`: convert a boolean argument (deprecated; do not use in new programs). +- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: convert an `int32` argument to the format specified by the second letter (decimal, hexadecimal, etc). +- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: convert a `nativeint` argument to the format specified by the second letter. +- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: convert an `int64` argument to the format specified by the second letter. +- `a`: user-defined printer. Take two arguments and apply the first one to `outchan` (the current output channel) and to the second argument. The first argument must therefore have type `out_channel -> 'b -> unit` and the second `'b`. The output produced by the function is inserted in the output of `fprintf` at the current point. +- `t`: same as `%a`, but take only one argument (with type `out_channel -> unit`) and apply it to `outchan`. +- `\{ fmt %\}`: convert a format string argument to its type digest. The argument must have the same type as the internal format string `fmt`. +- `( fmt %)`: format string substitution. Take a format string argument and substitute it to the internal format string `fmt` to print following arguments. The argument must have the same type as the internal format string `fmt`. +- `!`: take no argument and flush the output. +- `%`: take no argument and output one `%` character. +- `\@`: take no argument and output one `\@` character. +- `,`: take no argument and output nothing: a no-op delimiter for conversion specifications. +The optional `flags` are: +- `-`: left-justify the output (default is right justification). +- `0`: for numerical conversions, pad with zeroes instead of spaces. +- `+`: for signed numerical conversions, prefix number with a `+` sign if positive. +- space: for signed numerical conversions, prefix number with a space if positive. +- `#`: request an alternate formatting style for the integer types and the floating-point type `F`. +The optional `width` is an integer indicating the minimal width of the result. For instance, `%6d` prints an integer, prefixing it with spaces to fill at least 6 characters. +The optional `precision` is a dot `.` followed by an integer indicating how many digits follow the decimal point in the `%f`, `%e`, `%E`, `%h`, and `%H` conversions or the maximum number of significant digits to appear for the `%F`, `%g` and `%G` conversions. For instance, `%.4f` prints a `float` with 4 fractional digits. +The integer in a `width` or `precision` can also be specified as `*`, in which case an extra integer argument is taken to specify the corresponding `width` or `precision`. This integer argument precedes immediately the argument to print. For instance, `%.*f` prints a `float` with as many fractional digits as the value of the argument given before the float. +``` +val printf : ('a, out_channel, unit) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but output on `stdout`. +``` +val eprintf : ('a, out_channel, unit) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but output on `stderr`. +``` +val sprintf : ('a, unit, string) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, return a string containing the result of formatting the arguments. +``` +val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module [`Buffer`](./Stdlib-Buffer.md)). +``` +val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but does not print anything. Useful to ignore some material when conditionally printing. +since 3.10 +``` +val ibprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a +``` +Same as [`Printf.bprintf`](./#val-bprintf), but does not print anything. Useful to ignore some material when conditionally printing. +since 4.11 +Formatted output functions with continuations. +``` +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 +``` +val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a +``` +Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. +since 4.01 +``` +val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a +``` +Same as `sprintf` above, but instead of returning the string, passes it to the first argument. +since 3.09 +``` +val kbprintf : + (Buffer.t -> 'd) -> + Buffer.t -> + ('a, Buffer.t, unit, 'd) format4 -> + 'a +``` +Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing. +since 3.10 +``` +val ikbprintf : + (Buffer.t -> 'd) -> + Buffer.t -> + ('a, Buffer.t, unit, 'd) format4 -> + 'a +``` +Same as `kbprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. +since 4.11 +Deprecated +``` +val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a +``` +A deprecated synonym for `ksprintf`. +deprecated Use Printf.ksprintf instead. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Queue.md b/docs/api/melange/Stdlib-Queue.md new file mode 100644 index 000000000..1efb756bd --- /dev/null +++ b/docs/api/melange/Stdlib-Queue.md @@ -0,0 +1,187 @@ +# Module `Stdlib.Queue` +First-in first-out queues. +This module implements queues (FIFOs), with in-place modification. See [the example section](./#examples) below. +**Unsynchronized accesses** +Unsynchronized accesses to a queue may lead to an invalid queue state. Thus, concurrent accesses to queues must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +``` +type !'a t +``` +The type of queues containing elements of type `'a`. +``` +exception Empty +``` +Raised when [`Queue.take`](./#val-take) or [`Queue.peek`](./#val-peek) is applied to an empty queue. +``` +val create : unit -> 'a t +``` +Return a new queue, initially empty. +``` +val add : 'a -> 'a t -> unit +``` +`add x q` adds the element `x` at the end of the queue `q`. +``` +val push : 'a -> 'a t -> unit +``` +`push` is a synonym for `add`. +``` +val take : 'a t -> 'a +``` +`take q` removes and returns the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. +``` +val take_opt : 'a t -> 'a option +``` +`take_opt q` removes and returns the first element in queue `q`, or returns `None` if the queue is empty. +since 4.08 +``` +val pop : 'a t -> 'a +``` +`pop` is a synonym for `take`. +``` +val peek : 'a t -> 'a +``` +`peek q` returns the first element in queue `q`, without removing it from the queue, or raises [`Empty`](./#exception-Empty) if the queue is empty. +``` +val peek_opt : 'a t -> 'a option +``` +`peek_opt q` returns the first element in queue `q`, without removing it from the queue, or returns `None` if the queue is empty. +since 4.08 +``` +val top : 'a t -> 'a +``` +`top` is a synonym for `peek`. +``` +val drop : 'a t -> unit +``` +`drop q` removes the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. +since 5.3 +``` +val clear : 'a t -> unit +``` +Discard all elements from a queue. +``` +val copy : 'a t -> 'a t +``` +Return a copy of the given queue. +``` +val is_empty : 'a t -> bool +``` +Return `true` if the given queue is empty, `false` otherwise. +``` +val length : 'a t -> int +``` +Return the number of elements in a queue. +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f q` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. +``` +val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold f accu q` is equivalent to `List.fold_left f accu l`, where `l` is the list of `q`'s elements. The queue remains unchanged. +``` +val transfer : 'a t -> 'a t -> unit +``` +`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `iter (fun x -> add x q2) q1; clear q1`, but runs in constant time. +## Iterators +``` +val to_seq : 'a t -> 'a Seq.t +``` +Iterate on the queue, in front-to-back order. The behavior is not specified if the queue is modified during the iteration. +since 4.07 +``` +val add_seq : 'a t -> 'a Seq.t -> unit +``` +Add the elements from a sequence to the end of the queue. +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a t +``` +Create a queue from a sequence. +since 4.07 +## Examples +### Basic Example +A basic example: +```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. +``` +### Search Through a Graph +For a more elaborate example, a classic algorithmic use of queues is to implement a BFS (breadth-first search) through a graph. +```ocaml + type graph = { + edges: (int, int list) Hashtbl.t + } + + (* Search in graph [g] using BFS, starting from node [start]. + It returns the first node that satisfies [p], or [None] if + no node reachable from [start] satisfies [p]. + *) + let search_for ~(g:graph) ~(start:int) (p:int -> bool) : int option = + let to_explore = Queue.create() in + let explored = Hashtbl.create 16 in + + Queue.push start to_explore; + let rec loop () = + if Queue.is_empty to_explore then None + else + (* node to explore *) + let node = Queue.pop to_explore in + explore_node node + + and explore_node node = + if not (Hashtbl.mem explored node) then ( + if p node then Some node (* found *) + else ( + Hashtbl.add explored node (); + let children = + Hashtbl.find_opt g.edges node + |> Option.value ~default:[] + in + List.iter (fun child -> Queue.push child to_explore) children; + loop() + ) + ) else loop() + in + loop() + + (* a sample graph *) + let my_graph: graph = + let edges = + List.to_seq [ + 1, [2;3]; + 2, [10; 11]; + 3, [4;5]; + 5, [100]; + 11, [0; 20]; + ] + |> Hashtbl.of_seq + in {edges} + + # search_for ~g:my_graph ~start:1 (fun x -> x = 30) + - : int option = None + + # search_for ~g:my_graph ~start:1 (fun x -> x >= 15) + - : int option = Some 20 + + # search_for ~g:my_graph ~start:1 (fun x -> x >= 50) + - : int option = Some 100 +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Random-State.md b/docs/api/melange/Stdlib-Random-State.md new file mode 100644 index 000000000..23d1d629e --- /dev/null +++ b/docs/api/melange/Stdlib-Random-State.md @@ -0,0 +1,44 @@ +# Module `Random.State` +``` +type t +``` +The type of PRNG states. +``` +val make : int array -> t +``` +Create a new state and initialize it with the given seed. +``` +val make_self_init : unit -> t +``` +Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in [`Random.self_init`](./Stdlib-Random.md#val-self_init). +``` +val copy : t -> t +``` +Return a copy of the given state. +``` +val bits : t -> int +``` +``` +val int : t -> int -> int +``` +``` +val full_int : t -> int -> int +``` +``` +val int32 : t -> Int32.t -> Int32.t +``` +``` +val int64 : t -> Int64.t -> Int64.t +``` +``` +val float : t -> float -> float +``` +``` +val bool : t -> bool +``` +``` +val bits32 : t -> Int32.t +``` +``` +val bits64 : t -> Int64.t +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Random.md b/docs/api/melange/Stdlib-Random.md new file mode 100644 index 000000000..0ef606363 --- /dev/null +++ b/docs/api/melange/Stdlib-Random.md @@ -0,0 +1,77 @@ +# Module `Stdlib.Random` +Pseudo-random number generators (PRNG). +With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain. +In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the `Random.split` function and used with the functions from the [`Random.State`](./Stdlib-Random-State.md) module. +before 5.0 Random value generation used a different algorithm. This affects all the functions in this module which return random values. +## Basic functions +``` +val init : int -> unit +``` +Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. +``` +val full_init : int array -> unit +``` +Same as [`Random.init`](./#val-init) but takes more data as seed. +``` +val self_init : unit -> unit +``` +Initialize the domain-local generator with a random seed chosen in a system-dependent way. If `/dev/urandom` is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state). +``` +val bits : unit -> int +``` +Return 30 random bits in a nonnegative integer. +``` +val int : int -> int +``` +`Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0 and less than 230. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0 or bound \>= 230. +``` +val full_int : int -> int +``` +`Random.full_int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` may be any positive integer. +If `bound` is less than 231, then `Random.full_int bound` yields identical output across systems with varying `int` sizes. +If `bound` is less than 230, then `Random.full_int bound` is equal to [`Random.int`](./#val-int)` bound`. +If `bound` is at least 230 (on 64-bit systems, or non-standard environments such as JavaScript), then `Random.full_int` returns a value whereas [`Random.int`](./#val-int) raises [`Stdlib.Invalid_argument`](./Stdlib.md#exception-Invalid_argument). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. +since 4.13 +``` +val int32 : Int32.t -> Int32.t +``` +`Random.int32 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. +``` +val int64 : Int64.t -> Int64.t +``` +`Random.int64 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. +``` +val float : float -> float +``` +`Random.float bound` returns a random floating-point number between 0 and `bound` (inclusive). If `bound` is negative, the result is negative or zero. If `bound` is 0, the result is 0. +``` +val bool : unit -> bool +``` +`Random.bool ()` returns `true` or `false` with probability 0.5 each. +``` +val bits32 : unit -> Int32.t +``` +`Random.bits32 ()` returns 32 random bits as an integer between [`Int32.min_int`](./Stdlib-Int32.md#val-min_int) and [`Int32.max_int`](./Stdlib-Int32.md#val-max_int). +since 4.14 +``` +val bits64 : unit -> Int64.t +``` +`Random.bits64 ()` returns 64 random bits as an integer between [`Int64.min_int`](./Stdlib-Int64.md#val-min_int) and [`Int64.max_int`](./Stdlib-Int64.md#val-max_int). +since 4.14 +## Advanced functions +The functions from module [`State`](./Stdlib-Random-State.md) manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. +``` +module State : sig ... end +``` +``` +val get_state : unit -> State.t +``` +`get_state()` returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). +``` +val set_state : State.t -> unit +``` +`set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Result.md b/docs/api/melange/Stdlib-Result.md new file mode 100644 index 000000000..3e7b579fb --- /dev/null +++ b/docs/api/melange/Stdlib-Result.md @@ -0,0 +1,108 @@ +# Module `Stdlib.Result` +Result values. +Result values handle computation results and errors in an explicit and declarative manner without resorting to exceptions. +since 4.08 +## Results +``` +type ('a, 'e) t = ('a, 'e) result = +``` +``` +| Ok of 'a +``` +``` +| Error of 'e +``` +``` + +``` +The type for result values. Either a value `Ok v` or an error `Error e`. +``` +val ok : 'a -> ('a, 'e) result +``` +`ok v` is `Ok v`. +``` +val error : 'e -> ('a, 'e) result +``` +`error e` is `Error e`. +``` +val value : ('a, 'e) result -> default:'a -> 'a +``` +`value r ~default` is `v` if `r` is `Ok v` and `default` otherwise. +``` +val get_ok : ('a, 'e) result -> 'a +``` +`get_ok r` is `v` if `r` is `Ok v` and raise otherwise. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Error \_. +``` +val get_error : ('a, 'e) result -> 'e +``` +`get_error r` is `e` if `r` is `Error e` and raise otherwise. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Ok \_. +``` +val bind : ('a, 'e) result -> ('a -> ('b, 'e) result) -> ('b, 'e) result +``` +`bind r f` is `f v` if `r` is `Ok v` and `r` if `r` is `Error _`. +``` +val join : (('a, 'e) result, 'e) result -> ('a, 'e) result +``` +`join rr` is `r` if `rr` is `Ok r` and `rr` if `rr` is `Error _`. +``` +val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result +``` +`map f r` is `Ok (f v)` if `r` is `Ok v` and `r` if `r` is `Error _`. +``` +val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result +``` +`map_error f r` is `Error (f e)` if `r` is `Error e` and `r` if `r` is `Ok _`. +``` +val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c +``` +`fold ~ok ~error r` is `ok v` if `r` is `Ok v` and `error e` if `r` is `Error e`. +``` +val iter : ('a -> unit) -> ('a, 'e) result -> unit +``` +`iter f r` is `f v` if `r` is `Ok v` and `()` otherwise. +``` +val iter_error : ('e -> unit) -> ('a, 'e) result -> unit +``` +`iter_error f r` is `f e` if `r` is `Error e` and `()` otherwise. +## Predicates and comparisons +``` +val is_ok : ('a, 'e) result -> bool +``` +`is_ok r` is `true` if and only if `r` is `Ok _`. +``` +val is_error : ('a, 'e) result -> bool +``` +`is_error r` is `true` if and only if `r` is `Error _`. +``` +val equal : + ok:('a -> 'a -> bool) -> + error:('e -> 'e -> bool) -> + ('a, 'e) result -> + ('a, 'e) result -> + bool +``` +`equal ~ok ~error r0 r1` tests equality of `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. +``` +val compare : + ok:('a -> 'a -> int) -> + error:('e -> 'e -> int) -> + ('a, 'e) result -> + ('a, 'e) result -> + int +``` +`compare ~ok ~error r0 r1` totally orders `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _ ` and `Error _`. `Ok _` values are smaller than `Error _` values. +## Converting +``` +val to_option : ('a, 'e) result -> 'a option +``` +`to_option r` is `r` as an option, mapping `Ok v` to `Some v` and `Error _` to `None`. +``` +val to_list : ('a, 'e) result -> 'a list +``` +`to_list r` is `[v]` if `r` is `Ok v` and `[]` otherwise. +``` +val to_seq : ('a, 'e) result -> 'a Seq.t +``` +`to_seq r` is `r` as a sequence. `Ok v` is the singleton sequence containing `v` and `Error _` is the empty sequence. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Scanf-Scanning.md b/docs/api/melange/Stdlib-Scanf-Scanning.md new file mode 100644 index 000000000..f123adeda --- /dev/null +++ b/docs/api/melange/Stdlib-Scanf-Scanning.md @@ -0,0 +1,73 @@ +# Module `Scanf.Scanning` +``` +type in_channel +``` +The notion of input channel for the [`Scanf`](./Stdlib-Scanf.md) module: those channels provide all the machinery necessary to read from any source of characters, including a [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) value. A Scanf.Scanning.in\_channel value is also called a *formatted input channel* or equivalently a *scanning buffer*. The type [`Scanning.scanbuf`](./#type-scanbuf) below is an alias for `Scanning.in_channel`. Note that a `Scanning.in_channel` is not concurrency-safe: concurrent use may produce arbitrary values or exceptions. +since 3.12 +``` +type scanbuf = in_channel +``` +The type of scanning buffers. A scanning buffer is the source from which a formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far. +Note: a scanning action may often require to examine one character in advance; when this 'lookahead' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character yet to be read. +``` +val stdin : in_channel +``` +The standard input notion for the [`Scanf`](./Stdlib-Scanf.md) module. `Scanning.stdin` is the [`Scanning.in_channel`](./#type-in_channel) formatted input channel attached to [`Stdlib.stdin`](./Stdlib.md#val-stdin). +Note: in the interactive system, when input is read from [`Stdlib.stdin`](./Stdlib.md#val-stdin), the newline character that triggers evaluation is part of the input; thus, the scanning specifications must properly skip this additional newline character (for instance, simply add a `'\n'` as the last character of the format string). +since 3.12 +``` +type file_name = string +``` +A convenient alias to designate a file name. +since 4.00 +``` +val open_in : file_name -> in_channel +``` +`Scanning.open_in fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in text mode from file `fname`. +Note: `open_in` returns a formatted input channel that efficiently reads characters in large chunks; in contrast, `from_channel` below returns formatted input channels that must read one character at a time, leading to a much slower scanning rate. +since 3.12 +``` +val open_in_bin : file_name -> in_channel +``` +`Scanning.open_in_bin fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in binary mode from file `fname`. +since 3.12 +``` +val close_in : in_channel -> unit +``` +Closes the [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) associated with the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. +since 3.12 +``` +val from_file : file_name -> in_channel +``` +An alias for [`Scanning.open_in`](./#val-open_in) above. +``` +val from_file_bin : string -> in_channel +``` +An alias for [`Scanning.open_in_bin`](./#val-open_in_bin) above. +``` +val from_string : string -> in_channel +``` +`Scanning.from_string s` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached. +``` +val from_function : (unit -> char) -> in_channel +``` +`Scanning.from_function f` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel with the given function as its reading method. +When scanning needs one more character, the given function is called. +When the function has no more character to provide, it *must* signal an end-of-input condition by raising the exception `End_of_file`. +``` +val from_channel : in_channel -> in_channel +``` +`Scanning.from_channel ic` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the regular [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) input channel `ic` argument. Reading starts at current reading position of `ic`. +``` +val end_of_input : in_channel -> bool +``` +`Scanning.end_of_input ic` tests the end-of-input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. +``` +val beginning_of_input : in_channel -> bool +``` +`Scanning.beginning_of_input ic` tests the beginning of input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. +``` +val name_of_input : in_channel -> string +``` +`Scanning.name_of_input ic` returns the name of the character source for the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. +since 3.09 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Scanf.md b/docs/api/melange/Stdlib-Scanf.md new file mode 100644 index 000000000..b6eb226e8 --- /dev/null +++ b/docs/api/melange/Stdlib-Scanf.md @@ -0,0 +1,191 @@ +# Module `Stdlib.Scanf` +Formatted input functions. +## Introduction +### Functional input with format strings +The module [`Scanf`](#) provides formatted input functions or *scanners*. +The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a *formatted input channel* (or *scanning buffer*) and has type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). The more general formatted input function reads from any scanning buffer and is named `bscanf`. +Generally speaking, the formatted input functions have 3 arguments: +- the first argument is a source of characters for the input, +- the second argument is a format string that specifies the values to read, +- the third argument is a *receiver function* that is applied to the values read. +Hence, a typical call to the formatted input function [`Scanf.bscanf`](./#val-bscanf) is `bscanf ic fmt f`, where: +- `ic` is a source of characters (typically a *formatted input channel* with type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)), +- `fmt` is a format string (the same format strings as those used to print material with module [`Printf`](./Stdlib-Printf.md) or [`Format`](./Stdlib-Format.md)), +- `f` is a function that has as many arguments as the number of values to read in the input according to `fmt`. +### A simple example +As suggested above, the expression `bscanf ic "%d" f` reads a decimal integer `n` from the source of characters `ic` and returns `f n`. +For instance, +- if we use `stdin` as the source of characters ([`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) is the predefined formatted input channel that reads from standard input), +- if we define the receiver `f` as `let f x = x + 1`, +then `bscanf Scanning.stdin "%d" f` reads an integer `n` from the standard input and returns `f n` (that is `n + 1`). Thus, if we evaluate `bscanf stdin "%d" f`, and then enter `41` at the keyboard, the result we get is `42`. +### Formatted input as a functional feature +The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assignment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time. +**Unsynchronized accesses** +Unsynchronized accesses to a [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) may lead to an invalid [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) state. Thus, concurrent accesses to [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)s must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +## Formatted input channel +``` +module Scanning : sig ... end +``` +## Type of formatted input functions +``` +type ('a, 'b, 'c, 'd) scanner = + ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> + 'c +``` +The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic`. +For instance, the [`Scanf.scanf`](./#val-scanf) function below has type `('a, 'b, 'c, 'd) scanner`, since it is a formatted input function that reads from [`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin): `scanf fmt f` applies `f` to the arguments specified by `fmt`, reading those arguments from [`Stdlib.stdin`](./Stdlib.md#val-stdin) as expected. +If the format `fmt` has some `%r` indications, the corresponding formatted input functions must be provided *before* receiver function `f`. For instance, if `read_elem` is an input function for values of type `t`, then `bscanf ic "%r;" read_elem f` reads a value `v` of type `t` followed by a `';'` character, and returns `f v`. +since 3.10 +``` +type ('a, 'b, 'c, 'd) scanner_opt = + ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) format6 -> + 'c +``` +``` +exception Scan_failure of string +``` +When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan_failure`. +## The general formatted input function +``` +val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner +``` +`bscanf ic fmt r1 ... rN f` reads characters from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic` and converts them to values according to format string `fmt`. As a final step, receiver function `f` is applied to the values read and gives the result of the `bscanf` call. +For instance, if `f` is the function `fun s i -> i + 1`, then `Scanf.sscanf "x = 1" "%s = %i" f` returns `2`. +Arguments `r1` to `rN` are user-defined input functions that read the argument corresponding to the `%r` conversions specified in the format string. +``` +val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but returns `None` in case of scanning failure. +since 5.0 +## Format string description +The format string is a character string which contains three types of objects: +- plain characters, which are simply matched with the characters of the input (with a special case for space and line feed, see [The space character in format strings](./#space)), +- conversion specifications, each of which causes reading and conversion of one argument for the function `f` (see [Conversion specifications in format strings](./#conversion)), +- scanning indications to specify boundaries of tokens (see scanning [Scanning indications in format strings](./#indication)). +### The space character in format strings +As mentioned above, a plain character in the format string is just matched with the next character of the input; however, two characters are special exceptions to this rule: the space character (`' '` or ASCII code 32) and the line feed character (`'\n'` or ASCII code 10). A space does not match a single space character, but any amount of 'whitespace' in the input. More precisely, a space inside the format string matches *any number* of tab, space, line feed and carriage return characters. Similarly, a line feed character in the format string matches either a single line feed or a carriage return followed by a line feed. +Matching *any* amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call `bscanf ib "Price = %d $" (fun p -> p)` succeeds and returns `1` when reading an input with various whitespace in it, such as `Price = 1 $`, `Price = 1 $`, or even `Price=1$`. +### Conversion specifications in format strings +Conversion specifications consist in the `%` character, followed by an optional flag, an optional field width, and followed by one or two conversion characters. +The conversion characters and their meanings are: +- `d`: reads an optionally signed decimal integer (`0-9`\+). +- `i`: reads an optionally signed integer (usual input conventions for decimal (`0-9`\+), hexadecimal (`0x[0-9a-f]+` and `0X[0-9A-F]+`), octal (`0o[0-7]+`), and binary (`0b[0-1]+`) notations are understood). +- `u`: reads an unsigned decimal integer. +- `x` or `X`: reads an unsigned hexadecimal integer (`[0-9a-fA-F]+`). +- `o`: reads an unsigned octal integer (`[0-7]+`). +- `s`: reads a string argument that spreads as much as possible, until the following bounding condition holds: + - a whitespace has been found (see [The space character in format strings](./#space)), + - a scanning indication (see scanning [Scanning indications in format strings](./#indication)) has been encountered, + - the end-of-input has been reached. + Hence, this conversion always succeeds: it returns an empty string if the bounding condition holds when the scan begins. +- `S`: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml). +- `c`: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification `%0c`. Raise `Invalid_argument`, if the field width specification is greater than 1\. +- `C`: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml). +- `f`, `e`, `E`, `g`, `G`: reads an optionally signed floating-point number in decimal notation, in the style `dddd.ddd e/E+-dd`. +- `h`, `H`: reads an optionally signed floating-point number in hexadecimal notation. +- `F`: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned). +- `B`: reads a boolean argument (`true` or `false`). +- `b`: reads a boolean argument (for backward compatibility; do not use in new programs). +- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: reads an `int32` argument to the format specified by the second letter for regular integers. +- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: reads a `nativeint` argument to the format specified by the second letter for regular integers. +- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: reads an `int64` argument to the format specified by the second letter for regular integers. +- `[ range ]`: reads characters that matches one of the characters mentioned in the range of characters `range` (or not mentioned in it, if the range starts with `^`). Reads a `string` that can be empty, if the next input character does not match the range. The set of characters from `c1` to `c2` (inclusively) is denoted by `c1-c2`. Hence, `%[0-9]` returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, `%[0-9a-f]` returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the `^` in case of range negation); hence `[]]` matches a `]` character and `[^]]` matches any character that is not `]`. Use `%%` and `%@` to include a `%` or a `@` in a range. +- `r`: user-defined reader. Takes the next `ri` formatted input function and applies it to the scanning buffer `ib` to read the next argument. The input function `ri` must therefore have type `Scanning.in_channel -> 'a` and the argument read has type `'a`. +- `{ fmt %}`: reads a format string argument. The format string read must have the same type as the format string specification `fmt`. For instance, `"%{ %i %}"` reads any format string that can read a value of type `int`; hence, if `s` is the string `"fmt:\"number is %u\""`, then `Scanf.sscanf s "fmt: %{%i%}"` succeeds and returns the format string `"number is %u"`. +- `( fmt %)`: scanning sub-format substitution. Reads a format string `rf` in the input, then goes on scanning with `rf` instead of scanning with `fmt`. The format string `rf` must have the same type as the format string specification `fmt` that it replaces. For instance, `"%( %i %)"` reads any format string that can read a value of type `int`. The conversion returns the format string read `rf`, and then a value read using `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%(%i%)" (fun fmt i -> fmt, i)` evaluates to `("%4d", 1234)`. This behaviour is not mere format substitution, since the conversion returns the format string read as additional argument. If you need pure format substitution, use special flag `_` to discard the extraneous argument: conversion `%_( fmt %)` reads a format string `rf` and then behaves the same as format string `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%_(%i%)"` is simply equivalent to `Scanf.sscanf "1234.00" "%4d"`. +- `l`: returns the number of lines read so far. +- `n`: returns the number of characters read so far. +- `N` or `L`: returns the number of tokens read so far. +- `!`: matches the end of input condition. +- `%`: matches one `%` character in the input. +- `@`: matches one `@` character in the input. +- `,`: does nothing. +Following the `%` character that introduces a conversion, there may be the special flag `_`: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if `f` is the function `fun i -> i + 1`, and `s` is the string `"x = 1"`, then `Scanf.sscanf s "%_s = %i" f` returns `2`. +The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, `%6d` reads an integer, having at most 6 decimal digits; `%4f` reads a float with at most 4 characters; and `%8[\000-\255]` returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input). +Notes: +- as mentioned above, a `%s` conversion always succeeds, even if there is nothing to read in the input: in this case, it simply returns `""`. +- in addition to the relevant digits, `'_'` characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions. +- the `scanf` facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module `Str`), stream parsers, `ocamllex`\-generated lexers, `ocamlyacc`\-generated parsers. +### Scanning indications in format strings +Scanning indications appear just after the string conversions `%s` and `%[ range ]` to delimit the end of the token. A scanning indication is introduced by a `@` character, followed by some plain character `c`. It means that the string token should end just before the next matching `c` (which is skipped). If no `c` character is encountered, the string token spreads as much as possible. For instance, `"%s@\t"` reads a string up to the next tab character or to the end of input. If a `@` character appears anywhere else in the format string, it is treated as a plain character. +Note: +- As usual in format strings, `%` and `@` characters must be escaped using `%%` and `%@`; this rule still holds within range specifications and scanning indications. For instance, format `"%s@%%"` reads a string up to the next `%` character, and format `"%s@%@"` reads a string up to the next `@`. +- The scanning indications introduce slight differences in the syntax of [`Scanf`](#) format strings, compared to those used for the [`Printf`](./Stdlib-Printf.md) module. However, the scanning indications are similar to those used in the [`Format`](./Stdlib-Format.md) module; hence, when producing formatted text to be scanned by [`Scanf.bscanf`](./#val-bscanf), it is wise to use printing functions from the [`Format`](./Stdlib-Format.md) module (or, if you need to use functions from [`Printf`](./Stdlib-Printf.md), banish or carefully double check the format strings that contain `'@'` characters). +### Exceptions during scanning +Scanners may raise the following exceptions when the input cannot be read according to the format string: +- Raise [`Scanf.Scan_failure`](./#exception-Scan_failure) if the input does not match the format. +- Raise `Failure` if a conversion to a number is not possible. +- Raise `End_of_file` if the end of input is encountered while some more characters are needed to read the current conversion specification. +- Raise `Invalid_argument` if the format string is invalid. +Note: +- as a consequence, scanning a `%s` conversion never raises exception `End_of_file`: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or `""` if none were ever read. +## Specialised formatted input functions +``` +val sscanf : string -> ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the given string. +``` +val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt +``` +Same as [`Scanf.sscanf`](./#val-sscanf), but returns `None` in case of scanning failure. +since 5.0 +``` +val scanf : ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the predefined formatted input channel [`Scanf.Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) that is connected to [`Stdlib.stdin`](./Stdlib.md#val-stdin). +``` +val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt +``` +Same as [`Scanf.scanf`](./#val-scanf), but returns `None` in case of scanning failure. +since 5.0 +``` +val kscanf : + Scanning.in_channel -> + (Scanning.in_channel -> exn -> 'd) -> + ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments. +``` +val ksscanf : + string -> + (Scanning.in_channel -> exn -> 'd) -> + ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.kscanf`](./#val-kscanf) but reads from the given string. +since 4.02 +## Reading format strings from input +``` +val bscanf_format : + Scanning.in_channel -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> + 'g +``` +`bscanf_format ic fmt f` reads a format string token from the formatted input channel `ic`, according to the given format string `fmt`, and applies `f` to the resulting format string value. +raises [`Scan_failure`](./#exception-Scan_failure) if the format string value read does not have the same type as fmt. +since 3.09 +``` +val sscanf_format : + string -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> + 'g +``` +Same as [`Scanf.bscanf_format`](./#val-bscanf_format), but reads from the given string. +since 3.09 +``` +val format_from_string : + string -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 +``` +`format_from_string s fmt` converts a string argument to a format string, according to the given format string `fmt`. +raises [`Scan_failure`](./#exception-Scan_failure) if s, considered as a format string, does not have the same type as fmt. +since 3.10 +``` +val unescaped : string -> string +``` +`unescaped s` return a copy of `s` with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, `Scanf.unescaped` has the following property: for all string `s`, `Scanf.unescaped (String.escaped s) = s`. +Always return a copy of the argument, even if there is no escape sequence in the argument. +raises [`Scan_failure`](./#exception-Scan_failure) if s is not properly escaped (i.e. s has invalid escape sequences or special characters that are not properly escaped). For instance, Scanf.unescaped "\\"" will fail. +since 4.00 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Seq.md b/docs/api/melange/Stdlib-Seq.md new file mode 100644 index 000000000..37d85ea05 --- /dev/null +++ b/docs/api/melange/Stdlib-Seq.md @@ -0,0 +1,438 @@ +# Module `Stdlib.Seq` +Sequences. +A sequence of type `'a Seq.t` can be thought of as a **delayed list**, that is, a list whose elements are computed only when they are demanded by a consumer. This allows sequences to be produced and transformed lazily (one element at a time) rather than eagerly (all elements at once). This also allows constructing conceptually infinite sequences. +The type `'a Seq.t` is defined as a synonym for `unit -> 'a Seq.node`. This is a function type: therefore, it is opaque. The consumer can **query** a sequence in order to request the next element (if there is one), but cannot otherwise inspect the sequence in any way. +Because it is opaque, the type `'a Seq.t` does *not* reveal whether a sequence is: +- **persistent**, which means that the sequence can be used as many times as desired, producing the same elements every time, just like an immutable list; or +- **ephemeral**, which means that the sequence is not persistent. Querying an ephemeral sequence might have an observable side effect, such as incrementing a mutable counter. As a common special case, an ephemeral sequence can be **affine**, which means that it must be queried at most once. +It also does *not* reveal whether the elements of the sequence are: +- **pre-computed and stored** in memory, which means that querying the sequence is cheap; +- **computed when first demanded and then stored** in memory, which means that querying the sequence once can be expensive, but querying the same sequence again is cheap; or +- **re-computed every time they are demanded**, which may or may not be cheap. +It is up to the programmer to keep these distinctions in mind so as to understand the time and space requirements of sequences. +For the sake of simplicity, most of the documentation that follows is written under the implicit assumption that the sequences at hand are persistent. We normally do not point out *when* or *how many times* each function is invoked, because that would be too verbose. For instance, in the description of `map`, we write: "if `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`". If we wished to be more explicit, we could point out that the transformation takes place on demand: that is, the elements of `map f xs` are computed only when they are demanded. In other words, the definition `let ys = map f xs` terminates immediately and does not invoke `f`. The function call `f x0` takes place only when the first element of `ys` is demanded, via the function call `ys()`. Furthermore, calling `ys()` twice causes `f x0` to be called twice as well. If one wishes for `f` to be applied at most once to each element of `xs`, even in scenarios where `ys` is queried more than once, then one should use `let ys = memoize (map f xs)`. +As a general rule, the functions that build sequences, such as `map`, `filter`, `scan`, `take`, etc., produce sequences whose elements are computed only on demand. The functions that eagerly consume sequences, such as `is_empty`, `find`, `length`, `iter`, `fold_left`, etc., are the functions that force computation to take place. +When possible, we recommend using sequences rather than dispensers (functions of type `unit -> 'a option` that produce elements upon demand). Whereas sequences can be persistent or ephemeral, dispensers are always ephemeral, and are typically more difficult to work with than sequences. Two conversion functions, [`to_dispenser`](./#val-to_dispenser) and [`of_dispenser`](./#val-of_dispenser), are provided. +since 4.07 +``` +type 'a t = unit -> 'a node +``` +A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. Such a sequence is queried by performing a function application `xs()`. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail. +``` +and +'a node = +``` +``` +| Nil +``` +``` +| Cons of 'a * 'a t +``` +``` + +``` +A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence. +## Consuming sequences +The functions in this section consume their argument, a sequence, either partially or completely: +- `is_empty` and `uncons` consume the sequence down to depth 1\. That is, they demand the first argument of the sequence, if there is one. +- `iter`, `fold_left`, `length`, etc., consume the sequence all the way to its end. They terminate only if the sequence is finite. +- `for_all`, `exists`, `find`, etc. consume the sequence down to a certain depth, which is a priori unpredictable. +Similarly, among the functions that consume two sequences, one can distinguish two groups: +- `iter2` and `fold_left2` consume both sequences all the way to the end, provided the sequences have the same length. +- `for_all2`, `exists2`, `equal`, `compare` consume the sequences down to a certain depth, which is a priori unpredictable. +The functions that consume two sequences can be applied to two sequences of distinct lengths: in that case, the excess elements in the longer sequence are ignored. (It may be the case that one excess element is demanded, even though this element is not used.) +None of the functions in this section is lazy. These functions are consumers: they force some computation to take place. +``` +val is_empty : 'a t -> bool +``` +`is_empty xs` determines whether the sequence `xs` is empty. +It is recommended that the sequence `xs` be persistent. Indeed, `is_empty xs` demands the head of the sequence `xs`, so, if `xs` is ephemeral, it may be the case that `xs` cannot be used any more after this call has taken place. +since 4.14 +``` +val uncons : 'a t -> ('a * 'a t) option +``` +If `xs` is empty, then `uncons xs` is `None`. +If `xs` is nonempty, then `uncons xs` is `Some (x, ys)` where `x` is the head of the sequence and `ys` its tail. +since 4.14 +``` +val length : 'a t -> int +``` +`length xs` is the length of the sequence `xs`. +The sequence `xs` must be finite. +since 4.14 +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right. +It terminates only if the sequence `xs` is finite. +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right. +An accumulator of type `'a` is threaded through the calls to `f`. +It terminates only if the sequence `xs` is finite. +``` +val iteri : (int -> 'a -> unit) -> 'a t -> unit +``` +`iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`. +It terminates only if the sequence `xs` is finite. +`iteri f xs` is equivalent to `iter (fun (i, x) -> f i x) (zip (ints 0) xs)`. +since 4.14 +``` +val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`. +An accumulator of type `'b` is threaded through the calls to `f`. +It terminates only if the sequence `xs` is finite. +`fold_lefti f accu xs` is equivalent to `fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)`. +since 4.14 +``` +val for_all : ('a -> bool) -> 'a t -> bool +``` +`for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`. +The sequence `xs` must be finite. +since 4.14 +``` +val exists : ('a -> bool) -> 'a t -> bool +``` +`exists xs p` determines whether at least one element `x` of the sequence `xs` satisfies `p x`. +The sequence `xs` must be finite. +since 4.14 +``` +val find : ('a -> bool) -> 'a t -> 'a option +``` +`find p xs` returns `Some x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element. +It returns `None` if there is no such element. +The sequence `xs` must be finite. +since 4.14 +``` +val find_index : ('a -> bool) -> 'a t -> int option +``` +`find_index p xs` returns `Some i`, where `i` is the index of the first element of the sequence `xs` that satisfies `p x`, if there is such an element. +It returns `None` if there is no such element. +The sequence `xs` must be finite. +since 5.1 +``` +val find_map : ('a -> 'b option) -> 'a t -> 'b option +``` +`find_map f xs` returns `Some y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`. +It returns `None` if there is no such element. +The sequence `xs` must be finite. +since 4.14 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. +The sequence `xs` must be finite. +since 5.1 +``` +val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit +``` +`iter2 f xs ys` invokes `f x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. +If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. +Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. +`iter2 f xs ys` is equivalent to `iter (fun (x, y) -> f x y) (zip xs ys)`. +since 4.14 +``` +val fold_left2 : ('acc -> 'a -> 'b -> 'acc) -> 'acc -> 'a t -> 'b t -> 'acc +``` +`fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. +An accumulator of type `'a` is threaded through the calls to `f`. +If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. +Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. +`fold_left2 f accu xs ys` is equivalent to `fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)`. +since 4.14 +``` +val for_all2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool +``` +`for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`. +If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if `xs` or `ys` is empty, then `for_all2 p xs ys` is true. This is where `for_all2` and `equal` differ: `equal eq xs ys` can be true only if `xs` and `ys` have the same length. +At least one of the sequences `xs` and `ys` must be finite. +`for_all2 p xs ys` is equivalent to `for_all (fun b -> b) (map2 p xs ys)`. +since 4.14 +``` +val exists2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool +``` +`exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`. +If the sequences `xs` and `ys` have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. +At least one of the sequences `xs` and `ys` must be finite. +`exists2 p xs ys` is equivalent to `exists (fun b -> b) (map2 p xs ys)`. +since 4.14 +``` +val equal : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool +``` +Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal. +At least one of the sequences `xs` and `ys` must be finite. +since 4.14 +``` +val compare : ('a -> 'b -> int) -> 'a t -> 'b t -> int +``` +Provided the function `cmp` defines a preorder on elements, `compare cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder. +For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). +At least one of the sequences `xs` and `ys` must be finite. +since 4.14 +## Constructing sequences +The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. +``` +val empty : 'a t +``` +`empty` is the empty sequence. It has no elements. Its length is 0. +``` +val return : 'a -> 'a t +``` +`return x` is the sequence whose sole element is `x`. Its length is 1\. +``` +val cons : 'a -> 'a t -> 'a t +``` +`cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`. +Writing `cons (f()) xs` causes the function call `f()` to take place immediately. For this call to be delayed until the sequence is queried, one must instead write `(fun () -> Cons(f(), xs))`. +since 4.11 +``` +val init : int -> (int -> 'a) -> 'a t +``` +`init n f` is the sequence `f 0; f 1; ...; f (n-1)`. +`n` must be nonnegative. +If desired, the infinite sequence `f 0; f 1; ...` can be defined as `map f (ints 0)`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.14 +``` +val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t +``` +`unfold` constructs a sequence out of a step function and an initial state. +If `f u` is `None` then `unfold f u` is the empty sequence. If `f u` is `Some (x, u')` then `unfold f u` is the nonempty sequence `cons x (unfold f u')`. +For example, `unfold (function [] -> None | h :: t -> Some (h, t)) l` is equivalent to `List.to_seq l`. +since 4.11 +``` +val repeat : 'a -> 'a t +``` +`repeat x` is the infinite sequence where the element `x` is repeated indefinitely. +`repeat x` is equivalent to `cycle (return x)`. +since 4.14 +``` +val forever : (unit -> 'a) -> 'a t +``` +`forever f` is an infinite sequence where every element is produced (on demand) by the function call `f()`. +For instance, `forever Random.bool` is an infinite sequence of random bits. +`forever f` is equivalent to `map f (repeat ())`. +since 4.14 +``` +val cycle : 'a t -> 'a t +``` +`cycle xs` is the infinite sequence that consists of an infinite number of repetitions of the sequence `xs`. +If `xs` is an empty sequence, then `cycle xs` is empty as well. +Consuming (a prefix of) the sequence `cycle xs` once can cause the sequence `xs` to be consumed more than once. Therefore, `xs` must be persistent. +since 4.14 +``` +val iterate : ('a -> 'a) -> 'a -> 'a t +``` +`iterate f x` is the infinite sequence whose elements are `x`, `f x`, `f (f x)`, and so on. +In other words, it is the orbit of the function `f`, starting at `x`. +since 4.14 +## Transforming sequences +The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f xs` is the image of the sequence `xs` through the transformation `f`. +If `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`. +``` +val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t +``` +`mapi` is analogous to `map`, but applies the function `f` to an index and an element. +`mapi f xs` is equivalent to `map2 f (ints 0) xs`. +since 4.14 +``` +val filter : ('a -> bool) -> 'a t -> 'a t +``` +`filter p xs` is the sequence of the elements `x` of `xs` that satisfy `p x`. +In other words, `filter p xs` is the sequence `xs`, deprived of the elements `x` such that `p x` is false. +``` +val filter_map : ('a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`. +`filter_map f xs` is equivalent to `map Option.get (filter Option.is_some (map f xs))`. +``` +val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t +``` +If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators `[a0; a1; a2; ...]` where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on. +Thus, `scan f a0 xs` is conceptually related to `fold_left f a0 xs`. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators. +For instance, `scan (+) 0` transforms a sequence of integers into the sequence of its partial sums. +If `xs` has length `n` then `scan f a0 xs` has length `n+1`. +since 4.14 +``` +val take : int -> 'a t -> 'a t +``` +`take n xs` is the sequence of the first `n` elements of `xs`. +If `xs` has fewer than `n` elements, then `take n xs` is equivalent to `xs`. +`n` must be nonnegative. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.14 +``` +val drop : int -> 'a t -> 'a t +``` +`drop n xs` is the sequence `xs`, deprived of its first `n` elements. +If `xs` has fewer than `n` elements, then `drop n xs` is empty. +`n` must be nonnegative. +`drop` is lazy: the first `n+1` elements of the sequence `xs` are demanded only when the first element of `drop n xs` is demanded. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.14 +``` +val take_while : ('a -> bool) -> 'a t -> 'a t +``` +`take_while p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`. +since 4.14 +``` +val drop_while : ('a -> bool) -> 'a t -> 'a t +``` +`drop_while p xs` is the sequence `xs`, deprived of the prefix `take_while p xs`. +since 4.14 +``` +val group : ('a -> 'a -> bool) -> 'a t -> 'a t t +``` +Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`. +Every element of `group eq xs` is a nonempty sequence of equal elements. +The concatenation `concat (group eq xs)` is equal to `xs`. +Consuming `group eq xs`, and consuming the sequences that it contains, can cause `xs` to be consumed more than once. Therefore, `xs` must be persistent. +since 4.14 +``` +val memoize : 'a t -> 'a t +``` +The sequence `memoize xs` has the same elements as the sequence `xs`. +Regardless of whether `xs` is ephemeral or persistent, `memoize xs` is persistent: even if it is queried several times, `xs` is queried at most once. +The construction of the sequence `memoize xs` internally relies on suspensions provided by the module [`Lazy`](./Stdlib-Lazy.md). These suspensions are *not* thread-safe. Therefore, the sequence `memoize xs` must *not* be queried by multiple threads concurrently. +since 4.14 +``` +exception Forced_twice +``` +This exception is raised when a sequence returned by [`once`](./#val-once) (or a suffix of it) is queried more than once. +since 4.14 +``` +val once : 'a t -> 'a t +``` +The sequence `once xs` has the same elements as the sequence `xs`. +Regardless of whether `xs` is ephemeral or persistent, `once xs` is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception `Forced_twice` is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once. +raises [`Forced_twice`](./#exception-Forced_twice) if once xs, or a suffix of it, is queried more than once. +since 4.14 +``` +val transpose : 'a t t -> 'a t t +``` +If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`. +The rows of the matrix `xss` are not required to have the same length. +The matrix `xss` is not required to be finite (in either direction). +The matrix `xss` must be persistent. +since 4.14 +## Combining sequences +``` +val append : 'a t -> 'a t -> 'a t +``` +`append xs ys` is the concatenation of the sequences `xs` and `ys`. +Its elements are the elements of `xs`, followed by the elements of `ys`. +since 4.11 +``` +val concat : 'a t t -> 'a t +``` +If `xss` is a sequence of sequences, then `concat xss` is its concatenation. +If `xss` is the sequence `xs0; xs1; ...` then `concat xss` is the sequence `xs0 @ xs1 @ ...`. +since 4.13 +``` +val flat_map : ('a -> 'b t) -> 'a t -> 'b t +``` +`flat_map f xs` is equivalent to `concat (map f xs)`. +``` +val concat_map : ('a -> 'b t) -> 'a t -> 'b t +``` +`concat_map f xs` is equivalent to `concat (map f xs)`. +`concat_map` is an alias for `flat_map`. +since 4.13 +``` +val zip : 'a t -> 'b t -> ('a * 'b) t +``` +`zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`. +If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. +`zip xs ys` is equivalent to `map2 (fun a b -> (a, b)) xs ys`. +since 4.14 +``` +val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t +``` +`map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`. +If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. +`map2 f xs ys` is equivalent to `map (fun (x, y) -> f x y) (zip xs ys)`. +since 4.14 +``` +val interleave : 'a t -> 'a t -> 'a t +``` +`interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on. +When one of the sequences `xs` and `ys` is exhausted, `interleave xs ys` continues with the rest of the other sequence. +since 4.14 +``` +val sorted_merge : ('a -> 'a -> int) -> 'a t -> 'a t -> 'a t +``` +If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`. +For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). +since 4.14 +``` +val product : 'a t -> 'b t -> ('a * 'b) t +``` +`product xs ys` is the Cartesian product of the sequences `xs` and `ys`. +For every element `x` of `xs` and for every element `y` of `ys`, the pair `(x, y)` appears once as an element of `product xs ys`. +The order in which the pairs appear is unspecified. +The sequences `xs` and `ys` are not required to be finite. +The sequences `xs` and `ys` must be persistent. +since 4.14 +``` +val map_product : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t +``` +The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`. +For every element `x` of `xs` and for every element `y` of `ys`, the element `f x y` appears once as an element of `map_product f xs ys`. +The order in which these elements appear is unspecified. +The sequences `xs` and `ys` are not required to be finite. +The sequences `xs` and `ys` must be persistent. +`map_product f xs ys` is equivalent to `map (fun (x, y) -> f x y) (product xs ys)`. +since 4.14 +## Splitting a sequence into two sequences +``` +val unzip : ('a * 'b) t -> 'a t * 'b t +``` +`unzip` transforms a sequence of pairs into a pair of sequences. +`unzip xs` is equivalent to `(map fst xs, map snd xs)`. +Querying either of the sequences returned by `unzip xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `unzip (memoize xs)`. +since 4.14 +``` +val split : ('a * 'b) t -> 'a t * 'b t +``` +`split` is an alias for `unzip`. +since 4.14 +``` +val partition_map : ('a -> ('b, 'c) Either.t) -> 'a t -> 'b t * 'c t +``` +`partition_map f xs` returns a pair of sequences `(ys, zs)`, where: +- `ys` is the sequence of the elements `y` such that `f x = Left y`, where `x` ranges over `xs`; +- `zs` is the sequence of the elements `z` such that `f x = Right z`, where `x` ranges over `xs`. +`partition_map f xs` is equivalent to a pair of `filter_map Either.find_left (map f xs)` and `filter_map Either.find_right (map f xs)`. +Querying either of the sequences returned by `partition_map f xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `partition_map f (memoize xs)`. +since 4.14 +``` +val partition : ('a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition p xs` returns a pair of the subsequence of the elements of `xs` that satisfy `p` and the subsequence of the elements of `xs` that do not satisfy `p`. +`partition p xs` is equivalent to `filter p xs, filter (fun x -> not (p x)) xs`. +Consuming both of the sequences returned by `partition p xs` causes `xs` to be consumed twice and causes the function `f` to be applied twice to each element of the list. Therefore, `f` should be pure and cheap. Furthermore, `xs` should be persistent and cheap. If that is not the case, use `partition p (memoize xs)`. +since 4.14 +## Converting between sequences and dispensers +A dispenser is a representation of a sequence as a function of type `unit -> 'a option`. Every time this function is invoked, it returns the next element of the sequence. When there are no more elements, it returns `None`. A dispenser has mutable internal state, therefore is ephemeral: the sequence that it represents can be consumed at most once. +``` +val of_dispenser : (unit -> 'a option) -> 'a t +``` +`of_dispenser it` is the sequence of the elements produced by the dispenser `it`. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use `memoize (of_dispenser it)`. +since 4.14 +``` +val to_dispenser : 'a t -> unit -> 'a option +``` +`to_dispenser xs` is a fresh dispenser on the sequence `xs`. +This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently. +since 4.14 +## Sequences of integers +``` +val ints : int -> int t +``` +`ints i` is the infinite sequence of the integers beginning at `i` and counting up. +since 4.14 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md new file mode 100644 index 000000000..bce17bb85 --- /dev/null +++ b/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md @@ -0,0 +1,9 @@ +# Parameter `Make.Ord` +``` +type t +``` +The type of the set elements. +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set-Make.md b/docs/api/melange/Stdlib-Set-Make.md new file mode 100644 index 000000000..f248d8dbe --- /dev/null +++ b/docs/api/melange/Stdlib-Set-Make.md @@ -0,0 +1,225 @@ +# Module `Set.Make` +Functor building an implementation of the set structure given a totally ordered type. +## Parameters +``` +module Ord : OrderedType +``` +## Signature +## Sets +``` +type elt = Ord.t +``` +The type of the set elements. +``` +type t +``` +The type of sets. +``` +val empty : t +``` +The empty set. +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. +``` +val inter : t -> t -> t +``` +Set intersection. +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. +``` +val cardinal : t -> int +``` +Return the number of elements of a set. +## Elements +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +since 4.05 +## Searching +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. +since 4.05 +``` +val find_first : (elt -> bool) -> t -> elt +``` +`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. +since 4.05 +``` +val find_first_opt : (elt -> bool) -> t -> elt option +``` +`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +``` +val find_last : (elt -> bool) -> t -> elt +``` +`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +since 4.05 +``` +val find_last_opt : (elt -> bool) -> t -> elt option +``` +`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +## Traversing +``` +val iter : (elt -> unit) -> t -> unit +``` +`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. +``` +val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. +## Transforming +``` +val map : (elt -> elt) -> t -> t +``` +`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) +since 4.04 +``` +val filter : (elt -> bool) -> t -> t +``` +`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val filter_map : (elt -> elt option) -> t -> t +``` +`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. +For example, +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. +since 4.11 +``` +val partition : (elt -> bool) -> t -> t * t +``` +`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. +## Predicates and comparisons +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. +``` +val for_all : (elt -> bool) -> t -> bool +``` +`for_all f s` checks if all elements of the set satisfy the predicate `f`. +``` +val exists : (elt -> bool) -> t -> bool +``` +`exists f s` checks if at least one element of the set satisfies the predicate `f`. +## Converting +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set-module-type-OrderedType.md b/docs/api/melange/Stdlib-Set-module-type-OrderedType.md new file mode 100644 index 000000000..38b071184 --- /dev/null +++ b/docs/api/melange/Stdlib-Set-module-type-OrderedType.md @@ -0,0 +1,10 @@ +# Module type `Set.OrderedType` +Input signature of the functor [`Make`](./Stdlib-Set-Make.md). +``` +type t +``` +The type of the set elements. +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set-module-type-S.md b/docs/api/melange/Stdlib-Set-module-type-S.md new file mode 100644 index 000000000..dbd3b7007 --- /dev/null +++ b/docs/api/melange/Stdlib-Set-module-type-S.md @@ -0,0 +1,220 @@ +# Module type `Set.S` +Output signature of the functor [`Make`](./Stdlib-Set-Make.md). +## Sets +``` +type elt +``` +The type of the set elements. +``` +type t +``` +The type of sets. +``` +val empty : t +``` +The empty set. +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. +``` +val inter : t -> t -> t +``` +Set intersection. +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. +``` +val cardinal : t -> int +``` +Return the number of elements of a set. +## Elements +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-Set-Make.md). +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. +since 4.05 +## Searching +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. +since 4.05 +``` +val find_first : (elt -> bool) -> t -> elt +``` +`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. +since 4.05 +``` +val find_first_opt : (elt -> bool) -> t -> elt option +``` +`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +``` +val find_last : (elt -> bool) -> t -> elt +``` +`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. +since 4.05 +``` +val find_last_opt : (elt -> bool) -> t -> elt option +``` +`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. +since 4.05 +## Traversing +``` +val iter : (elt -> unit) -> t -> unit +``` +`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. +``` +val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. +## Transforming +``` +val map : (elt -> elt) -> t -> t +``` +`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) +since 4.04 +``` +val filter : (elt -> bool) -> t -> t +``` +`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). +before 4.03 Physical equality was not ensured. +``` +val filter_map : (elt -> elt option) -> t -> t +``` +`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. +For example, +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. +since 4.11 +``` +val partition : (elt -> bool) -> t -> t * t +``` +`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. +## Predicates and comparisons +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. +``` +val for_all : (elt -> bool) -> t -> bool +``` +`for_all f s` checks if all elements of the set satisfy the predicate `f`. +``` +val exists : (elt -> bool) -> t -> bool +``` +`exists f s` checks if at least one element of the set satisfies the predicate `f`. +## Converting +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set.md b/docs/api/melange/Stdlib-Set.md new file mode 100644 index 000000000..67f1c9b14 --- /dev/null +++ b/docs/api/melange/Stdlib-Set.md @@ -0,0 +1,31 @@ +# Module `Stdlib.Set` +Sets over ordered types. +This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. +The [`Make`](./Stdlib-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: +```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 PairsSet = Set.Make(IntPairs) + + let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) +``` +This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-Set-Make.md). +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-Set-Make.md). +``` +module Make (Ord : OrderedType) : S with type elt = Ord.t +``` +Functor building an implementation of the set structure given a totally ordered type. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Stack.md b/docs/api/melange/Stdlib-Stack.md new file mode 100644 index 000000000..d6cfffb21 --- /dev/null +++ b/docs/api/melange/Stdlib-Stack.md @@ -0,0 +1,85 @@ +# Module `Stdlib.Stack` +Last-in first-out stacks. +This module implements stacks (LIFOs), with in-place modification. +**Unsynchronized accesses** +Unsynchronized accesses to a stack may lead to an invalid queue state. Thus, concurrent accesses to stacks must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +``` +type !'a t +``` +The type of stacks containing elements of type `'a`. +``` +exception Empty +``` +Raised when [`Stack.pop`](./#val-pop) or [`Stack.top`](./#val-top) is applied to an empty stack. +``` +val create : unit -> 'a t +``` +Return a new stack, initially empty. +``` +val push : 'a -> 'a t -> unit +``` +`push x s` adds the element `x` at the top of stack `s`. +``` +val pop : 'a t -> 'a +``` +`pop s` removes and returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. +``` +val pop_opt : 'a t -> 'a option +``` +`pop_opt s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty. +since 4.08 +``` +val drop : 'a t -> unit +``` +`drop s` removes the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. +since 5.1 +``` +val top : 'a t -> 'a +``` +`top s` returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. +``` +val top_opt : 'a t -> 'a option +``` +`top_opt s` returns the topmost element in stack `s`, or `None` if the stack is empty. +since 4.08 +``` +val clear : 'a t -> unit +``` +Discard all elements from a stack. +``` +val copy : 'a t -> 'a t +``` +Return a copy of the given stack. +``` +val is_empty : 'a t -> bool +``` +Return `true` if the given stack is empty, `false` otherwise. +``` +val length : 'a t -> int +``` +Return the number of elements in a stack. Time complexity O(1) +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f s` applies `f` in turn to all elements of `s`, from the element at the top of the stack to the element at the bottom of the stack. The stack itself is unchanged. +``` +val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold f accu s` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1` is the top of the stack, `x2` the second element, and `xn` the bottom element. The stack is unchanged. +since 4.03 +## Stacks and Sequences +``` +val to_seq : 'a t -> 'a Seq.t +``` +Iterate on the stack, top to bottom. It is safe to modify the stack during iteration. +since 4.07 +``` +val add_seq : 'a t -> 'a Seq.t -> unit +``` +Add the elements from the sequence on the top of the stack. +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a t +``` +Create a stack from the sequence. +since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-StdLabels.md b/docs/api/melange/Stdlib-StdLabels.md new file mode 100644 index 000000000..44581af3e --- /dev/null +++ b/docs/api/melange/Stdlib-StdLabels.md @@ -0,0 +1,22 @@ +# Module `Stdlib.StdLabels` +Standard labeled libraries. +This meta-module provides versions of the [`Array`](./Stdlib-ArrayLabels.md), [`Bytes`](./Stdlib-BytesLabels.md), [`List`](./Stdlib-ListLabels.md) and [`String`](./Stdlib-StringLabels.md) modules where function arguments are systematically labeled. It is intended to be opened at the top of source files, as shown below. +```ocaml + open StdLabels + + let to_upper = String.map ~f:Char.uppercase_ascii + let seq len = List.init ~f:(fun i -> i) ~len + let everything = Array.create_matrix ~dimx:42 ~dimy:42 42 +``` +``` +module Array = ArrayLabels +``` +``` +module Bytes = BytesLabels +``` +``` +module List = ListLabels +``` +``` +module String = StringLabels +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-String.md b/docs/api/melange/Stdlib-String.md new file mode 100644 index 000000000..0e73d1b47 --- /dev/null +++ b/docs/api/melange/Stdlib-String.md @@ -0,0 +1,369 @@ +# Module `Stdlib.String` +Strings. +A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. +The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. +``` +positions 0 1 2 3 4 n-1 n + +---+---+---+---+ +-----+ + indices | 0 | 1 | 2 | 3 | ... | n-1 | + +---+---+---+---+ +-----+ +``` +- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. +- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. +Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. +**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. +**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +## Strings +``` +type t = string +``` +The type for strings. +``` +val make : int -> char -> string +``` +`make n c` is a string of length `n` with each index holding the character `c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> (int -> char) -> string +``` +`init n f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +since 4.02 +``` +val empty : string +``` +The empty string. +since 4.13 +``` +val length : string -> int +``` +`length s` is the length (number of bytes/characters) of `s`. +``` +val get : string -> int -> char +``` +`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. +``` +val of_bytes : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. +since 4.13 +``` +val to_bytes : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. +since 4.13 +``` +val blit : string -> int -> bytes -> int -> int -> unit +``` +Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. +## Concatenating +**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. +``` +val concat : string -> string list -> string +``` +`concat sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : string -> string -> string +``` +`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.13 +## Predicates and comparisons +``` +val equal : t -> t -> bool +``` +`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. +since 4.03 (4.05 in StringLabels) +``` +val compare : t -> t -> int +``` +`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. +``` +val starts_with : prefix:string -> string -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. +since 4.13 +``` +val ends_with : suffix:string -> string -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. +since 4.13 +``` +val contains_from : string -> int -> char -> bool +``` +`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : string -> int -> char -> bool +``` +`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val contains : string -> char -> bool +``` +`contains s c` is [`String.contains_from`](./#val-contains_from)` s 0 c`. +## Extracting substrings +``` +val sub : string -> int -> int -> string +``` +`sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. +``` +val split_on_char : char -> string -> string list +``` +`split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. +The function's result is specified by the following invariants: +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). +- No string in the result contains the `sep` character. +since 4.04 (4.05 in StringLabels) +## Transforming +``` +val map : (char -> char) -> string -> string +``` +`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. +since 4.00 +``` +val mapi : (int -> char -> char) -> string -> string +``` +`mapi f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. +since 4.02 +``` +val fold_left : ('acc -> char -> 'acc) -> 'acc -> string -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. +since 4.13 +``` +val fold_right : (char -> 'acc -> 'acc) -> string -> 'acc -> 'acc +``` +`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. +since 4.13 +``` +val for_all : (char -> bool) -> string -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. +since 4.13 +``` +val exists : (char -> bool) -> string -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. +since 4.13 +``` +val trim : string -> string +``` +`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. +since 4.00 +``` +val escaped : string -> string +``` +`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. +All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). +The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val uppercase_ascii : string -> string +``` +`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +``` +val lowercase_ascii : string -> string +``` +`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +``` +val capitalize_ascii : string -> string +``` +`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +``` +val uncapitalize_ascii : string -> string +``` +`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +## Traversing +``` +val iter : (char -> unit) -> string -> unit +``` +`iter f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. +``` +val iteri : (int -> char -> unit) -> string -> unit +``` +`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. +since 4.00 +## Searching +``` +val index_from : string -> int -> char -> int +``` +`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +``` +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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : string -> int -> char -> int +``` +`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +``` +val rindex_from_opt : string -> int -> char -> int option +``` +`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val index : string -> char -> int +``` +`index s c` is [`String.index_from`](./#val-index_from)` s 0 c`. +``` +val index_opt : string -> char -> int option +``` +`index_opt s c` is [`String.index_from_opt`](./#val-index_from_opt)` s 0 c`. +since 4.05 +``` +val rindex : string -> char -> int +``` +`rindex s c` is [`String.rindex_from`](./#val-rindex_from)` s (length s - 1) c`. +``` +val rindex_opt : string -> char -> int option +``` +`rindex_opt s c` is [`String.rindex_from_opt`](./#val-rindex_from_opt)` s (length s - 1) c`. +since 4.05 +## Strings and Sequences +``` +val to_seq : t -> char Seq.t +``` +`to_seq s` is a sequence made of the string's characters in increasing order. +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +`of_seq s` is a string made of the sequence's characters. +since 4.07 +## UTF decoding and validations +since 4.14 +### UTF-8 +``` +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`. +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. +### UTF-16BE +``` +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`. +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. +### UTF-16LE +``` +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`. +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. +## Binary decoding of integers +The functions in this section binary decode integers from strings. +All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. +``` +val get_uint8 : string -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. +since 4.13 +``` +val get_int8 : string -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. +since 4.13 +``` +val get_uint16_ne : string -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_uint16_be : string -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_uint16_le : string -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int16_ne : string -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int16_be : string -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int16_le : string -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int32_ne : string -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. +since 4.13 +``` +val hash : t -> int +``` +An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.0 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.0 +``` +val get_int32_be : string -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. +since 4.13 +``` +val get_int32_le : string -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. +since 4.13 +``` +val get_int64_ne : string -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. +since 4.13 +``` +val get_int64_be : string -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. +since 4.13 +``` +val get_int64_le : string -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. +since 4.13 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-StringLabels.md b/docs/api/melange/Stdlib-StringLabels.md new file mode 100644 index 000000000..13fd18a72 --- /dev/null +++ b/docs/api/melange/Stdlib-StringLabels.md @@ -0,0 +1,375 @@ +# Module `Stdlib.StringLabels` +Strings. +A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. +The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. +``` +positions 0 1 2 3 4 n-1 n + +---+---+---+---+ +-----+ + indices | 0 | 1 | 2 | 3 | ... | n-1 | + +---+---+---+---+ +-----+ +``` +- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. +- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. +Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. +**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. +**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. +## Strings +``` +type t = string +``` +The type for strings. +``` +val make : int -> char -> string +``` +`make n c` is a string of length `n` with each index holding the character `c`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> f:(int -> char) -> string +``` +`init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +since 4.02 +``` +val empty : string +``` +The empty string. +since 4.13 +``` +val length : string -> int +``` +`length s` is the length (number of bytes/characters) of `s`. +``` +val get : string -> int -> char +``` +`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. +``` +val of_bytes : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. +since 4.13 +``` +val to_bytes : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. +since 4.13 +``` +val blit : + src:string -> + src_pos:int -> + dst:bytes -> + dst_pos:int -> + len:int -> + unit +``` +Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. +## Concatenating +**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. +``` +val concat : sep:string -> string list -> string +``` +`concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : string -> string -> string +``` +`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.13 +## Predicates and comparisons +``` +val equal : t -> t -> bool +``` +`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. +since 4.03 (4.05 in StringLabels) +``` +val compare : t -> t -> int +``` +`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. +``` +val starts_with : prefix:string -> string -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. +since 4.13 +``` +val ends_with : suffix:string -> string -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. +since 4.13 +``` +val contains_from : string -> int -> char -> bool +``` +`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : string -> int -> char -> bool +``` +`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val contains : string -> char -> bool +``` +`contains s c` is [`String.contains_from`](./Stdlib-String.md#val-contains_from)` s 0 c`. +## Extracting substrings +``` +val sub : string -> pos:int -> len:int -> string +``` +`sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. +``` +val split_on_char : sep:char -> string -> string list +``` +`split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. +The function's result is specified by the following invariants: +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). +- No string in the result contains the `sep` character. +since 4.04 (4.05 in StringLabels) +## Transforming +``` +val map : f:(char -> char) -> string -> string +``` +`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. +since 4.00 +``` +val mapi : f:(int -> char -> char) -> string -> string +``` +`mapi ~f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. +since 4.02 +``` +val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> string -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. +since 4.13 +``` +val fold_right : f:(char -> 'acc -> 'acc) -> string -> init:'acc -> 'acc +``` +`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. +since 4.13 +``` +val for_all : f:(char -> bool) -> string -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. +since 4.13 +``` +val exists : f:(char -> bool) -> string -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. +since 4.13 +``` +val trim : string -> string +``` +`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. +since 4.00 +``` +val escaped : string -> string +``` +`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. +All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). +The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val uppercase_ascii : string -> string +``` +`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +``` +val lowercase_ascii : string -> string +``` +`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +``` +val capitalize_ascii : string -> string +``` +`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +``` +val uncapitalize_ascii : string -> string +``` +`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. +since 4.03 (4.05 in StringLabels) +## Traversing +``` +val iter : f:(char -> unit) -> string -> unit +``` +`iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. +``` +val iteri : f:(int -> char -> unit) -> string -> unit +``` +`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. +since 4.00 +## Searching +``` +val index_from : string -> int -> char -> int +``` +`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +``` +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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : string -> int -> char -> int +``` +`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +``` +val rindex_from_opt : string -> int -> char -> int option +``` +`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val index : string -> char -> int +``` +`index s c` is [`String.index_from`](./Stdlib-String.md#val-index_from)` s 0 c`. +``` +val index_opt : string -> char -> int option +``` +`index_opt s c` is [`String.index_from_opt`](./Stdlib-String.md#val-index_from_opt)` s 0 c`. +since 4.05 +``` +val rindex : string -> char -> int +``` +`rindex s c` is [`String.rindex_from`](./Stdlib-String.md#val-rindex_from)` s (length s - 1) c`. +``` +val rindex_opt : string -> char -> int option +``` +`rindex_opt s c` is [`String.rindex_from_opt`](./Stdlib-String.md#val-rindex_from_opt)` s (length s - 1) c`. +since 4.05 +## Strings and Sequences +``` +val to_seq : t -> char Seq.t +``` +`to_seq s` is a sequence made of the string's characters in increasing order. +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +`of_seq s` is a string made of the sequence's characters. +since 4.07 +## UTF decoding and validations +since 4.14 +### UTF-8 +``` +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`. +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. +### UTF-16BE +``` +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`. +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. +### UTF-16LE +``` +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`. +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. +## Binary decoding of integers +The functions in this section binary decode integers from strings. +All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. +``` +val get_uint8 : string -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. +since 4.13 +``` +val get_int8 : string -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. +since 4.13 +``` +val get_uint16_ne : string -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_uint16_be : string -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_uint16_le : string -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int16_ne : string -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int16_be : string -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int16_le : string -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. +since 4.13 +``` +val get_int32_ne : string -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. +since 4.13 +``` +val hash : t -> int +``` +An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.0 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.0 +``` +val get_int32_be : string -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. +since 4.13 +``` +val get_int32_le : string -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. +since 4.13 +``` +val get_int64_ne : string -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. +since 4.13 +``` +val get_int64_be : string -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. +since 4.13 +``` +val get_int64_le : string -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. +since 4.13 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md new file mode 100644 index 000000000..de6fd038a --- /dev/null +++ b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md @@ -0,0 +1,4 @@ +# Parameter `Make.Immediate` +``` +type t +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md new file mode 100644 index 000000000..7bf3d87cb --- /dev/null +++ b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md @@ -0,0 +1,4 @@ +# Parameter `Make.Non_immediate` +``` +type t +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make.md b/docs/api/melange/Stdlib-Sys-Immediate64-Make.md new file mode 100644 index 000000000..8a6519de3 --- /dev/null +++ b/docs/api/melange/Stdlib-Sys-Immediate64-Make.md @@ -0,0 +1,27 @@ +# Module `Immediate64.Make` +## Parameters +``` +module Immediate : Immediate +``` +``` +module Non_immediate : Non_immediate +``` +## Signature +``` +type t +``` +``` +type 'a repr = +``` +``` +| Immediate : Immediate.t repr +``` +``` +| Non_immediate : Non_immediate.t repr +``` +``` + +``` +``` +val repr : t repr +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md new file mode 100644 index 000000000..fafc06698 --- /dev/null +++ b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md @@ -0,0 +1,4 @@ +# Module type `Immediate64.Immediate` +``` +type t +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md new file mode 100644 index 000000000..44ae90f2d --- /dev/null +++ b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md @@ -0,0 +1,4 @@ +# Module type `Immediate64.Non_immediate` +``` +type t +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64.md b/docs/api/melange/Stdlib-Sys-Immediate64.md new file mode 100644 index 000000000..f70c82e15 --- /dev/null +++ b/docs/api/melange/Stdlib-Sys-Immediate64.md @@ -0,0 +1,15 @@ +# Module `Sys.Immediate64` +This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. +since 4.10 +``` +module type Non_immediate = sig ... end +``` +``` +module type Immediate = sig ... end +``` +``` +module Make + (Immediate : Immediate) + (Non_immediate : Non_immediate) : + sig ... end +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys.md b/docs/api/melange/Stdlib-Sys.md new file mode 100644 index 000000000..2d898a9cf --- /dev/null +++ b/docs/api/melange/Stdlib-Sys.md @@ -0,0 +1,391 @@ +# Module `Stdlib.Sys` +System interface. +Every function in this module raises `Sys_error` with an informative message when the underlying system call signal an error. +``` +val argv : string array +``` +The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program. +``` +val executable_name : string +``` +The name of the file containing the executable currently running. This name may be absolute or relative to the current directory, depending on the platform and whether the program was compiled to bytecode or a native executable. +``` +val file_exists : string -> bool +``` +Test if a file with the given name exists. +``` +val is_directory : string -> bool +``` +Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file. +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. +since 3.10 +``` +val is_regular_file : string -> bool +``` +Returns `true` if the given name refers to a regular file, `false` if it refers to another kind of file. +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. +since 5.1 +``` +val remove : string -> unit +``` +Remove the given file name from the file system. +``` +val rename : string -> string -> unit +``` +Rename a file or directory. `rename oldpath newpath` renames the file or directory called `oldpath`, giving it `newpath` as its new name, moving it between (parent) directories if needed. If a file named `newpath` already exists, its contents will be replaced with those of `oldpath`. Depending on the operating system, the metadata (permissions, owner, etc) of `newpath` can either be preserved or be replaced by those of `oldpath`. +since 4.06 concerning the "replace existing file" behavior +``` +val getenv : string -> string +``` +Return the value associated to a variable in the process environment. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if the variable is unbound. +``` +val getenv_opt : string -> string option +``` +Return the value associated to a variable in the process environment or `None` if the variable is unbound. +since 4.05 +``` +val command : string -> int +``` +Execute the given shell command and return its exit code. +The argument of [`Sys.command`](./#val-command) is generally the name of a command followed by zero, one or several arguments, separated by whitespace. The given argument is interpreted by a shell: either the Windows shell `cmd.exe` for the Win32 ports of OCaml, or the POSIX shell `sh` for other ports. It can contain shell builtin commands such as `echo`, and also special characters such as file redirections `>` and `<`, which will be honored by the shell. +Conversely, whitespace or special shell characters occurring in command names or in their arguments must be quoted or escaped so that the shell does not interpret them. The quoting rules vary between the POSIX shell and the Windows shell. The [`Filename.quote_command`](./Stdlib-Filename.md#val-quote_command) performs the appropriate quoting given a command name, a list of arguments, and optional file redirections. +``` +val time : unit -> float +``` +Return the processor time, in seconds, used by the program since the beginning of execution. +``` +val chdir : string -> unit +``` +Change the current working directory of the process. +``` +val mkdir : string -> int -> unit +``` +Create a directory with the given permissions. +since 4.12 +``` +val rmdir : string -> unit +``` +Remove an empty directory. +since 4.12 +``` +val getcwd : unit -> string +``` +Return the current working directory of the process. +``` +val readdir : string -> string array +``` +Return the names of all files present in the given directory. Names denoting the current directory and the parent directory (`"."` and `".."` in Unix) are not returned. Each string in the result is a file name rather than a complete path. There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order. +``` +val interactive : bool ref +``` +This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`. +alert unsynchronized\_access The interactive status is a mutable global state. +``` +val os_type : string +``` +Operating system currently executing the OCaml program. One of +- `"Unix"` (for all Unix versions, including Linux and Mac OS X), +- `"Win32"` (for MS-Windows, OCaml compiled with MSVC++ or MinGW-w64), +- `"Cygwin"` (for MS-Windows, OCaml compiled with Cygwin). +``` +type backend_type = +``` +``` +| Native +``` +``` +| Bytecode +``` +``` +| Other of string +``` +``` + +``` +Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript. +since 4.04 +``` +val backend_type : backend_type +``` +Backend type currently executing the OCaml program. +since 4.04 +``` +val unix : bool +``` +True if `Sys.os_type = "Unix"`. +since 4.01 +``` +val win32 : bool +``` +True if `Sys.os_type = "Win32"`. +since 4.01 +``` +val cygwin : bool +``` +True if `Sys.os_type = "Cygwin"`. +since 4.01 +``` +val word_size : int +``` +Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64. +``` +val int_size : int +``` +Size of `int`, in bits. It is 31 (resp. 63) when using OCaml on a 32-bit (resp. 64-bit) platform. It may differ for other implementations, e.g. it can be 32 bits when compiling to JavaScript. +since 4.03 +``` +val big_endian : bool +``` +Whether the machine currently executing the Caml program is big-endian. +since 4.00 +``` +val max_string_length : int +``` +Maximum length of strings and byte sequences. +``` +val max_array_length : int +``` +Maximum length of a normal array (i.e. any array whose elements are not of type `float`). The maximum length of a `float array` is `max_floatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with `--disable-flat-float-array`. +``` +val max_floatarray_length : int +``` +Maximum length of a floatarray. This is also the maximum length of a `float array` when OCaml is configured with `--enable-flat-float-array`. +``` +val runtime_variant : unit -> string +``` +Return the name of the runtime variant the program is running on. This is normally the argument given to `-runtime-variant` at compile time, but for byte-code it can be changed after compilation. +since 4.03 +``` +val runtime_parameters : unit -> string +``` +Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable. +since 4.03 +## Signal handling +``` +type signal_behavior = +``` +``` +| Signal_default +``` +``` +| Signal_ignore +``` +``` +| Signal_handle of int -> unit +``` +``` + +``` +What to do when receiving a signal: +- `Signal_default`: take the default behavior (usually: abort the program) +- `Signal_ignore`: ignore the signal +- `Signal_handle f`: call function `f`, giving it the signal number as argument. +``` +val signal : int -> signal_behavior -> signal_behavior +``` +Set the behavior of the system on receipt of a given signal. The first argument is the signal number. Return the behavior previously associated with the signal. If the signal number is invalid (or not available on your system), an `Invalid_argument` exception is raised. +``` +val set_signal : int -> signal_behavior -> unit +``` +Same as [`Sys.signal`](./#val-signal) but return value is ignored. +### Signal numbers for the standard POSIX signals. +``` +val sigabrt : int +``` +Abnormal termination +``` +val sigalrm : int +``` +Timeout +``` +val sigfpe : int +``` +Arithmetic exception +``` +val sighup : int +``` +Hangup on controlling terminal +``` +val sigill : int +``` +Invalid hardware instruction +``` +val sigint : int +``` +Interactive interrupt (ctrl-C) +``` +val sigkill : int +``` +Termination (cannot be ignored) +``` +val sigpipe : int +``` +Broken pipe +``` +val sigquit : int +``` +Interactive termination +``` +val sigsegv : int +``` +Invalid memory reference +``` +val sigterm : int +``` +Termination +``` +val sigusr1 : int +``` +Application-defined signal 1 +``` +val sigusr2 : int +``` +Application-defined signal 2 +``` +val sigchld : int +``` +Child process terminated +``` +val sigcont : int +``` +Continue +``` +val sigstop : int +``` +Stop +``` +val sigtstp : int +``` +Interactive stop +``` +val sigttin : int +``` +Terminal read from background process +``` +val sigttou : int +``` +Terminal write from background process +``` +val sigvtalrm : int +``` +Timeout in virtual time +``` +val sigprof : int +``` +Profiling interrupt +``` +val sigbus : int +``` +Bus error +since 4.03 +``` +val sigpoll : int +``` +Pollable event +since 4.03 +``` +val sigsys : int +``` +Bad argument to routine +since 4.03 +``` +val sigtrap : int +``` +Trace/breakpoint trap +since 4.03 +``` +val sigurg : int +``` +Urgent condition on socket +since 4.03 +``` +val sigxcpu : int +``` +Timeout in cpu time +since 4.03 +``` +val sigxfsz : int +``` +File size limit exceeded +since 4.03 +``` +exception Break +``` +Exception raised on interactive interrupt if [`Sys.catch_break`](./#val-catch_break) is enabled. +``` +val catch_break : bool -> unit +``` +`catch_break` governs whether interactive interrupt (ctrl-C) terminates the program or raises the `Break` exception. Call `catch_break true` to enable raising `Break`, and `catch_break false` to let the system terminate the program on user interrupt. +Inside multi-threaded programs, the `Break` exception will arise in any one of the active threads, and will keep arising on further interactive interrupt until all threads are terminated. Use signal masks from `Thread.sigmask` to direct the interrupt towards a specific thread. +``` +val ocaml_version : string +``` +`ocaml_version` is the version of OCaml. It is a string of the form `"major.minor[.patchlevel][(+|~)additional-info]"`, where `major`, `minor`, and `patchlevel` are integers, and `additional-info` is an arbitrary string. The `[.patchlevel]` part was absent before version 3.08.0 and became mandatory from 3.08.0 onwards. The `[(+|~)additional-info]` part may be absent. +``` +val development_version : bool +``` +`true` if this is a development version, `false` otherwise. +since 4.14 +``` +type extra_prefix = +``` +``` +| Plus +``` +``` +| Tilde +``` +since 4.14 +``` + +``` +``` +type extra_info = extra_prefix * string +``` +since 4.14 +``` +type ocaml_release_info = { +``` +`major : int;` +`minor : int;` +`patchlevel : int;` +`extra : extra_info option;` +``` +} +``` +since 4.14 +``` +val ocaml_release : ocaml_release_info +``` +`ocaml_release` is the version of OCaml. +since 4.14 +``` +val enable_runtime_warnings : bool -> unit +``` +Control whether the OCaml runtime system can emit warnings on stderr. Currently, the only supported warning is triggered when a channel created by `open_*` functions is finalized without being closed. Runtime warnings are disabled by default. +since 4.03 +alert unsynchronized\_access The status of runtime warnings is a mutable global state. +``` +val runtime_warnings_enabled : unit -> bool +``` +Return whether runtime warnings are currently enabled. +since 4.03 +alert unsynchronized\_access The status of runtime warnings is a mutable global state. +## Optimization +``` +val opaque_identity : 'a -> 'a +``` +For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function. +At runtime, `opaque_identity` disappears altogether. However, it does prevent the argument from being garbage collected until the location where the call would have occurred. +A typical use of this function is to prevent pure computations from being optimized away in benchmarking loops. For example: +```ocaml + for _round = 1 to 100_000 do + ignore (Sys.opaque_identity (my_pure_computation ())) + done +``` +since 4.03 +``` +module Immediate64 : sig ... end +``` +This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Type-Id.md b/docs/api/melange/Stdlib-Type-Id.md new file mode 100644 index 000000000..98f28171f --- /dev/null +++ b/docs/api/melange/Stdlib-Type-Id.md @@ -0,0 +1,66 @@ +# Module `Type.Id` +Type identifiers. +A type identifier is a value that denotes a type. Given two type identifiers, they can be tested for [equality](./#val-provably_equal) to prove they denote the same type. Note that: +- Unequal identifiers do not imply unequal types: a given type can be denoted by more than one identifier. +- Type identifiers can be marshalled, but they get a new, distinct, identity on unmarshalling, so the equalities are lost. +See an [example](./#example) of use. +## Type identifiers +``` +type !'a t +``` +The type for identifiers for type `'a`. +``` +val make : unit -> 'a t +``` +`make ()` is a new type identifier. +``` +val uid : 'a t -> int +``` +`uid id` is a runtime unique identifier for `id`. +``` +val provably_equal : 'a t -> 'b t -> ('a, 'b) eq option +``` +`provably_equal i0 i1` is `Some Equal` if identifier `i0` is equal to `i1` and `None` otherwise. +## Example +The following shows how type identifiers can be used to implement a simple heterogeneous key-value dictionary. In contrast to [`Stdlib.Map`](./Stdlib-Map.md) values whose keys map to a single, homogeneous type of values, this dictionary can associate a different type of value to each key. +```ocaml +(** Heterogeneous dictionaries. *) +module Dict : sig + type t + (** The type for dictionaries. *) + + type 'a key + (** The type for keys binding values of type ['a]. *) + + val key : unit -> 'a key + (** [key ()] is a new dictionary key. *) + + val empty : t + (** [empty] is the empty dictionary. *) + + val add : 'a key -> 'a -> t -> t + (** [add k v d] is [d] with [k] bound to [v]. *) + + val remove : 'a key -> t -> t + (** [remove k d] is [d] with the last binding of [k] removed. *) + + val find : 'a key -> t -> 'a option + (** [find k d] is the binding of [k] in [d], if any. *) +end = struct + type 'a key = 'a Type.Id.t + type binding = B : 'a key * 'a -> binding + type t = (int * binding) list + + let key () = Type.Id.make () + let empty = [] + let add k v d = (Type.Id.uid k, B (k, v)) :: d + let remove k d = List.remove_assoc (Type.Id.uid k) d + let find : type a. a key -> t -> a option = fun k d -> + match List.assoc_opt (Type.Id.uid k) d with + | None -> None + | Some (B (k', v)) -> + match Type.Id.provably_equal k k' with + | Some Type.Equal -> Some v + | None -> assert false +end +``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Type.md b/docs/api/melange/Stdlib-Type.md new file mode 100644 index 000000000..9b35f29fc --- /dev/null +++ b/docs/api/melange/Stdlib-Type.md @@ -0,0 +1,25 @@ +# Module `Stdlib.Type` +Type introspection. +since 5.1 +## Type equality witness +``` +type (_, _) eq = +``` +``` +| Equal : ('a, 'a) eq +``` +``` + +``` +The purpose of `eq` is to represent type equalities that may not otherwise be known by the type checker (e.g. because they may depend on dynamic data). +A value of type `(a, b) eq` represents the fact that types `a` and `b` are equal. +If one has a value `eq : (a, b) eq` that proves types `a` and `b` are equal, one can use it to convert a value of type `a` to a value of type `b` by pattern matching on `Equal`: +```ocaml + let cast (type a) (type b) (Equal : (a, b) Type.eq) (a : a) : b = a +``` +At runtime, this function simply returns its second argument unchanged. +## Type identifiers +``` +module Id : sig ... end +``` +Type identifiers. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Uchar.md b/docs/api/melange/Stdlib-Uchar.md new file mode 100644 index 000000000..050ef27cb --- /dev/null +++ b/docs/api/melange/Stdlib-Uchar.md @@ -0,0 +1,114 @@ +# Module `Stdlib.Uchar` +Unicode characters. +since 4.03 +``` +type t +``` +The type for Unicode characters. +A value of this type represents a Unicode [scalar value](http://unicode.org/glossary/#unicode_scalar_value) which is an integer in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`. +``` +val min : t +``` +`min` is U+0000. +``` +val max : t +``` +`max` is U+10FFFF. +``` +val bom : t +``` +`bom` is U+FEFF, the [byte order mark](http://unicode.org/glossary/#byte_order_mark) (BOM) character. +since 4.06 +``` +val rep : t +``` +`rep` is U+FFFD, the [replacement](http://unicode.org/glossary/#replacement_character) character. +since 4.06 +``` +val succ : t -> t +``` +`succ u` is the scalar value after `u` in the set of Unicode scalar values. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is max. +``` +val pred : t -> t +``` +`pred u` is the scalar value before `u` in the set of Unicode scalar values. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is min. +``` +val is_valid : int -> bool +``` +`is_valid n` is `true` if and only if `n` is a Unicode scalar value (i.e. in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`). +``` +val of_int : int -> t +``` +`of_int i` is `i` as a Unicode character. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i does not satisfy is\_valid. +``` +val to_int : t -> int +``` +`to_int u` is `u` as an integer. +``` +val is_char : t -> bool +``` +`is_char u` is `true` if and only if `u` is a latin1 OCaml character. +``` +val of_char : char -> t +``` +`of_char c` is `c` as a Unicode character. +``` +val to_char : t -> char +``` +`to_char u` is `u` as an OCaml latin1 character. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u does not satisfy is\_char. +``` +val equal : t -> t -> bool +``` +`equal u u'` is `u = u'`. +``` +val compare : t -> t -> int +``` +`compare u u'` is `Stdlib.compare u u'`. +``` +val seeded_hash : int -> t -> int +``` +`seeded_hash seed u` A seeded hash function with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). +since 5.3 +``` +val hash : t -> int +``` +An unseeded hash function with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). +since 5.3 +## UTF codecs tools +since 4.14 +``` +type utf_decode +``` +The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt. +``` +val utf_decode_is_valid : utf_decode -> bool +``` +`utf_decode_is_valid d` is `true` if and only if `d` holds a valid decode. +``` +val utf_decode_uchar : utf_decode -> t +``` +`utf_decode_uchar d` is the Unicode character decoded by `d` if `utf_decode_is_valid d` is `true` and [`Uchar.rep`](./#val-rep) otherwise. +``` +val utf_decode_length : utf_decode -> int +``` +`utf_decode_length d` is the number of elements from the source that were consumed by the decode `d`. This is always strictly positive and smaller or equal to `4`. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes. +``` +val utf_decode : int -> t -> utf_decode +``` +`utf_decode n u` is a valid UTF decode for `u` that consumed `n` elements from the source for decoding. `n` must be positive and smaller or equal to `4` (this is not checked by the module). +``` +val utf_decode_invalid : int -> utf_decode +``` +`utf_decode_invalid n` is an invalid UTF decode that consumed `n` elements from the source to error. `n` must be positive and smaller or equal to `4` (this is not checked by the module). The resulting decode has [`rep`](./#val-rep) as the decoded Unicode character. +``` +val utf_8_byte_length : t -> int +``` +`utf_8_byte_length u` is the number of bytes needed to encode `u` in UTF-8. +``` +val utf_16_byte_length : t -> int +``` +`utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Unit.md b/docs/api/melange/Stdlib-Unit.md new file mode 100644 index 000000000..bdb64c57f --- /dev/null +++ b/docs/api/melange/Stdlib-Unit.md @@ -0,0 +1,27 @@ +# Module `Stdlib.Unit` +Unit values. +since 4.08 +## The unit type +``` +type t = unit = +``` +``` +| () +``` +``` + +``` +The unit type. +The constructor `()` is included here so that it has a path, but it is not intended to be used in user-defined data types. +``` +val equal : t -> t -> bool +``` +`equal u1 u2` is `true`. +``` +val compare : t -> t -> int +``` +`compare u1 u2` is `0`. +``` +val to_string : t -> string +``` +`to_string b` is `"()"`. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md b/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md new file mode 100644 index 000000000..492b57f0f --- /dev/null +++ b/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md @@ -0,0 +1,16 @@ +# Parameter `Make.H` +``` +type t +``` +The type of the hashtable keys. +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Weak-Make.md b/docs/api/melange/Stdlib-Weak-Make.md new file mode 100644 index 000000000..9ba485f93 --- /dev/null +++ b/docs/api/melange/Stdlib-Weak-Make.md @@ -0,0 +1,69 @@ +# Module `Weak.Make` +Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. +## Parameters +``` +module H : Hashtbl.HashedType +``` +## Signature +``` +type data = H.t +``` +The type of the elements stored in the table. +``` +type t +``` +The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. +``` +val create : int -> t +``` +`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. +``` +val clear : t -> unit +``` +Remove all elements from the table. +``` +val merge : t -> data -> data +``` +`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. +``` +val add : t -> data -> unit +``` +`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. +``` +val remove : t -> data -> unit +``` +`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. +``` +val find : t -> data -> data +``` +`find t x` returns an instance of `x` found in `t`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. +``` +val find_opt : t -> data -> data option +``` +`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. +since 4.05 +``` +val find_all : t -> data -> data list +``` +`find_all t x` returns a list of all the instances of `x` found in `t`. +``` +val mem : t -> data -> bool +``` +`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. +``` +val iter : (data -> unit) -> t -> unit +``` +`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. +``` +val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. +``` +val count : t -> int +``` +Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. +``` +val stats : t -> int * int * int * int * int * int +``` +Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Weak-module-type-S.md b/docs/api/melange/Stdlib-Weak-module-type-S.md new file mode 100644 index 000000000..526daebd0 --- /dev/null +++ b/docs/api/melange/Stdlib-Weak-module-type-S.md @@ -0,0 +1,64 @@ +# Module type `Weak.S` +The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). +``` +type data +``` +The type of the elements stored in the table. +``` +type t +``` +The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. +``` +val create : int -> t +``` +`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. +``` +val clear : t -> unit +``` +Remove all elements from the table. +``` +val merge : t -> data -> data +``` +`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. +``` +val add : t -> data -> unit +``` +`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. +``` +val remove : t -> data -> unit +``` +`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. +``` +val find : t -> data -> data +``` +`find t x` returns an instance of `x` found in `t`. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. +``` +val find_opt : t -> data -> data option +``` +`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. +since 4.05 +``` +val find_all : t -> data -> data list +``` +`find_all t x` returns a list of all the instances of `x` found in `t`. +``` +val mem : t -> data -> bool +``` +`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. +``` +val iter : (data -> unit) -> t -> unit +``` +`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. +``` +val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. +``` +val count : t -> int +``` +Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. +``` +val stats : t -> int * int * int * int * int * int +``` +Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Weak.md b/docs/api/melange/Stdlib-Weak.md new file mode 100644 index 000000000..c1c3c0d4e --- /dev/null +++ b/docs/api/melange/Stdlib-Weak.md @@ -0,0 +1,64 @@ +# Module `Stdlib.Weak` +Arrays of weak pointers and hash sets of weak pointers. +## Low-level functions +``` +type !'a t +``` +The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program. Note that finalisation functions are run before the weak pointers are erased, because the finalisation functions can make values alive again (before 4.03 the finalisation functions were run after). +A weak pointer is said to be full if it points to a value, empty if the value was erased by the GC. +Notes: +- Integers are not allocated and cannot be stored in weak arrays. +- Weak arrays cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) nor the functions of the [`Marshal`](./Stdlib-Marshal.md) module. +``` +val create : int -> 'a t +``` +`Weak.create n` returns a new weak array of length `n`. All the pointers are initially empty. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not comprised between zero and Obj.Ephemeron.max\_ephe\_length (limits included). +``` +val length : 'a t -> int +``` +`Weak.length ar` returns the length (number of elements) of `ar`. +``` +val set : 'a t -> int -> 'a option -> unit +``` +`Weak.set ar n (Some el)` sets the `n`th cell of `ar` to be a (full) pointer to `el`; `Weak.set ar n None` sets the `n`th cell of `ar` to empty. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +``` +val get : 'a t -> int -> 'a option +``` +`Weak.get ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is the value) if it is full. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +``` +val get_copy : 'a t -> int -> 'a option +``` +`Weak.get_copy ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is a (shallow) copy of the value) if it is full. In addition to pitfalls with mutable values, the interesting difference with `get` is that `get_copy` does not prevent the incremental GC from erasing the value in its current cycle (`get` may delay the erasure to the next GC cycle). +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +If the element is a custom block it is not copied. +``` +val check : 'a t -> int -> bool +``` +`Weak.check ar n` returns `true` if the `n`th cell of `ar` is full, `false` if it is empty. Note that even if `Weak.check ar n` returns `true`, a subsequent [`Weak.get`](./#val-get)` ar n` can return `None`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +``` +val fill : 'a t -> int -> int -> 'a option -> unit +``` +`Weak.fill ar ofs len el` sets to `el` all pointers of `ar` from `ofs` to `ofs + len - 1`. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid subarray of ar. +``` +val blit : 'a t -> int -> 'a t -> int -> int -> unit +``` +`Weak.blit ar1 off1 ar2 off2 len` copies `len` weak pointers from `ar1` (starting at `off1`) to `ar2` (starting at `off2`). It works correctly even if `ar1` and `ar2` are the same. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off1 and len do not designate a valid subarray of ar1, or if off2 and len do not designate a valid subarray of ar2. +## Weak hash sets +A weak hash set is a hashed set of values. Each value may magically disappear from the set when it is not used by the rest of the program any more. This is normally used to share data structures without inducing memory leaks. Weak hash sets are defined on values from a [`Hashtbl.HashedType`](./Stdlib-Hashtbl-module-type-HashedType.md) module; the `equal` relation and `hash` function are taken from that module. We will say that `v` is an instance of `x` if `equal x v` is `true`. +The `equal` relation must be able to work on a shallow copy of the values and give the same result as with the values themselves. +**Unsynchronized accesses** +Unsynchronized accesses to weak hash sets are a programming error. Unsynchronized accesses to a weak hash set may lead to an invalid weak hash set state. Thus, concurrent accesses to weak hash sets must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). +``` +module type S = sig ... end +``` +The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). +``` +module Make (H : Hashtbl.HashedType) : S with type data = H.t +``` +Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. \ No newline at end of file diff --git a/docs/api/melange/Stdlib.md b/docs/api/melange/Stdlib.md new file mode 100644 index 000000000..0a260bb84 --- /dev/null +++ b/docs/api/melange/Stdlib.md @@ -0,0 +1,1216 @@ +# Module `Stdlib` +The OCaml Standard library. +This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by `Stdlib`. +In particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the [standard library modules](./#modules). +## Exceptions +``` +val raise : exn -> 'a +``` +Raise the given exception value +``` +val raise_notrace : exn -> 'a +``` +A faster version `raise` which does not record the backtrace. +since 4.02 +``` +val invalid_arg : string -> 'a +``` +Raise exception `Invalid_argument` with the given string. +``` +val failwith : string -> 'a +``` +Raise exception `Failure` with the given string. +``` +exception Exit +``` +The `Exit` exception is not raised by any library function. It is provided for use in your programs. +``` +exception Match_failure of string * int * int +``` +Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number). +``` +exception Assert_failure of string * int * int +``` +Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number). +``` +exception Invalid_argument of string +``` +Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it. +``` +exception Failure of string +``` +Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure \_ instead). +``` +exception Not_found +``` +Exception raised by search functions when the desired object could not be found. +``` +exception Out_of_memory +``` +Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.) +``` +exception Stack_overflow +``` +Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program. +Before 4.10, it was not fully implemented by the native-code compiler. +``` +exception Sys_error of string +``` +Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys\_error \_ instead). +``` +exception End_of_file +``` +Exception raised by input functions to signal that the end of file has been reached. +``` +exception Division_by_zero +``` +Exception raised by integer division and remainder operations when their second argument is zero. +``` +exception Sys_blocked_io +``` +A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel. +``` +exception Undefined_recursive_module of string * int * int +``` +Exception raised when an ill-founded recursive module definition is evaluated. The arguments are the location of the definition in the source code (file name, line number, column number). +## Comparisons +``` +val (=) : 'a -> 'a -> bool +``` +`e1 = e2` tests for structural equality of `e1` and `e2`. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises `Invalid_argument`. Equality between cyclic data structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (<>) : 'a -> 'a -> bool +``` +Negation of [`Stdlib.(=)`](./#val-\(=\)). Left-associative operator, see `Ocaml_operators` for more information. +``` +val (<) : 'a -> 'a -> bool +``` +See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. +``` +val (>) : 'a -> 'a -> bool +``` +See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. +``` +val (<=) : 'a -> 'a -> bool +``` +See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. +``` +val (>=) : 'a -> 'a -> bool +``` +Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with `( = )`. As in the case of `( = )`, mutable structures are compared by contents. Comparison between functional values raises `Invalid_argument`. Comparison between cyclic structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. +``` +val compare : 'a -> 'a -> int +``` +`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. The ordering implemented by `compare` is compatible with the comparison predicates `=`, `<` and `>` defined above, with one difference on the treatment of the float value [`Stdlib.nan`](./#val-nan). Namely, the comparison predicates treat `nan` as different from any other float value, including itself; while `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. +`compare` applied to functional values may raise `Invalid_argument`. `compare` applied to cyclic structures may not terminate. +The `compare` function can be used as the comparison function required by the [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md) functors, as well as the [`List.sort`](./Stdlib-List.md#val-sort) and [`Array.sort`](./Stdlib-Array.md#val-sort) functions. +``` +val min : 'a -> 'a -> 'a +``` +``` +val max : 'a -> 'a -> 'a +``` +``` +val (==) : 'a -> 'a -> bool +``` +`e1 == e2` tests for physical equality of `e1` and `e2`. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, `e1 == e2` is true if and only if physical modification of `e1` also affects `e2`. On non-mutable types, the behavior of `( == )` is implementation-dependent; however, it is guaranteed that `e1 == e2` implies `compare e1 e2 = 0`. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (!=) : 'a -> 'a -> bool +``` +Negation of [`Stdlib.(==)`](./#val-\(==\)). Left-associative operator, see `Ocaml_operators` for more information. +## Boolean operations +``` +val not : bool -> bool +``` +The boolean negation. +``` +val (&&) : bool -> bool -> bool +``` +The boolean 'and'. Evaluation is sequential, left-to-right: in `e1 && e2`, `e1` is evaluated first, and if it returns `false`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. +``` +val (||) : bool -> bool -> bool +``` +The boolean 'or'. Evaluation is sequential, left-to-right: in `e1 || e2`, `e1` is evaluated first, and if it returns `true`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. +## Debugging +``` +val __LOC__ : string +``` +`__LOC__` returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". +since 4.02 +``` +val __FILE__ : string +``` +`__FILE__` returns the name of the file currently being parsed by the compiler. +since 4.02 +``` +val __LINE__ : int +``` +`__LINE__` returns the line number at which this expression appears in the file currently being parsed by the compiler. +since 4.02 +``` +val __MODULE__ : string +``` +`__MODULE__` returns the module name of the file being parsed by the compiler. +since 4.02 +``` +val __POS__ : string * int * int * int +``` +`__POS__` returns a tuple `(file,lnum,cnum,enum)`, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. +since 4.02 +``` +val __FUNCTION__ : string +``` +`__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes. +since 4.12 +``` +val __LOC_OF__ : 'a -> string * 'a +``` +`__LOC_OF__ expr` returns a pair `(loc, expr)` where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". +since 4.02 +``` +val __LINE_OF__ : 'a -> int * 'a +``` +`__LINE_OF__ expr` returns a pair `(line, expr)`, where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler. +since 4.02 +``` +val __POS_OF__ : 'a -> (string * int * int * int) * 'a +``` +`__POS_OF__ expr` returns a pair `(loc,expr)`, where `loc` is a tuple `(file,lnum,cnum,enum)` corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. +since 4.02 +## Composition operators +``` +val (|>) : 'a -> ('a -> 'b) -> 'b +``` +Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. Left-associative operator, see `Ocaml_operators` for more information. +since 4.01 +``` +val (@@) : ('a -> 'b) -> 'a -> 'b +``` +Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. Right-associative operator, see `Ocaml_operators` for more information. +since 4.01 +## Integer arithmetic +Integers are `Sys.int_size` bits wide. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. +``` +val (~-) : int -> int +``` +Unary negation. You can also write `- e` instead of `~- e`. Unary operator, see `Ocaml_operators` for more information. +``` +val (~+) : int -> int +``` +Unary addition. You can also write `+ e` instead of `~+ e`. Unary operator, see `Ocaml_operators` for more information. +since 3.12 +``` +val succ : int -> int +``` +`succ x` is `x + 1`. +``` +val pred : int -> int +``` +`pred x` is `x - 1`. +``` +val (+) : int -> int -> int +``` +Integer addition. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (-) : int -> int -> int +``` +Integer subtraction. Left-associative operator, , see `Ocaml_operators` for more information. +``` +val (*) : int -> int -> int +``` +Integer multiplication. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (/) : int -> int -> int +``` +Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if `x >= 0` and `y > 0`, `x / y` is the greatest integer less than or equal to the real quotient of `x` by `y`. Moreover, `(- x) / y = x / (- y) = - (x / y)`. Left-associative operator, see `Ocaml_operators` for more information. +raises [`Division_by_zero`](./#exception-Division_by_zero) if the second argument is 0. +``` +val (mod) : int -> int -> int +``` +Integer remainder. If `y` is not zero, the result of `x mod y` satisfies the following properties: `x = (x / y) * y + x mod y` and `abs(x mod y) <= abs(y) - 1`. If `y = 0`, `x mod y` raises `Division_by_zero`. Note that `x mod y` is negative only if `x < 0`. Left-associative operator, see `Ocaml_operators` for more information. +raises [`Division_by_zero`](./#exception-Division_by_zero) if y is zero. +``` +val abs : int -> int +``` +`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. +``` +val max_int : int +``` +The greatest representable integer. +``` +val min_int : int +``` +The smallest representable integer. +### Bitwise operations +``` +val (land) : int -> int -> int +``` +Bitwise logical and. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (lor) : int -> int -> int +``` +Bitwise logical or. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (lxor) : int -> int -> int +``` +Bitwise logical exclusive or. Left-associative operator, see `Ocaml_operators` for more information. +``` +val lnot : int -> int +``` +Bitwise logical negation. +``` +val (lsl) : int -> int -> int +``` +`n lsl m` shifts `n` to the left by `m` bits. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. +``` +val (lsr) : int -> int -> int +``` +`n lsr m` shifts `n` to the right by `m` bits. This is a logical shift: zeroes are inserted regardless of the sign of `n`. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. +``` +val (asr) : int -> int -> int +``` +`n asr m` shifts `n` to the right by `m` bits. This is an arithmetic shift: the sign bit of `n` is replicated. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. +## Floating-point arithmetic +OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... +``` +val (~-.) : float -> float +``` +Unary negation. You can also write `-. e` instead of `~-. e`. Unary operator, see `Ocaml_operators` for more information. +``` +val (~+.) : float -> float +``` +Unary addition. You can also write `+. e` instead of `~+. e`. Unary operator, see `Ocaml_operators` for more information. +since 3.12 +``` +val (+.) : float -> float -> float +``` +Floating-point addition. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (-.) : float -> float -> float +``` +Floating-point subtraction. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (*.) : float -> float -> float +``` +Floating-point multiplication. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (/.) : float -> float -> float +``` +Floating-point division. Left-associative operator, see `Ocaml_operators` for more information. +``` +val (**) : float -> float -> float +``` +Exponentiation. +``` +val sqrt : float -> float +``` +Square root. +``` +val exp : float -> float +``` +Exponential. +``` +val log : float -> float +``` +Natural logarithm. +``` +val log10 : float -> float +``` +Base 10 logarithm. +``` +val expm1 : float -> float +``` +`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. +since 3.12.0 +``` +val log1p : float -> float +``` +`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. +since 3.12.0 +``` +val cos : float -> float +``` +Cosine. Argument is in radians. +``` +val sin : float -> float +``` +Sine. Argument is in radians. +``` +val tan : float -> float +``` +Tangent. Argument is in radians. +``` +val acos : float -> float +``` +Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. +``` +val asin : float -> float +``` +Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. +``` +val atan : float -> float +``` +Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. +``` +val atan2 : float -> float -> float +``` +`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. +``` +val hypot : float -> float -> float +``` +`hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. +since 4.00.0 +``` +val cosh : float -> float +``` +Hyperbolic cosine. Argument is in radians. +``` +val sinh : float -> float +``` +Hyperbolic sine. Argument is in radians. +``` +val tanh : float -> float +``` +Hyperbolic tangent. Argument is in radians. +``` +val acosh : float -> float +``` +Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. +since 4.13.0 +``` +val asinh : float -> float +``` +Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. +since 4.13.0 +``` +val atanh : float -> float +``` +Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. +since 4.13.0 +``` +val ceil : float -> float +``` +Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. +``` +val floor : float -> float +``` +Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. +``` +val abs_float : float -> float +``` +`abs_float f` returns the absolute value of `f`. +``` +val copysign : float -> float -> float +``` +`copysign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. +since 4.00 +``` +val mod_float : float -> float -> float +``` +`mod_float a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. +``` +val frexp : float -> float * int +``` +`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. +``` +val ldexp : float -> int -> float +``` +`ldexp x n` returns `x *. 2 ** n`. +``` +val modf : float -> float * float +``` +`modf f` returns the pair of the fractional and integral part of `f`. +``` +val float : int -> float +``` +Same as [`Stdlib.float_of_int`](./#val-float_of_int). +``` +val float_of_int : int -> float +``` +Convert an integer to floating-point. +``` +val truncate : float -> int +``` +Same as [`Stdlib.int_of_float`](./#val-int_of_float). +``` +val int_of_float : float -> int +``` +Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. +``` +val infinity : float +``` +Positive infinity. +``` +val neg_infinity : float +``` +Negative infinity. +``` +val nan : float +``` +``` +val max_float : float +``` +The largest positive finite value of type `float`. +``` +val min_float : float +``` +The smallest positive, non-zero, non-denormalized value of type `float`. +``` +val epsilon_float : float +``` +The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. +``` +type fpclass = +``` +``` +| FP_normal +``` +Normal number, none of the below +``` +| FP_subnormal +``` +Number very close to 0.0, has reduced precision +``` +| FP_zero +``` +Number is 0.0 or \-0.0 +``` +| FP_infinite +``` +Number is positive or negative infinity +``` +| FP_nan +``` +Not a number: result of an undefined operation +``` + +``` +The five classes of floating-point numbers, as determined by the [`Stdlib.classify_float`](./#val-classify_float) function. +``` +val classify_float : float -> fpclass +``` +## String operations +More string operations are provided in module [`String`](./Stdlib-String.md). +``` +val (^) : string -> string -> string +``` +String concatenation. Right-associative operator, see `Ocaml_operators` for more information. +raises [`Invalid_argument`](./#exception-Invalid_argument) if the result is longer then than Sys.max\_string\_length bytes. +## Character operations +More character operations are provided in module [`Char`](./Stdlib-Char.md). +``` +val int_of_char : char -> int +``` +Return the ASCII code of the argument. +``` +val char_of_int : int -> char +``` +Return the character with the given ASCII code. +raises [`Invalid_argument`](./#exception-Invalid_argument) if the argument is outside the range 0--255. +## Unit operations +``` +val ignore : 'a -> unit +``` +Discard the value of its argument and return `()`. For instance, `ignore(f x)` discards the result of the side-effecting function `f`. It is equivalent to `f x; ()`, except that the latter may generate a compiler warning; writing `ignore(f x)` instead avoids the warning. +## String conversion functions +``` +val string_of_bool : bool -> string +``` +Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly. +``` +val bool_of_string_opt : string -> bool option +``` +Convert the given string to a boolean. +Return `None` if the string is not `"true"` or `"false"`. +since 4.05 +``` +val bool_of_string : string -> bool +``` +Same as [`Stdlib.bool_of_string_opt`](./#val-bool_of_string_opt), but raise `Invalid_argument "bool_of_string"` instead of returning `None`. +``` +val string_of_int : int -> string +``` +Return the string representation of an integer, in decimal. +``` +val int_of_string_opt : string -> int option +``` +Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with `0u`), in hexadecimal (if it begins with `0x` or `0X`), in octal (if it begins with `0o` or `0O`), or in binary (if it begins with `0b` or `0B`). +The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*max_int+1]`. If the input exceeds [`max_int`](./#val-max_int) it is converted to the signed integer `min_int + input - max_int - 1`. +The `_` (underscore) character can appear anywhere in the string and is ignored. +Return `None` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int`. +since 4.05 +``` +val int_of_string : string -> int +``` +Same as [`Stdlib.int_of_string_opt`](./#val-int_of_string_opt), but raise `Failure "int_of_string"` instead of returning `None`. +``` +val string_of_float : float -> string +``` +Return a string representation of a floating-point number. +This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). +``` +val float_of_string_opt : string -> float option +``` +Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). +The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. +The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. +In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. +The `_` (underscore) character can appear anywhere in the string and is ignored. +Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. +Return `None` if the given string is not a valid representation of a float. +since 4.05 +``` +val float_of_string : string -> float +``` +Same as [`Stdlib.float_of_string_opt`](./#val-float_of_string_opt), but raise `Failure "float_of_string"` instead of returning `None`. +## Pair operations +``` +val fst : ('a * 'b) -> 'a +``` +Return the first component of a pair. +``` +val snd : ('a * 'b) -> 'b +``` +Return the second component of a pair. +## List operations +More list operations are provided in module [`List`](./Stdlib-List.md). +``` +val (@) : 'a list -> 'a list -> 'a list +``` +`l0 @ l1` appends `l1` to `l0`. Same function as [`List.append`](./Stdlib-List.md#val-append). Right-associative operator, see `Ocaml_operators` for more information. +since 5.1 this function is tail-recursive. +## Input/output +Note: all input/output functions can raise `Sys_error` when the system calls they invoke fail. +``` +type in_channel +``` +The type of input channel. +``` +type out_channel +``` +The type of output channel. +``` +val stdin : in_channel +``` +The standard input for the process. +``` +val stdout : out_channel +``` +The standard output for the process. +``` +val stderr : out_channel +``` +The standard error output for the process. +### Output functions on standard output +``` +val print_char : char -> unit +``` +Print a character on standard output. +``` +val print_string : string -> unit +``` +Print a string on standard output. +``` +val print_bytes : bytes -> unit +``` +Print a byte sequence on standard output. +since 4.02 +``` +val print_int : int -> unit +``` +Print an integer, in decimal, on standard output. +``` +val print_float : float -> unit +``` +Print a floating-point number, in decimal, on standard output. +The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. +``` +val print_endline : string -> unit +``` +Print a string, followed by a newline character, on standard output and flush standard output. +``` +val print_newline : unit -> unit +``` +Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. +### Output functions on standard error +``` +val prerr_char : char -> unit +``` +Print a character on standard error. +``` +val prerr_string : string -> unit +``` +Print a string on standard error. +``` +val prerr_bytes : bytes -> unit +``` +Print a byte sequence on standard error. +since 4.02 +``` +val prerr_int : int -> unit +``` +Print an integer, in decimal, on standard error. +``` +val prerr_float : float -> unit +``` +Print a floating-point number, in decimal, on standard error. +The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. +``` +val prerr_endline : string -> unit +``` +Print a string, followed by a newline character on standard error and flush standard error. +``` +val prerr_newline : unit -> unit +``` +Print a newline character on standard error, and flush standard error. +### Input functions on standard input +``` +val read_line : unit -> string +``` +Flush standard output, then read characters from standard input until a newline character is encountered. +Return the string of all characters read, without the newline character at the end. +raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. +``` +val read_int_opt : unit -> int option +``` +Flush standard output, then read one line from standard input and convert it to an integer. +Return `None` if the line read is not a valid representation of an integer. +since 4.05 +``` +val read_int : unit -> int +``` +Same as [`Stdlib.read_int_opt`](./#val-read_int_opt), but raise `Failure "int_of_string"` instead of returning `None`. +``` +val read_float_opt : unit -> float option +``` +Flush standard output, then read one line from standard input and convert it to a floating-point number. +Return `None` if the line read is not a valid representation of a floating-point number. +since 4.05 +``` +val read_float : unit -> float +``` +Same as [`Stdlib.read_float_opt`](./#val-read_float_opt), but raise `Failure "float_of_string"` instead of returning `None`. +### General output functions +``` +type open_flag = +``` +``` +| Open_rdonly +``` +open for reading. +``` +| Open_wronly +``` +open for writing. +``` +| Open_append +``` +open for appending: always write at end of file. +``` +| Open_creat +``` +create the file if it does not exist. +``` +| Open_trunc +``` +empty the file if it already exists. +``` +| Open_excl +``` +fail if Open\_creat and the file already exists. +``` +| Open_binary +``` +open in binary mode (no conversion). +``` +| Open_text +``` +open in text mode (may perform conversions). +``` +| Open_nonblock +``` +open in non-blocking mode. +``` + +``` +Opening modes for [`Stdlib.open_out_gen`](./#val-open_out_gen) and [`Stdlib.open_in_gen`](./#val-open_in_gen). +``` +val open_out : string -> out_channel +``` +Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. +``` +val open_out_bin : string -> out_channel +``` +Same as [`Stdlib.open_out`](./#val-open_out), but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_out`](./#val-open_out). +``` +val open_out_gen : open_flag list -> int -> string -> out_channel +``` +`open_out_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`Stdlib.open_out`](./#val-open_out) and [`Stdlib.open_out_bin`](./#val-open_out_bin) are special cases of this function. +``` +val flush : out_channel -> unit +``` +Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. +``` +val flush_all : unit -> unit +``` +Flush all open output channels; ignore errors. +``` +val output_char : out_channel -> char -> unit +``` +Write the character on the given output channel. +``` +val output_string : out_channel -> string -> unit +``` +Write the string on the given output channel. +``` +val output_bytes : out_channel -> bytes -> unit +``` +Write the byte sequence on the given output channel. +since 4.02 +``` +val output : out_channel -> bytes -> int -> int -> unit +``` +`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. +raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val output_substring : out_channel -> string -> int -> int -> unit +``` +Same as `output` but take a string as argument instead of a byte sequence. +since 4.02 +``` +val output_byte : out_channel -> int -> unit +``` +Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. +``` +val output_binary_int : out_channel -> int -> unit +``` +Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the [`Stdlib.input_binary_int`](./#val-input_binary_int) function. The format is compatible across all machines for a given version of OCaml. +``` +val output_value : out_channel -> 'a -> unit +``` +Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function [`Stdlib.input_value`](./#val-input_value). See the description of module [`Marshal`](./Stdlib-Marshal.md) for more information. [`Stdlib.output_value`](./#val-output_value) is equivalent to [`Marshal.to_channel`](./Stdlib-Marshal.md#val-to_channel) with an empty list of flags. +``` +val seek_out : out_channel -> int -> unit +``` +`seek_out chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. +``` +val pos_out : out_channel -> int +``` +Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_out`, then going back to this position using `seek_out` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. +``` +val out_channel_length : out_channel -> int +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. +``` +val close_out : out_channel -> unit +``` +Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except `close_out` and `flush`, which do nothing when applied to an already closed channel. Note that `close_out` may raise `Sys_error` if the operating system signals an error when flushing or closing. +``` +val close_out_noerr : out_channel -> unit +``` +Same as `close_out`, but ignore all errors. +``` +val set_binary_mode_out : out_channel -> bool -> unit +``` +`set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. `set_binary_mode_out oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. +### General input functions +``` +val open_in : string -> in_channel +``` +Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. +``` +val open_in_bin : string -> in_channel +``` +Same as [`Stdlib.open_in`](./#val-open_in), but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_in`](./#val-open_in). +``` +val open_in_gen : open_flag list -> int -> string -> in_channel +``` +`open_in_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`Stdlib.open_in`](./#val-open_in) and [`Stdlib.open_in_bin`](./#val-open_in_bin) are special cases of this function. +``` +val input_char : in_channel -> char +``` +Read one character from the given input channel. +raises [`End_of_file`](./#exception-End_of_file) if there are no more characters to read. +``` +val input_line : in_channel -> string +``` +Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. +raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. +``` +val input : in_channel -> bytes -> int -> int -> int +``` +`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and `len` exclusive means that not all requested `len` characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; `input` must be called again to read the remaining characters, if desired. (See also [`Stdlib.really_input`](./#val-really_input) for reading exactly `len` characters.) Exception `Invalid_argument "input"` is raised if `pos` and `len` do not designate a valid range of `buf`. +``` +val really_input : in_channel -> bytes -> int -> int -> unit +``` +`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. +raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. +raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val really_input_string : in_channel -> int -> string +``` +`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. +raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. +since 4.02 +``` +val input_byte : in_channel -> int +``` +Same as [`Stdlib.input_char`](./#val-input_char), but return the 8-bit integer representing the character. +raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached. +``` +val input_binary_int : in_channel -> int +``` +Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See [`Stdlib.output_binary_int`](./#val-output_binary_int). +raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached while reading the integer. +``` +val input_value : in_channel -> 'a +``` +Read the representation of a structured value, as produced by [`Stdlib.output_value`](./#val-output_value), and return the corresponding value. This function is identical to [`Marshal.from_channel`](./Stdlib-Marshal.md#val-from_channel); see the description of module [`Marshal`](./Stdlib-Marshal.md) for more information, in particular concerning the lack of type safety. +``` +val seek_in : in_channel -> int -> unit +``` +`seek_in chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. +``` +val pos_in : in_channel -> int +``` +Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_in`, then going back to this position using `seek_in` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. +``` +val in_channel_length : in_channel -> int +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. +``` +val close_in : in_channel -> unit +``` +Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except `close_in`, which does nothing when applied to an already closed channel. +``` +val close_in_noerr : in_channel -> unit +``` +Same as `close_in`, but ignore all errors. +``` +val set_binary_mode_in : in_channel -> bool -> unit +``` +`set_binary_mode_in ic true` sets the channel `ic` to binary mode: no translations take place during input. `set_binary_mode_out ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. +### Operations on large files +``` +module LargeFile : sig ... end +``` +Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. +## References +``` +type 'a ref = { +``` +`mutable contents : 'a;` +``` +} +``` +The type of references (mutable indirection cells) containing a value of type `'a`. +``` +val ref : 'a -> 'a ref +``` +Return a fresh reference containing the given value. +``` +val (!) : 'a ref -> 'a +``` +`!r` returns the current contents of reference `r`. Equivalent to `fun r -> r.contents`. Unary operator, see `Ocaml_operators` for more information. +``` +val (:=) : 'a ref -> 'a -> unit +``` +`r := a` stores the value of `a` in reference `r`. Equivalent to `fun r v -> r.contents <- v`. Right-associative operator, see `Ocaml_operators` for more information. +``` +val incr : int ref -> unit +``` +Increment the integer contained in the given reference. Equivalent to `fun r -> r := succ !r`. +``` +val decr : int ref -> unit +``` +Decrement the integer contained in the given reference. Equivalent to `fun r -> r := pred !r`. +## Result type +``` +type ('a, 'b) result = +``` +``` +| Ok of 'a +``` +``` +| Error of 'b +``` +``` + +``` +since 4.03 +## Operations on format strings +Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module [`Scanf`](./Stdlib-Scanf.md) and to print data with formatted output functions from modules [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). +Format strings are made of three kinds of entities: +- *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print, +- *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument, +- *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output. +There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`. +For more information about conversion specifications and formatting indications available, read the documentation of modules [`Scanf`](./Stdlib-Scanf.md), [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). +Format strings have a general and highly polymorphic type `('a, 'b, 'c, 'd, 'e, 'f) format6`. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml. +The meaning of format string type parameters is as follows: +- `'a` is the type of the parameters of the format for formatted output functions (`printf`\-style functions); `'a` is the type of the values read by the format for formatted input functions (`scanf`\-style functions). +- `'b` is the type of input source for formatted input functions and the type of output target for formatted output functions. For `printf`\-style functions from module [`Printf`](./Stdlib-Printf.md), `'b` is typically `out_channel`; for `printf`\-style functions from module [`Format`](./Stdlib-Format.md), `'b` is typically [`Format.formatter`](./Stdlib-Format.md#type-formatter); for `scanf`\-style functions from module [`Scanf`](./Stdlib-Scanf.md), `'b` is typically [`Scanf.Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). +Type argument `'b` is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion. +- `'c` is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf`\-style functions or to the `kscanf`\-style functions. +- `'d` is the type of parameters for the `scanf`\-style functions. +- `'e` is the type of the receiver function for the `scanf`\-style functions. +- `'f` is the final result type of a formatted input/output function invocation: for the `printf`\-style functions, it is typically `unit`; for the `scanf`\-style functions, it is typically the result type of the receiver function. +``` +type ('a, 'b, 'c, 'd, 'e, 'f) format6 = + ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 +``` +``` +type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 +``` +``` +type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 +``` +``` +val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string +``` +Converts a format string into a string. +``` +val format_of_string : + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 +``` +`format_of_string s` returns a format string read from the string literal `s`. Note: `format_of_string` can not convert a string argument that is not a literal. If you need this functionality, use the more general [`Scanf.format_from_string`](./Stdlib-Scanf.md#val-format_from_string) function. +``` +val (^^) : + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + ('f, 'b, 'c, 'e, 'g, 'h) format6 -> + ('a, 'b, 'c, 'd, 'g, 'h) format6 +``` +`f1 ^^ f2` catenates format strings `f1` and `f2`. The result is a format string that behaves as the concatenation of format strings `f1` and `f2`: in case of formatted output, it accepts arguments from `f1`, then arguments from `f2`; in case of formatted input, it returns results from `f1`, then results from `f2`. Right-associative operator, see `Ocaml_operators` for more information. +## Program termination +``` +val exit : int -> 'a +``` +Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with [`Domain.at_exit`](./Stdlib-Domain.md#val-at_exit) are called followed by those registered with [`Stdlib.at_exit`](./#val-at_exit). +An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception. +``` +val at_exit : (unit -> unit) -> unit +``` +Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following: +- executes [`Stdlib.exit`](./#val-exit) +- terminates, either normally or because of an uncaught exception +- executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. +## Standard library modules +``` +module Arg : sig ... end +``` +Parsing of command line arguments. +``` +module Array : sig ... end +``` +Array operations. +``` +module ArrayLabels : sig ... end +``` +Array operations. +``` +module Atomic : sig ... end +``` +Atomic references. +``` +module Bool : sig ... end +``` +Boolean values. +``` +module Buffer : sig ... end +``` +Extensible buffers. +``` +module Bytes : sig ... end +``` +Byte sequence operations. +``` +module BytesLabels : sig ... end +``` +Byte sequence operations. +``` +module Char : sig ... end +``` +Character operations. +``` +module Complex : sig ... end +``` +Complex numbers. +``` +module Digest : sig ... end +``` +Message digest. +``` +module Domain : sig ... end +``` +``` +module Dynarray : sig ... end +``` +Dynamic arrays. +``` +module Effect : sig ... end +``` +``` +module Either : sig ... end +``` +Either type. +``` +module Filename : sig ... end +``` +Operations on file names. +``` +module Float : sig ... end +``` +Floating-point arithmetic. +``` +module Format : sig ... end +``` +Pretty-printing. +``` +module Fun : sig ... end +``` +Function manipulation. +``` +module Gc : sig ... end +``` +Memory management control and statistics; finalised values. +``` +module Hashtbl : sig ... end +``` +Hash tables and hash functions. +``` +module In_channel : sig ... end +``` +Input channels. +``` +module Int : sig ... end +``` +Integer values. +``` +module Int32 : sig ... end +``` +32-bit integers. +``` +module Int64 : sig ... end +``` +64-bit integers. +``` +module Lazy : sig ... end +``` +Deferred computations. +``` +module Lexing : sig ... end +``` +The run-time library for lexers generated by `ocamllex`. +``` +module List : sig ... end +``` +List operations. +``` +module ListLabels : sig ... end +``` +List operations. +``` +module Map : sig ... end +``` +Association tables over ordered types. +``` +module Marshal : sig ... end +``` +Marshaling of data structures. +``` +module MoreLabels : sig ... end +``` +Extra labeled libraries. +``` +module Mutex : sig ... end +``` +Locks for mutual exclusion. +``` +module Obj : sig ... end +``` +Operations on internal representations of values. +``` +module Oo : sig ... end +``` +Operations on objects +``` +module Option : sig ... end +``` +Option values. +``` +module Out_channel : sig ... end +``` +Output channels. +``` +module Parsing : sig ... end +``` +The run-time library for parsers generated by `ocamlyacc`. +``` +module Printexc : sig ... end +``` +Facilities for printing exceptions and inspecting current call stack. +``` +module Printf : sig ... end +``` +Formatted output functions. +``` +module Queue : sig ... end +``` +First-in first-out queues. +``` +module Random : sig ... end +``` +Pseudo-random number generators (PRNG). +``` +module Result : sig ... end +``` +Result values. +``` +module Scanf : sig ... end +``` +Formatted input functions. +``` +module Seq : sig ... end +``` +Sequences. +``` +module Set : sig ... end +``` +Sets over ordered types. +``` +module Stack : sig ... end +``` +Last-in first-out stacks. +``` +module StdLabels : sig ... end +``` +Standard labeled libraries. +``` +module String : sig ... end +``` +Strings. +``` +module StringLabels : sig ... end +``` +Strings. +``` +module Sys : sig ... end +``` +System interface. +``` +module Type : sig ... end +``` +Type introspection. +``` +module Uchar : sig ... end +``` +Unicode characters. +``` +module Unit : sig ... end +``` +Unit values. +``` +module Weak : sig ... end +``` +Arrays of weak pointers and hash sets of weak pointers. \ No newline at end of file From be162bfb6fb0e38413e5400156dd00c378bfcf48 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 1 May 2025 16:20:34 +0100 Subject: [PATCH 04/19] Generate opam files from dune-project --- documentation-site.opam | 26 ++++++++++++++++---------- documentation-site.opam.template | 7 +++++++ dune-project | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 10 deletions(-) create mode 100644 documentation-site.opam.template diff --git a/documentation-site.opam b/documentation-site.opam index ecbede1e0..6d19366b1 100644 --- a/documentation-site.opam +++ b/documentation-site.opam @@ -1,3 +1,4 @@ +# This file is generated by dune, edit dune-project instead opam-version: "2.0" synopsis: "Melange documentation site" description: "Content for the Melange documentation site" @@ -11,25 +12,22 @@ authors: [ ] license: "MIT" homepage: "https://github.com/melange-re/melange-re.github.io" -bug-reports: "https://github.com/melange-re/melange-re.github.io" +bug-reports: "https://github.com/melange-re/melange-re.github.io/issues" depends: [ "ocaml" - "dune" {>= "3.8.0"} - "reason" {>= "3.13.0"} + "dune" {>= "3.8"} + "reason" "reason-react" "reason-react-ppx" "ocamlformat" "js_of_ocaml" "cmarkit" {dev} - "melange" {dev} # needs to pin it to get the docs in a stable path + "melange" {dev} + "odoc" {dev} + "odoc-parser" {dev} "melange-playground" {dev} "ocaml-lsp-server" {dev} -] -dev-repo: "git+https://github.com/melange-re/melange-re.github.io.git" -pin-depends: [ - [ "melange.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6" ] - [ "melange-playground.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6" ] - [ "cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91" ] + "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} @@ -45,3 +43,11 @@ build: [ "@doc" {with-doc} ] ] +dev-repo: "git+https://github.com/melange-re/melange-re.github.io.git" +pin-depends: [ + ["melange.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] + ["melange-playground.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] + ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] + ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] + ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] +] diff --git a/documentation-site.opam.template b/documentation-site.opam.template new file mode 100644 index 000000000..838339cd8 --- /dev/null +++ b/documentation-site.opam.template @@ -0,0 +1,7 @@ +pin-depends: [ + ["melange.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] + ["melange-playground.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] + ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] + ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] + ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] +] diff --git a/dune-project b/dune-project index 69c2d1b9c..3f510fe8d 100644 --- a/dune-project +++ b/dune-project @@ -2,4 +2,36 @@ (using melange 0.1) +(generate_opam_files true) + (name documentation-site) + +(license MIT) +(maintainers + "Antonio Nuno Monteiro " + "Javier Chávarri ") +(authors + "Antonio Nuno Monteiro " + "Javier Chávarri ") + +(source + (github melange-re/melange-re.github.io)) + +(package + (name documentation-site) + (synopsis "Melange documentation site") + (description "Content for the Melange documentation site") + (depends + ocaml + dune + reason + reason-react + reason-react-ppx + ocamlformat + js_of_ocaml + (cmarkit :dev) + (melange :dev) + (odoc :dev) + (odoc-parser :dev) + (melange-playground :dev) + (ocaml-lsp-server :dev))) From 834058cd61f0e844c18e4adc464a3fce027095f8 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 1 May 2025 16:21:19 +0100 Subject: [PATCH 05/19] Fix gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 513eac863..e5108f192 100644 --- a/.gitignore +++ b/.gitignore @@ -12,4 +12,4 @@ docs/public/api/re docs/api/ml docs/api/re -melange.dev/* +melange.dev From 03b815b57af987a6524af0f1fecf90e1b89cbb21 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Sat, 3 May 2025 15:23:46 +0100 Subject: [PATCH 06/19] Update with latest odoc --- docs/api/melange/Belt-Array.md | 92 ++++- docs/api/melange/Belt-Float.md | 3 + docs/api/melange/Belt-HashMap-Int.md | 4 + docs/api/melange/Belt-HashMap-String.md | 4 + docs/api/melange/Belt-HashMap.md | 22 ++ docs/api/melange/Belt-HashSet-Int.md | 6 + docs/api/melange/Belt-HashSet-String.md | 6 + docs/api/melange/Belt-HashSet.md | 17 + .../Belt-Id-MakeComparable-argument-1-M.md | 2 + docs/api/melange/Belt-Id-MakeComparable.md | 6 + .../Belt-Id-MakeComparableU-argument-1-M.md | 2 + docs/api/melange/Belt-Id-MakeComparableU.md | 6 + .../Belt-Id-MakeHashable-argument-1-M.md | 2 + docs/api/melange/Belt-Id-MakeHashable.md | 6 + .../Belt-Id-MakeHashableU-argument-1-M.md | 2 + docs/api/melange/Belt-Id-MakeHashableU.md | 6 + .../melange/Belt-Id-module-type-Comparable.md | 2 + .../melange/Belt-Id-module-type-Hashable.md | 2 + docs/api/melange/Belt-Id.md | 23 ++ docs/api/melange/Belt-Int.md | 3 + docs/api/melange/Belt-List.md | 86 +++++ docs/api/melange/Belt-Map-Dict.md | 19 + docs/api/melange/Belt-Map-Int.md | 19 + docs/api/melange/Belt-Map-String.md | 19 + docs/api/melange/Belt-Map.md | 73 ++++ docs/api/melange/Belt-MutableMap-Int.md | 14 + docs/api/melange/Belt-MutableMap-String.md | 14 + docs/api/melange/Belt-MutableMap.md | 19 + docs/api/melange/Belt-MutableQueue.md | 24 +- docs/api/melange/Belt-MutableSet-Int.md | 19 +- docs/api/melange/Belt-MutableSet-String.md | 19 +- docs/api/melange/Belt-MutableSet.md | 20 +- docs/api/melange/Belt-MutableStack.md | 10 +- docs/api/melange/Belt-Option.md | 42 +++ docs/api/melange/Belt-Range.md | 18 +- docs/api/melange/Belt-Result.md | 25 ++ docs/api/melange/Belt-Set-Dict.md | 18 +- docs/api/melange/Belt-Set-Int.md | 22 +- docs/api/melange/Belt-Set-String.md | 22 +- docs/api/melange/Belt-Set.md | 61 +++ docs/api/melange/Belt-SortArray-Int.md | 12 +- docs/api/melange/Belt-SortArray-String.md | 12 +- docs/api/melange/Belt-SortArray.md | 17 + docs/api/melange/Belt.md | 48 ++- docs/api/melange/Dom-Storage.md | 2 + docs/api/melange/Dom.md | 2 + docs/api/melange/Js-Array.md | 9 + docs/api/melange/Js-Bigint.md | 12 + docs/api/melange/Js-Blob.md | 13 +- docs/api/melange/Js-Console.md | 2 + docs/api/melange/Js-Date.md | 15 + docs/api/melange/Js-Dict.md | 18 +- docs/api/melange/Js-Exn.md | 8 + docs/api/melange/Js-File.md | 16 +- docs/api/melange/Js-Float.md | 28 ++ docs/api/melange/Js-FormData.md | 17 +- docs/api/melange/Js-Global.md | 20 + docs/api/melange/Js-Int.md | 17 + docs/api/melange/Js-Iterator.md | 3 + docs/api/melange/Js-Json.md | 43 +++ docs/api/melange/Js-Map.md | 4 + docs/api/melange/Js-Math.md | 63 +++- docs/api/melange/Js-Null.md | 13 + docs/api/melange/Js-Nullable.md | 15 + docs/api/melange/Js-Obj.md | 4 + docs/api/melange/Js-Promise.md | 4 + docs/api/melange/Js-Re.md | 32 ++ docs/api/melange/Js-Set.md | 4 + docs/api/melange/Js-String.md | 61 +++ .../api/melange/Js-Typed_array-ArrayBuffer.md | 4 + docs/api/melange/Js-Typed_array-DataView.md | 3 + .../melange/Js-Typed_array-Float32Array.md | 4 + .../melange/Js-Typed_array-Float64Array.md | 4 + docs/api/melange/Js-Typed_array-Int16Array.md | 4 + docs/api/melange/Js-Typed_array-Int32Array.md | 4 + docs/api/melange/Js-Typed_array-Int8Array.md | 4 + .../api/melange/Js-Typed_array-Uint16Array.md | 4 + .../api/melange/Js-Typed_array-Uint32Array.md | 4 + docs/api/melange/Js-Typed_array-Uint8Array.md | 4 + .../Js-Typed_array-Uint8ClampedArray.md | 4 + docs/api/melange/Js-Typed_array.md | 7 +- docs/api/melange/Js-Types.md | 7 + docs/api/melange/Js-Undefined.md | 14 + docs/api/melange/Js-WeakMap.md | 4 + docs/api/melange/Js-WeakSet.md | 4 + docs/api/melange/Js.md | 56 ++- docs/api/melange/Node-Buffer.md | 3 + docs/api/melange/Node-Child_process.md | 3 + docs/api/melange/Node-Fs-Watch.md | 3 + docs/api/melange/Node-Fs.md | 5 + docs/api/melange/Node-Module.md | 3 + docs/api/melange/Node-Path.md | 3 + docs/api/melange/Node-Process.md | 3 + docs/api/melange/Node.md | 9 +- docs/api/melange/Stdlib-Arg.md | 46 +++ docs/api/melange/Stdlib-Array.md | 91 ++++- docs/api/melange/Stdlib-ArrayLabels.md | 91 ++++- docs/api/melange/Stdlib-Atomic.md | 26 ++ docs/api/melange/Stdlib-Bool.md | 21 ++ docs/api/melange/Stdlib-Buffer.md | 60 +++ docs/api/melange/Stdlib-Bytes.md | 158 +++++++- docs/api/melange/Stdlib-BytesLabels.md | 158 +++++++- docs/api/melange/Stdlib-Char.md | 13 + docs/api/melange/Stdlib-Complex.md | 24 +- docs/api/melange/Stdlib-Digest-BLAKE128.md | 17 + docs/api/melange/Stdlib-Digest-BLAKE256.md | 17 + docs/api/melange/Stdlib-Digest-BLAKE512.md | 17 + docs/api/melange/Stdlib-Digest-MD5.md | 17 + .../melange/Stdlib-Digest-module-type-S.md | 17 + docs/api/melange/Stdlib-Digest.md | 31 +- docs/api/melange/Stdlib-Domain-DLS.md | 12 +- docs/api/melange/Stdlib-Domain.md | 21 +- docs/api/melange/Stdlib-Dynarray.md | 135 +++++++ docs/api/melange/Stdlib-Either.md | 23 +- docs/api/melange/Stdlib-Filename.md | 35 ++ docs/api/melange/Stdlib-Float-Array.md | 85 ++++- docs/api/melange/Stdlib-Float.md | 96 ++++- docs/api/melange/Stdlib-Format.md | 303 ++++++++++++++- docs/api/melange/Stdlib-Fun.md | 17 +- docs/api/melange/Stdlib-Gc-Memprof.md | 31 +- docs/api/melange/Stdlib-Gc.md | 75 +++- .../Stdlib-Hashtbl-Make-argument-1-H.md | 5 + docs/api/melange/Stdlib-Hashtbl-Make.md | 7 + .../Stdlib-Hashtbl-MakeSeeded-argument-1-H.md | 6 +- docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md | 7 + .../Stdlib-Hashtbl-module-type-HashedType.md | 6 + .../melange/Stdlib-Hashtbl-module-type-S.md | 3 + ...ib-Hashtbl-module-type-SeededHashedType.md | 7 +- .../Stdlib-Hashtbl-module-type-SeededS.md | 3 + docs/api/melange/Stdlib-Hashtbl.md | 87 +++++ docs/api/melange/Stdlib-In_channel.md | 62 ++++ docs/api/melange/Stdlib-Int.md | 41 ++ docs/api/melange/Stdlib-Int32.md | 49 +++ docs/api/melange/Stdlib-Int64.md | 53 +++ docs/api/melange/Stdlib-LargeFile.md | 3 + docs/api/melange/Stdlib-Lazy.md | 29 ++ docs/api/melange/Stdlib-Lexing.md | 34 +- docs/api/melange/Stdlib-List.md | 105 ++++++ docs/api/melange/Stdlib-ListLabels.md | 105 ++++++ .../melange/Stdlib-Map-Make-argument-1-Ord.md | 5 +- docs/api/melange/Stdlib-Map-Make.md | 69 ++++ .../Stdlib-Map-module-type-OrderedType.md | 6 +- docs/api/melange/Stdlib-Map-module-type-S.md | 65 ++++ docs/api/melange/Stdlib-Map.md | 10 +- docs/api/melange/Stdlib-Marshal.md | 30 +- ...ib-MoreLabels-Hashtbl-Make-argument-1-H.md | 5 + .../melange/Stdlib-MoreLabels-Hashtbl-Make.md | 7 + ...eLabels-Hashtbl-MakeSeeded-argument-1-H.md | 6 +- .../Stdlib-MoreLabels-Hashtbl-MakeSeeded.md | 7 + ...reLabels-Hashtbl-module-type-HashedType.md | 6 + ...Stdlib-MoreLabels-Hashtbl-module-type-S.md | 3 + ...ls-Hashtbl-module-type-SeededHashedType.md | 7 +- ...-MoreLabels-Hashtbl-module-type-SeededS.md | 3 + docs/api/melange/Stdlib-MoreLabels-Hashtbl.md | 87 +++++ ...dlib-MoreLabels-Map-Make-argument-1-Ord.md | 5 +- .../api/melange/Stdlib-MoreLabels-Map-Make.md | 69 ++++ ...-MoreLabels-Map-module-type-OrderedType.md | 6 +- .../Stdlib-MoreLabels-Map-module-type-S.md | 65 ++++ docs/api/melange/Stdlib-MoreLabels-Map.md | 10 +- ...dlib-MoreLabels-Set-Make-argument-1-Ord.md | 5 +- .../api/melange/Stdlib-MoreLabels-Set-Make.md | 72 ++++ ...-MoreLabels-Set-module-type-OrderedType.md | 6 +- .../Stdlib-MoreLabels-Set-module-type-S.md | 68 ++++ docs/api/melange/Stdlib-MoreLabels-Set.md | 10 +- docs/api/melange/Stdlib-MoreLabels.md | 10 +- docs/api/melange/Stdlib-Mutex.md | 11 + docs/api/melange/Stdlib-Obj-Ephemeron.md | 9 +- .../Stdlib-Obj-Extension_constructor.md | 2 + docs/api/melange/Stdlib-Obj.md | 11 +- docs/api/melange/Stdlib-Oo.md | 6 +- docs/api/melange/Stdlib-Option.md | 28 +- docs/api/melange/Stdlib-Out_channel.md | 62 ++++ docs/api/melange/Stdlib-Parsing.md | 14 + docs/api/melange/Stdlib-Printexc-Slot.md | 10 + docs/api/melange/Stdlib-Printexc.md | 64 ++++ docs/api/melange/Stdlib-Printf.md | 27 ++ docs/api/melange/Stdlib-Queue.md | 38 ++ docs/api/melange/Stdlib-Random-State.md | 6 + docs/api/melange/Stdlib-Random.md | 28 +- docs/api/melange/Stdlib-Result.md | 31 +- docs/api/melange/Stdlib-Scanf-Scanning.md | 22 ++ docs/api/melange/Stdlib-Scanf.md | 74 ++++ docs/api/melange/Stdlib-Seq.md | 186 ++++++++++ .../melange/Stdlib-Set-Make-argument-1-Ord.md | 5 +- docs/api/melange/Stdlib-Set-Make.md | 72 ++++ .../Stdlib-Set-module-type-OrderedType.md | 6 +- docs/api/melange/Stdlib-Set-module-type-S.md | 68 ++++ docs/api/melange/Stdlib-Set.md | 10 +- docs/api/melange/Stdlib-Stack.md | 26 ++ docs/api/melange/Stdlib-StdLabels.md | 4 + docs/api/melange/Stdlib-String.md | 111 ++++++ docs/api/melange/Stdlib-StringLabels.md | 111 ++++++ ...s-Immediate64-Make-argument-1-Immediate.md | 2 + ...mediate64-Make-argument-2-Non_immediate.md | 2 + .../melange/Stdlib-Sys-Immediate64-Make.md | 6 + ...b-Sys-Immediate64-module-type-Immediate.md | 2 + ...s-Immediate64-module-type-Non_immediate.md | 2 + docs/api/melange/Stdlib-Sys-Immediate64.md | 3 + docs/api/melange/Stdlib-Sys.md | 87 ++++- docs/api/melange/Stdlib-Type-Id.md | 14 + docs/api/melange/Stdlib-Type.md | 13 +- docs/api/melange/Stdlib-Uchar.md | 32 +- docs/api/melange/Stdlib-Unit.md | 11 +- .../melange/Stdlib-Weak-Make-argument-1-H.md | 5 + docs/api/melange/Stdlib-Weak-Make.md | 23 +- docs/api/melange/Stdlib-Weak-module-type-S.md | 19 +- docs/api/melange/Stdlib-Weak.md | 26 +- docs/api/melange/Stdlib.md | 351 +++++++++++++++++- 208 files changed, 5919 insertions(+), 72 deletions(-) diff --git a/docs/api/melange/Belt-Array.md b/docs/api/melange/Belt-Array.md index dc66f4fd3..31970e565 100644 --- a/docs/api/melange/Belt-Array.md +++ b/docs/api/melange/Belt-Array.md @@ -1,7 +1,12 @@ + # Module `Belt.Array` + [`Belt.Array`](#) + **mutable array**: Utilities functions + [`Belt.Array`](#) Utililites for Array functions + ``` type 'a t = 'a array ``` @@ -9,15 +14,19 @@ type 'a t = 'a array val length : 'a t -> int ``` `length xs` return the size of the array + ``` val size : 'a t -> int ``` **See** [`length`](./#val-length) + ``` val get : 'a t -> int -> 'a option ``` `get arr i` + If `i <= 0 <= length arr`;returns `Some value` where `value` is the item at index `i` If `i` is out of range;returns `None` + ```ocaml Belt.Array.get [|"a";"b";"c"|] 0 = Some "a";; Belt.Array.get [|"a";"b";"c"|] 3 = None;; @@ -27,27 +36,36 @@ If `i <= 0 <= length arr`;returns `Some value` where `value` is the item at inde val getExn : 'a t -> int -> 'a ``` `getExn arr i` + **raise** an exception if `i` is out of range;otherwise return the value at index `i` in `arr` + ``` val getUnsafe : 'a t -> int -> 'a ``` `getUnsafe arr i` + **Unsafe** + no bounds checking;this would cause type error if `i` does not stay within range + ``` val getUndefined : 'a t -> int -> 'a Js.undefined ``` `getUndefined arr i` + It does the samething in the runtime as [`getUnsafe`](./#val-getUnsafe); it is *type safe* since the return type still track whether it is in range or not + ``` val set : 'a t -> int -> 'a -> bool ``` `set arr n x` modifies `arr` in place; it replaces the nth element of `arr` with `x` + returns false means not updated due to out of range ``` val setExn : 'a t -> int -> 'a -> unit ``` `setExn arr i x` **raise** an exception if `i` is out of range + ``` val setUnsafe : 'a t -> int -> 'a -> unit ``` @@ -55,15 +73,18 @@ val setUnsafe : 'a t -> int -> 'a -> unit val shuffleInPlace : 'a t -> unit ``` `shuffleInPlace arr` randomly re-orders the items in `arr` + ``` val shuffle : 'a t -> 'a t ``` `shuffle xs` + returns a fresh array with items in original array randomly shuffled ``` val reverseInPlace : 'a t -> unit ``` `reverseInPlace arr` reverses items in `arr` in place + ```ocaml let arr = [|10;11;12;13;14|];; let () = reverseInPlace arr;; @@ -73,6 +94,7 @@ val reverseInPlace : 'a t -> unit val reverse : 'a t -> 'a t ``` `reverse arr` + returns a fresh array with items in arr in reverse order ```ocaml reverse [|10;11;12;13;14|] = [|14;13;12;11;10|];; @@ -81,6 +103,7 @@ returns a fresh array with items in arr in reverse order val makeUninitialized : int -> 'a Js.undefined array ``` `makeUninitialized n` creates an array of length `n` filled with the undefined value. You must specify the type of data that will eventually fill the array. + ```ocaml let arr: string Js.undefined array = makeUninitialized 5;; getExn arr 0 = Js.undefined;; @@ -89,7 +112,9 @@ val makeUninitialized : int -> 'a Js.undefined array val makeUninitializedUnsafe : int -> 'a t ``` \`makeUninitializedUnsafe n\` + **Unsafe** + ```ocaml let arr = Belt.Array.makeUninitializedUnsafe 5;; let () = Js.log(Belt.Array.getExn arr 0);; (* undefined *) @@ -100,11 +125,13 @@ let () = Js.log(Belt.Array.getExn arr 0 = "example");; val make : int -> 'a -> 'a t ``` `make n e` return an array of size `n` filled with value `e` + returns an empty array when n is negative. ``` val range : int -> int -> int t ``` `range start finish` create an inclusive array + ```ocaml range 0 3 = [|0;1;2;3|];; range 3 0 = [||] ;; @@ -114,6 +141,7 @@ val range : int -> int -> int t val rangeBy : int -> int -> step:int -> int t ``` `rangeBy start finish ~step` + returns empty array when step is 0 or negative it also return empty array when start \> finish ```ocaml rangeBy 0 10 ~step:3 = [|0;3;6;9|];; @@ -131,7 +159,9 @@ val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t val makeBy : int -> (int -> 'a) -> 'a t ``` `makeBy n f` + return an empty array when `n` is negative return an array of size `n` populated by `f i` start from `0` to `n - 1` + ```ocaml makeBy 5 (fun i -> i) = [|0;1;2;3;4|];; makeBy 5 (fun i -> i * i) = [|0;1;4;9;16|] @@ -143,12 +173,16 @@ val makeByAndShuffleU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t val makeByAndShuffle : int -> (int -> 'a) -> 'a t ``` `makeByAndShuffle n f` + Equivalent to `shuffle (makeBy n f)` + ``` val zip : 'a t -> 'b array -> ('a * 'b) array ``` `zip a b` + Create an array of pairs from corresponding elements of `a` and `b`. Stop with the shorter array + ```ocaml zip [|1;2|] [|3;4;5|] = [|(1, 3);(2, 4)|] ``` @@ -159,8 +193,11 @@ val zipByU : 'a t -> 'b array -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c array val zipBy : 'a t -> 'b array -> ('a -> 'b -> 'c) -> 'c array ``` `zipBy xs ys f` + Create an array by applying `f` to corresponding elements of `xs` and `ys` Stops with shorter array + Equivalent to `map (zip xs ys) (fun (a,b) -> f a b) ` + ```ocaml zipBy [|1;2;3|] [|4;5|] (fun a b -> 2 * a + b) = [|6;9|];; ``` @@ -168,6 +205,7 @@ Equivalent to `map (zip xs ys) (fun (a,b) -> f a b) ` val unzip : ('a * 'b) array -> 'a t * 'b array ``` `unzip a` takes an array of pairs and creates a pair of arrays. The first array contains all the first items of the pairs; the second array contains all the second items. + ```ocaml unzip [|(1,2) ; (3,4)|] = ([|1;3|], [|2;4|]);; unzip [|(1,2) ; (3,4) ; (5,6) ; (7,8)|] = ([|1;3;5;7|], [|2;4;6;8|]);; @@ -176,6 +214,7 @@ val unzip : ('a * 'b) array -> 'a t * 'b array val concat : 'a t -> 'a t -> 'a t ``` `concat xs ys` + returns a fresh array containing the concatenation of the arrays v1 and v2;so even if v1 or v2 is empty;it can not be shared ```ocaml concat [|1;2;3|] [|4;5|] = [|1;2;3;4;5|];; @@ -185,6 +224,7 @@ returns a fresh array containing the concatenation of the arrays v1 and v2;so ev val concatMany : 'a t t -> 'a t ``` `concatMany xss` + returns a fresh array as the concatenation of xss (an array of arrays) ```ocaml concatMany [| [|1;2;3|]; [|4;5;6|]; [|7;8|] |] = [|1;2;3;4;5;6;7;8|];; @@ -193,10 +233,15 @@ returns a fresh array as the concatenation of xss (an array of arrays) val slice : 'a t -> offset:int -> len:int -> 'a t ``` `slice xs offset len` creates a new array with the `len` elements of `xs` starting at `offset` for + `offset` can be negative;and is evaluated as `length xs - offset` `slice xs -1 1` means get the last element as a singleton array + `slice xs (-len) len` will return a copy of the array + if the array does not have enough data;`slice` extracts through the end of sequence. + if `len` is negative;returns the empty array. + ```ocaml slice [|10;11;12;13;14;15;16|] ~offset: 2 ~len: 3 = [|12;13;14|];; slice [|10;11;12;13;14;15;16|] ~offset: (-4) ~len: 3 = [|13;14;15|];; @@ -206,8 +251,11 @@ if `len` is negative;returns the empty array. val sliceToEnd : 'a t -> int -> 'a t ``` `sliceToEnd xs offset` creates a new array with the elements of `xs` starting at `offset` + `offset` can be negative;and is evaluated as `length xs - offset` `sliceToEnd xs -1` means get the last element as a singleton array + `sliceToEnd xs 0` will return a copy of the array + ```ocaml sliceToEnd [|10;11;12;13;14;15;16|] 2 = [|12;13;14;15;16|];; sliceToEnd [|10;11;12;13;14;15;16|] (-4) = [|13;14;15;16|];; @@ -216,14 +264,19 @@ val sliceToEnd : 'a t -> int -> 'a t val copy : 'a t -> 'a t ``` `copy a` + returns a copy of a;that is;a fresh array containing the same elements as a. ``` val fill : 'a t -> offset:int -> len:int -> 'a -> unit ``` `fill arr ~offset ~len x` + Modifies `arr` in place, storing `x` in elements number `offset` to `offset + len - 1`. + `offset` can be negative;and is evaluated as `length arr - offset` + `fill arr ~offset:(-1) ~len:1` means fill the last element, if the array does not have enough data;`fill` will ignore it + ```ocaml let arr = makeBy 5 (fun i -> i) ;; @@ -242,10 +295,15 @@ val blit : unit ``` `blit ~src:v1 ~srcOffset:o1 ~dst:v2 ~dstOffset:o2 ~len` + copies `len` elements from array `v1`;starting at element number `o1`;to array `v2`, starting at element number `o2`. + It works correctly even if `v1` and `v2` are the same array;and the source and destination chunks overlap. + `offset` can be negative;`-1` means `len - 1`;if `len + offset` is still negative;it will be set as 0 + For each of the examples;presume that `v1 = [|10;11;12;13;14;15;16;17|]` and `v2 = [|20;21;22;23;24;25;26;27|]`. The result shown is the content of the destination array. + ```ocaml Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v2 ~dstOffset: 2 ~len: 3 |. [|20;21;14;15;16;25;26;27|] @@ -262,6 +320,7 @@ val blitUnsafe : unit ``` **Unsafe** blit without bounds checking + ``` val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit ``` @@ -269,7 +328,9 @@ val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit val forEach : 'a t -> ('a -> unit) -> unit ``` `forEach xs f` + Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`;so no new array is created. Use `forEach` when you are primarily concerned with repetitively creating side effects. + ```ocaml forEach [|"a";"b";"c"|] (fun x -> Js.log("Item: " ^ x));; (* prints: @@ -290,6 +351,7 @@ val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b array val map : 'a t -> ('a -> 'b) -> 'b array ``` `map xs f ` + returns a new array by calling f for each element of xs from the beginning to end ```ocaml map [|1;2|] (fun x-> x + 10) = [|11;12|] @@ -301,6 +363,7 @@ val flatMapU : 'a t -> ('a -> 'b t) Js.Fn.arity1 -> 'b t val flatMap : 'a t -> ('a -> 'b t) -> 'b t ``` `flatMap xs f` \*\*return\*\* a new array by calling \`f\` for each element of \`xs\` from the beginning to end, and then concatenating the results \``` flatMap `|1;2|` (fun x-\> `|x + 10;x + 20|`) \= `|11;21;12;22|` \``` + ``` val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option ``` @@ -308,6 +371,7 @@ val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option val getBy : 'a t -> ('a -> bool) -> 'a option ``` `getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. + ```ocaml getBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 4 getBy [|15;13;11|] (fun x -> x mod 2 = 0) = None @@ -319,6 +383,7 @@ val getIndexByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> int option val getIndexBy : 'a t -> ('a -> bool) -> int option ``` `getIndexBy xs p` returns `Some index` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. + ```ocaml getIndexBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 1 getIndexBy [|15;13;11|] (fun x -> x mod 2 = 0) = None @@ -330,6 +395,7 @@ val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t val keep : 'a t -> ('a -> bool) -> 'a t ``` `keep xs p ` + returns a new array that keeps all elements satisfying p ```ocaml keep [|1;2;3|] (fun x -> x mod 2 = 0) = [|2|] @@ -341,6 +407,7 @@ val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t ``` `keepWithIndex xs p ` + returns a new array that keeps all elements satisfying p. The predicate p takes two arguments: the element from xs and the index starting from 0. ```ocaml keepWithIndex [|1;2;3|] (fun _x i -> i = 1) = [|2|] @@ -352,6 +419,7 @@ val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b array val keepMap : 'a t -> ('a -> 'b option) -> 'b array ``` `keepMap xs p` + returns a new array that keeps all elements that return a non-None when applied to p ```ocaml keepMap [|1;2;3|] (fun x -> if x mod 2 = 0 then Some x else None) @@ -364,7 +432,9 @@ val forEachWithIndexU : 'a t -> (int -> 'a -> unit) Js.Fn.arity2 -> unit val forEachWithIndex : 'a t -> (int -> 'a -> unit) -> unit ``` `forEachWithIndex xs f` + The same as [`forEach`](./#val-forEach); except that `f` is supplied with two arguments: the index starting from 0 and the element from `xs` + ```ocaml forEachWithIndex [|"a";"b";"c"|] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; @@ -385,6 +455,7 @@ val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t ``` `mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. + ```ocaml mapWithIndex [|1;2;3|] (fun i x -> i + x) = [|0 + 1; 1 + 2; 2 + 3|] @@ -396,6 +467,7 @@ val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t val partition : 'a t -> ('a -> bool) -> 'a t * 'a t ``` `partition f a` split array into tuple of two arrays based on predicate f; first of tuple where predicate cause true, second where predicate cause false + ```ocaml partition [|1;2;3;4;5|] (fun x -> x mod 2 = 0 ) = ([|2;4|], [|1;2;3|]);; partition [|1;2;3;4;5|] (fun x -> x mod 2 <> 0 ) = ([|1;2;3|], [|2;4|]);; @@ -407,7 +479,9 @@ val reduceU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a val reduce : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a ``` `reduce xs init f` + Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”;which starts with a value of `init`. `reduce` returns the final value of the accumulator. + ```ocaml reduce [|2;3;4|] 1 (+) = 10;; reduce [|"a";"b";"c";"d"|] "" (^) = "abcd";; @@ -419,7 +493,9 @@ val reduceReverseU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a val reduceReverse : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a ``` `reduceReverse xs init f` + Works like [`reduce`](./#val-reduce);except that function `f` is applied to each item of `xs` from the last back to the first. + ```ocaml reduceReverse [|"a";"b";"c";"d"|] "" (^) = "dcba";; ``` @@ -435,6 +511,7 @@ val reduceReverse2U : val reduceReverse2 : 'a t -> 'b array -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c ``` `reduceReverse2 xs ys init f` Reduces two arrays `xs` and `ys`;taking items starting at `min (length xs) (length ys)` down to and including zero. + ```ocaml reduceReverse2 [|1;2;3|] [|1;2|] 0 (fun acc x y -> acc + x + y) = 6 ``` @@ -445,7 +522,9 @@ val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b ``` `reduceWithIndex xs f` + Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the array and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. + ```ocaml reduceWithIndex [|1;2;3;4|] 0 (fun acc x i -> acc + x + i) = 16; ``` @@ -456,7 +535,9 @@ val joinWithU : 'a t -> string -> ('a -> string) Js.Fn.arity1 -> string val joinWith : 'a t -> string -> ('a -> string) -> string ``` `joinWith xs sep toString` + Concatenates all the elements of `xs` converted to string with `toString`, each separated by `sep`, the string given as the second argument, into a single string. If the array has only one element, then that element will be returned without using the separator. If the array is empty, the empty string will be returned. + ```ocaml joinWith [|0; 1|] ", " string_of_int = "0, 1" joinWith [||] " " string_of_int = "" @@ -469,6 +550,7 @@ val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool val some : 'a t -> ('a -> bool) -> bool ``` `some xs p` + returns true if at least one of the elements in xs satifies p;where p is a predicate: a function taking an element and returning a bool. ```ocaml some [|2; 3; 4|] (fun x -> x mod 2 = 1) = true;; @@ -481,6 +563,7 @@ val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool val every : 'a t -> ('a -> bool) -> bool ``` `every xs p` + returns true if all elements satisfy p;where p is a predicate: a function taking an element and returning a bool. ```ocaml every [|1; 3; 5|] (fun x -> x mod 2 = 1) = true;; @@ -493,6 +576,7 @@ val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool ``` `every2 xs ys p` returns true if `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + ```ocaml every2 [|1;2;3|] [|0;1|] (>) = true;; every2 [||] [|1|] (fun x y -> x > y) = true;; @@ -506,6 +590,7 @@ val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool ``` `some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + ```ocaml some2 [|0;2|] [|1;0;3|] (>) = true ;; (some2 [||] [|1|] (fun x y -> x > y)) = false;; @@ -518,6 +603,7 @@ val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int ``` `cmp xs ys f` + - Compared by length if `length xs <> length ys`;returning \-1 if`length xs < length ys` or 1 if `length xs > length ys` - Otherwise compare one by one `f x y`. `f` returns - a negative number if `x` is “less than” `y` @@ -536,6 +622,7 @@ val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool ``` `eq xs ys` + - return false if length is not the same - otherwise compare items one by one using `f xi yi`;and return true if all results are true;false otherwise ```ocaml @@ -545,8 +632,11 @@ val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool val truncateToLengthUnsafe : 'a t -> int -> unit ``` **Unsafe** `truncateToLengthUnsafe xs n` sets length of array `xs` to `n`. + If `n` is greater than the length of `xs`;the extra elements are set to `Js.Null_undefined.null` + If `n` is less than zero;raises a `RangeError`. + ```ocaml let arr = [|"ant";"bee";"cat";"dog";"elk"|];; let () = truncateToLengthUnsafe arr 3;; @@ -561,4 +651,4 @@ val init : int -> (int -> 'a) -> 'a t ``` val push : 'a t -> 'a -> unit ``` -`arr->push(item)` push element \`item\` into the array \ No newline at end of file +`arr->push(item)` push element \`item\` into the array diff --git a/docs/api/melange/Belt-Float.md b/docs/api/melange/Belt-Float.md index d062921e5..a05b382d7 100644 --- a/docs/api/melange/Belt-Float.md +++ b/docs/api/melange/Belt-Float.md @@ -1,5 +1,8 @@ + # Module `Belt.Float` + [`Belt.Float`](#) Utililites for Float + ``` val toInt : float -> int ``` diff --git a/docs/api/melange/Belt-HashMap-Int.md b/docs/api/melange/Belt-HashMap-Int.md index f9083e664..46c1f54f7 100644 --- a/docs/api/melange/Belt-HashMap-Int.md +++ b/docs/api/melange/Belt-HashMap-Int.md @@ -1,5 +1,8 @@ + # Module `HashMap.Int` + Specalized when key type is `int`, more efficient than the generic type + ``` type key = int ``` @@ -19,6 +22,7 @@ val isEmpty : _ t -> bool val set : 'a t -> key -> 'a -> unit ``` `setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` + ``` val copy : 'a t -> 'a t ``` diff --git a/docs/api/melange/Belt-HashMap-String.md b/docs/api/melange/Belt-HashMap-String.md index 4708b8f0c..dc5e0eab3 100644 --- a/docs/api/melange/Belt-HashMap-String.md +++ b/docs/api/melange/Belt-HashMap-String.md @@ -1,5 +1,8 @@ + # Module `HashMap.String` + Specalized when key type is `string`, more efficient than the generic type + ``` type key = string ``` @@ -19,6 +22,7 @@ val isEmpty : _ t -> bool val set : 'a t -> key -> 'a -> unit ``` `setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` + ``` val copy : 'a t -> 'a t ``` diff --git a/docs/api/melange/Belt-HashMap.md b/docs/api/melange/Belt-HashMap.md index 9acf8b3e0..0c0c8533e 100644 --- a/docs/api/melange/Belt-HashMap.md +++ b/docs/api/melange/Belt-HashMap.md @@ -1,10 +1,18 @@ + # Module `Belt.HashMap` + [`Belt.HashMap`](#) + The top level provides generic **mutable** hash map operations. + It also has two specialized inner modules [`Belt.HashMap.Int`](./Belt-HashMap-Int.md) and [`Belt.HashMap.String`](./Belt-HashMap-String.md) + A **mutable** Hash map which allows customized hash behavior. + All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashMaps of ints* initialized with different *hash* functions will have different type. + For example: + ```ocaml type t = int module I0 = @@ -21,12 +29,15 @@ For example: let s1 : (_, string,_) t = make ~hintSize:40 ~id:(module I1) ``` The invariant must be held: for two elements who are *equal*, their hashed value should be the same + Here the compiler would infer `s0` and `s1` having different type so that it would not mix. + ```ocaml val s0 : (int, I0.identity) t val s1 : (int, I1.identity) t ``` We can add elements to the collection: + ```ocaml let () = @@ -34,18 +45,22 @@ We can add elements to the collection: add s1 1 "3" ``` Since this is an mutable data strucure, `s1` will contain two pairs. + ``` module Int : sig ... end ``` Specalized when key type is `int`, more efficient than the generic type + ``` module String : sig ... end ``` Specalized when key type is `string`, more efficient than the generic type + ``` type ('key, 'value, 'id) t ``` The type of hash tables from type `'key` to type `'value`. + ``` type ('a, 'id) id = (module Belt__.Belt_Id.Hashable @@ -59,6 +74,7 @@ val make : hintSize:int -> id:('key, 'id) id -> ('key, 'value, 'id) t val clear : ('key, 'value, 'id) t -> unit ``` Empty a hash table. + ``` val isEmpty : (_, _, _) t -> bool ``` @@ -66,6 +82,7 @@ val isEmpty : (_, _, _) t -> bool val set : ('key, 'value, 'id) t -> 'key -> 'value -> unit ``` `set tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` + ``` val copy : ('key, 'value, 'id) t -> ('key, 'value, 'id) t ``` @@ -76,6 +93,7 @@ val get : ('key, 'value, 'id) t -> 'key -> 'value option val has : ('key, 'value, 'id) t -> 'key -> bool ``` `has tbl x` checks if `x` is bound in `tbl`. + ``` val remove : ('key, 'value, 'id) t -> 'key -> unit ``` @@ -89,6 +107,7 @@ val forEachU : val forEach : ('key, 'value, 'id) t -> ('key -> 'value -> unit) -> unit ``` `forEach tbl f` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. + ``` val reduceU : ('key, 'value, 'id) t -> @@ -100,7 +119,9 @@ val reduceU : val reduce : ('key, 'value, 'id) t -> 'c -> ('c -> 'key -> 'value -> 'c) -> 'c ``` `reduce tbl init f` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. + The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + ``` val keepMapInPlaceU : ('key, 'value, 'id) t -> @@ -117,6 +138,7 @@ val keepMapInPlace : val size : (_, _, _) t -> int ``` `size tbl` returns the number of bindings in `tbl`. It takes constant time. + ``` val toArray : ('key, 'value, 'id) t -> ('key * 'value) array ``` diff --git a/docs/api/melange/Belt-HashSet-Int.md b/docs/api/melange/Belt-HashSet-Int.md index 8a8c11c20..e674b95e9 100644 --- a/docs/api/melange/Belt-HashSet-Int.md +++ b/docs/api/melange/Belt-HashSet-Int.md @@ -1,8 +1,14 @@ + # Module `HashSet.Int` + Specalized when key type is `int`, more efficient than the generic type + This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. + It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + **See** [`Belt.HashSet`](./Belt-HashSet.md) + ``` type key = int ``` diff --git a/docs/api/melange/Belt-HashSet-String.md b/docs/api/melange/Belt-HashSet-String.md index 9f0c86032..299cc480d 100644 --- a/docs/api/melange/Belt-HashSet-String.md +++ b/docs/api/melange/Belt-HashSet-String.md @@ -1,8 +1,14 @@ + # Module `HashSet.String` + Specalized when key type is `string`, more efficient than the generic type + This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. + It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + **See** [`Belt.HashSet`](./Belt-HashSet.md) + ``` type key = string ``` diff --git a/docs/api/melange/Belt-HashSet.md b/docs/api/melange/Belt-HashSet.md index 8061c8421..1f8647d50 100644 --- a/docs/api/melange/Belt-HashSet.md +++ b/docs/api/melange/Belt-HashSet.md @@ -1,10 +1,18 @@ + # Module `Belt.HashSet` + [`Belt.HashSet`](#) + The top level provides generic **mutable** hash set operations. + It also has two specialized inner modules [`Belt.HashSet.Int`](./Belt-HashSet-Int.md) and [`Belt.HashSet.String`](./Belt-HashSet-String.md) + A **mutable** Hash set which allows customized hash behavior. + All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashSets of ints* initialized with different *hash* functions will have different type. + For example: + ```ocaml type t = int module I0 = @@ -21,12 +29,15 @@ For example: let s1 = make ~id:(module I1) ~hintSize:40 ``` The invariant must be held: for two elements who are *equal*, their hashed value should be the same + Here the compiler would infer `s0` and `s1` having different type so that it would not mix. + ```ocaml val s0 : (int, I0.identity) t val s1 : (int, I1.identity) t ``` We can add elements to the collection: + ```ocaml let () = @@ -34,18 +45,22 @@ We can add elements to the collection: add s1 1 ``` Since this is an mutable data strucure, `s1` will contain two pairs. + ``` module Int : sig ... end ``` Specalized when key type is `int`, more efficient than the generic type + ``` module String : sig ... end ``` Specalized when key type is `string`, more efficient than the generic type + ``` type ('a, 'id) t ``` The type of hash tables from type `'a` to type `'b`. + ``` type ('a, 'id) id = (module Belt__.Belt_Id.Hashable @@ -80,6 +95,7 @@ val forEachU : ('a, 'id) t -> ('a -> unit) Js.Fn.arity1 -> unit val forEach : ('a, 'id) t -> ('a -> unit) -> unit ``` Order unspecified. + ``` val reduceU : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) Js.Fn.arity2 -> 'c ``` @@ -87,6 +103,7 @@ val reduceU : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) Js.Fn.arity2 -> 'c val reduce : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) -> 'c ``` Order unspecified. + ``` val size : ('a, 'id) t -> int ``` diff --git a/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md b/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md index c50c978a9..7cdbeba8e 100644 --- a/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md +++ b/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md @@ -1,4 +1,6 @@ + # Parameter `MakeComparable.M` + ``` type t ``` diff --git a/docs/api/melange/Belt-Id-MakeComparable.md b/docs/api/melange/Belt-Id-MakeComparable.md index 8f7a9ff16..a4e124a8e 100644 --- a/docs/api/melange/Belt-Id-MakeComparable.md +++ b/docs/api/melange/Belt-Id-MakeComparable.md @@ -1,9 +1,15 @@ + # Module `Id.MakeComparable` + + ## Parameters + ``` module M : sig ... end ``` + ## Signature + ``` type identity ``` diff --git a/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md b/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md index 8fc1b5d88..94b48d88a 100644 --- a/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md +++ b/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md @@ -1,4 +1,6 @@ + # Parameter `MakeComparableU.M` + ``` type t ``` diff --git a/docs/api/melange/Belt-Id-MakeComparableU.md b/docs/api/melange/Belt-Id-MakeComparableU.md index 720efb1a1..6ade5dd1d 100644 --- a/docs/api/melange/Belt-Id-MakeComparableU.md +++ b/docs/api/melange/Belt-Id-MakeComparableU.md @@ -1,9 +1,15 @@ + # Module `Id.MakeComparableU` + + ## Parameters + ``` module M : sig ... end ``` + ## Signature + ``` type identity ``` diff --git a/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md b/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md index 72f1862a2..2ad08437b 100644 --- a/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md +++ b/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md @@ -1,4 +1,6 @@ + # Parameter `MakeHashable.M` + ``` type t ``` diff --git a/docs/api/melange/Belt-Id-MakeHashable.md b/docs/api/melange/Belt-Id-MakeHashable.md index a98e058be..15f31e6d6 100644 --- a/docs/api/melange/Belt-Id-MakeHashable.md +++ b/docs/api/melange/Belt-Id-MakeHashable.md @@ -1,9 +1,15 @@ + # Module `Id.MakeHashable` + + ## Parameters + ``` module M : sig ... end ``` + ## Signature + ``` type identity ``` diff --git a/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md b/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md index 9d8b06d75..eb5a430a2 100644 --- a/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md +++ b/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md @@ -1,4 +1,6 @@ + # Parameter `MakeHashableU.M` + ``` type t ``` diff --git a/docs/api/melange/Belt-Id-MakeHashableU.md b/docs/api/melange/Belt-Id-MakeHashableU.md index 4dd0b7009..a8834245f 100644 --- a/docs/api/melange/Belt-Id-MakeHashableU.md +++ b/docs/api/melange/Belt-Id-MakeHashableU.md @@ -1,9 +1,15 @@ + # Module `Id.MakeHashableU` + + ## Parameters + ``` module M : sig ... end ``` + ## Signature + ``` type identity ``` diff --git a/docs/api/melange/Belt-Id-module-type-Comparable.md b/docs/api/melange/Belt-Id-module-type-Comparable.md index c83cf4e96..8f8f4244d 100644 --- a/docs/api/melange/Belt-Id-module-type-Comparable.md +++ b/docs/api/melange/Belt-Id-module-type-Comparable.md @@ -1,4 +1,6 @@ + # Module type `Id.Comparable` + ``` type identity ``` diff --git a/docs/api/melange/Belt-Id-module-type-Hashable.md b/docs/api/melange/Belt-Id-module-type-Hashable.md index 4a1aaadd4..9758efeeb 100644 --- a/docs/api/melange/Belt-Id-module-type-Hashable.md +++ b/docs/api/melange/Belt-Id-module-type-Hashable.md @@ -1,4 +1,6 @@ + # Module type `Id.Hashable` + ``` type identity ``` diff --git a/docs/api/melange/Belt-Id.md b/docs/api/melange/Belt-Id.md index ab2863728..d9072b719 100644 --- a/docs/api/melange/Belt-Id.md +++ b/docs/api/melange/Belt-Id.md @@ -1,25 +1,39 @@ + # Module `Belt.Id` + [`Belt.Id`](#) + Provide utilities to create identified comparators or hashes for data structures used below. + It create a unique identifier per module of functions so that different data structures with slightly different comparison functions won't mix + [`Belt.Id`](#) + Provide utiliites to create identified comparators or hashes for data structures used below. + It create a unique identifer per module of functions so that different data structures with slightly different comparison functions won't mix. + ``` type ('a, 'id) hash ``` `('a, 'id) hash` + Its runtime represenation is a `hash` function, but signed with a type parameter, so that different hash functions type mismatch + ``` type ('a, 'id) eq ``` `('a, 'id) eq` + Its runtime represenation is an `eq` function, but signed with a type parameter, so that different hash functions type mismatch + ``` type ('a, 'id) cmp ``` `('a,'id) cmp` + Its runtime representation is a `cmp` function, but signed with a type parameter, so that different hash functions type mismatch + ``` module type Comparable = sig ... end ``` @@ -30,9 +44,13 @@ type ('key, 'id) comparable = and type t = 'key) ``` `('key, 'id) cmparable` is a module of functions, here it only includes `cmp`. + Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). + It can be created using function [`comparableU`](./#val-comparableU) or [`comparable`](./#val-comparable). + The idea of a unique identity when created is that it makes sure two sets would type mismatch if they use different comparison function + ``` module MakeComparableU (M : sig ... end) : Comparable with type t = M.t ``` @@ -55,6 +73,7 @@ val comparable : cmp:('a -> 'a -> int) -> (module Comparable with type t = 'a) let m = Belt.Set.make(module C) ``` Note that the name of C can not be ignored + ``` module type Hashable = sig ... end ``` @@ -65,9 +84,13 @@ type ('key, 'id) hashable = and type t = 'key) ``` `('key, 'id) hashable` is a module of functions, here it only includes `hash`, `eq`. + Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). + It can be created using function [`hashableU`](./#val-hashableU) or [`hashable`](./#val-hashable). + The idea of a unique identity when created is that it makes sure two hash sets would type mismatch if they use different comparison function + ``` module MakeHashableU (M : sig ... end) : Hashable with type t = M.t ``` diff --git a/docs/api/melange/Belt-Int.md b/docs/api/melange/Belt-Int.md index 2ace83c57..e16080186 100644 --- a/docs/api/melange/Belt-Int.md +++ b/docs/api/melange/Belt-Int.md @@ -1,5 +1,8 @@ + # Module `Belt.Int` + [`Belt.Int`](#) Utililites for Int + ``` val toFloat : int -> float ``` diff --git a/docs/api/melange/Belt-List.md b/docs/api/melange/Belt-List.md index 93f1dd9cd..eb9dee2fd 100644 --- a/docs/api/melange/Belt-List.md +++ b/docs/api/melange/Belt-List.md @@ -1,26 +1,37 @@ + # Module `Belt.List` + [`Belt.List`](#) + Utilities for List data type + [`Belt.List`](#) + Utilities for List data type. + This module is compatible with original ocaml stdlib. In general, all functions comes with the original stdlib also applies to this collection, however, this module provides faster and stack safer utilities + ``` type 'a t = 'a list ``` `'a t` is compatible with built-in `list` type + ``` val length : 'a t -> int ``` `length xs` + returns the length of the list xs ``` val size : 'a t -> int ``` **See** [`length`](./#val-length) + ``` val head : 'a t -> 'a option ``` `head xs` returns `None` if `xs` is the empty list, otherwise it returns `Some value` where `value` is the first element in the list. + ```ocaml head [] = None ;; head [1;2;3] = Some 1 ;; @@ -29,12 +40,16 @@ val head : 'a t -> 'a option val headExn : 'a t -> 'a ``` `headExn xs` + **See** [`head`](./#val-head) + **raise** an exception if `xs` is empty + ``` val tail : 'a t -> 'a t option ``` `tail xs` returns `None` if `xs` is empty; otherwise it returns `Some xs2` where `xs2` is everything except the first element of `xs`; + ```ocaml tail [] = None;; tail [1;2;3;4] = Some [2;3;4];; @@ -43,12 +58,16 @@ val tail : 'a t -> 'a t option val tailExn : 'a t -> 'a t ``` `tailExn xs` + **See** [`tail`](./#val-tail) + **raise** an exception if `xs` is empty + ``` val add : 'a t -> 'a -> 'a t ``` `add xs y` adds `y` to the beginning of list `xs` + ```ocaml add [1] 3 = [3;1];; ``` @@ -56,7 +75,9 @@ val add : 'a t -> 'a -> 'a t val get : 'a t -> int -> 'a option ``` `get xs n` + return the nth element in `xs`, or `None` if `n` is larger than the length + ```ocaml get [0;3;32] 2 = Some 32 ;; get [0;3;32] 3 = None;; @@ -65,12 +86,16 @@ return the nth element in `xs`, or `None` if `n` is larger than the length val getExn : 'a t -> int -> 'a ``` `getExn xs n` + **See** [`get`](./#val-get) + **raise** an exception if `n` is larger than the length + ``` val make : int -> 'a -> 'a t ``` `make n v` + - return a list of length `n` with each element filled with value `v` - return the empty list if `n` is negative ```ocaml @@ -83,6 +108,7 @@ val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t val makeBy : int -> (int -> 'a) -> 'a t ``` `makeBy n f` + - return a list of length `n` with element `i` initialized with `f i` - return the empty list if `n` is negative ```ocaml @@ -93,12 +119,15 @@ val makeBy : int -> (int -> 'a) -> 'a t val shuffle : 'a t -> 'a t ``` `shuffle xs` + returns a new list in random order ``` val drop : 'a t -> int -> 'a t option ``` `drop xs n` + return the list obtained by dropping the first `n` elements, or `None` if `xs` has fewer than `n` elements + ```ocaml drop [1;2;3] 2 = Some [3];; drop [1;2;3] 3 = Some [];; @@ -108,7 +137,9 @@ return the list obtained by dropping the first `n` elements, or `None` if `xs` h val take : 'a t -> int -> 'a t option ``` `take xs n` + return a list with the first `n` elements from `xs`, or `None` if `xs` has fewer than `n` elements + ```ocaml take [1;2;3] 1 = Some [1];; take [1;2;3] 2 = Some [1;2];; @@ -118,6 +149,7 @@ return a list with the first `n` elements from `xs`, or `None` if `xs` has fewer val splitAt : 'a t -> int -> ('a list * 'a list) option ``` `splitAt xs n` split the list `xs` at position `n` return None when the length of `xs` is less than `n` + ```ocaml splitAt [0;1;2;3;4] 2 = Some ([0;1], [2;3;4]) ``` @@ -125,6 +157,7 @@ val splitAt : 'a t -> int -> ('a list * 'a list) option val concat : 'a t -> 'a t -> 'a t ``` `concat xs ys` + returns the list obtained by adding ys after xs ```ocaml concat [1;2;3] [4;5] = [1;2;3;4;5] @@ -133,6 +166,7 @@ returns the list obtained by adding ys after xs val concatMany : 'a t array -> 'a t ``` `concatMany a` return the list obtained by concatenating in order all the lists in array `a` + ```ocaml concatMany [| [1;2;3] ; []; [3]; [4] |] = [1;2;3;3;4] ``` @@ -140,6 +174,7 @@ val concatMany : 'a t array -> 'a t val reverseConcat : 'a t -> 'a t -> 'a t ``` `reverseConcat xs ys` is equivalent to `concat (reverse xs) ys` + ```ocaml reverseConcat [1;2] [3;4] = [2;1;3;4] ``` @@ -147,6 +182,7 @@ val reverseConcat : 'a t -> 'a t -> 'a t val flatten : 'a t t -> 'a t ``` `flatten ls` return the list obtained by concatenating in order all the lists in list `ls` + ```ocaml flatten [ [1;2;3] ; []; [3]; [4] ] = [1;2;3;3;4] ``` @@ -157,7 +193,9 @@ val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t val map : 'a t -> ('a -> 'b) -> 'b t ``` `map xs f` + return the list obtained by applying `f` to each element of `xs` + ```ocaml map [1;2] (fun x-> x + 1) = [3;4] ``` @@ -165,6 +203,7 @@ return the list obtained by applying `f` to each element of `xs` val zip : 'a t -> 'b t -> ('a * 'b) t ``` `zip xs ys` + returns a list of pairs from the two lists with the length of the shorter list ```ocaml zip [1;2] [3;4;5] = [(1,3); (2,4)] @@ -176,8 +215,11 @@ val zipByU : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t val zipBy : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t ``` `zipBy xs ys f` + **See** [`zip`](./#val-zip) + Equivalent to `zip xs ys |> List.map (fun (x,y) -> f x y)` + ```ocaml zipBy [1;2;3] [4;5] (fun a b -> 2 * a + b) = [6;9];; ``` @@ -188,6 +230,7 @@ val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t ``` `mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. + ```ocaml mapWithIndex [1;2;3] (fun i x -> i + x) = [0 + 1; 1 + 2; 2 + 3 ] @@ -196,6 +239,7 @@ val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t val fromArray : 'a array -> 'a t ``` `fromArray arr` converts the given array to a list + ```ocaml fromArray [|1;2;3|] = [1;2;3] ``` @@ -203,6 +247,7 @@ val fromArray : 'a array -> 'a t val toArray : 'a t -> 'a array ``` `toArray xs` converts the given list to an array + ```ocaml toArray [1;2;3] = [|1;2;3|] ``` @@ -210,6 +255,7 @@ val toArray : 'a t -> 'a array val reverse : 'a t -> 'a t ``` `reverse xs` returns a new list whose elements are those of `xs` in reverse order. + ```ocaml reverse [1;2;3] = [3;2;1] ``` @@ -220,7 +266,9 @@ val mapReverseU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t val mapReverse : 'a t -> ('a -> 'b) -> 'b t ``` `mapReverse xs f` + Equivalent to `reverse (map xs f)` + ```ocaml mapReverse [3;4;5] (fun x -> x * x) = [25;16;9];; ``` @@ -231,6 +279,7 @@ val forEachU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> unit val forEach : 'a t -> ('a -> 'b) -> unit ``` `forEach xs f ` Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`, so no new array is created. Use `foreach` when you are primarily concerned with repetitively creating side effects. + ```ocaml forEach ["a";"b";"c"] (fun x -> Js.log("Item: " ^ x));; (* prints: @@ -250,6 +299,7 @@ val forEachWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> unit val forEachWithIndex : 'a t -> (int -> 'a -> 'b) -> unit ``` `forEachWithIndex xs f` + ```ocaml forEach ["a";"b";"c"] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; @@ -270,7 +320,9 @@ val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b ``` `reduce xs f` + Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”, which starts with a value of `init`. `reduce` returns the final value of the accumulator. + ```ocaml reduce [1;2;3;4] 0 (+) = 10;; reduce [1;2;3;4] 10 (-) = 0;; @@ -283,7 +335,9 @@ val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b ``` `reduceWithIndex xs f` + Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the list and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. + ```ocaml reduceWithIndex [1;2;3;4] 0 (fun acc x i -> acc + x + i) = 16;; ``` @@ -294,7 +348,9 @@ val reduceReverseU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b val reduceReverse : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b ``` `reduceReverse xs f` + Works like [`reduce`](./#val-reduce), except that function `f` is applied to each item of `xs` from the last back to the first. + ```ocaml reduceReverse [1;2;3;4] 0 (+) = 10;; reduceReverse [1;2;3;4] 10 (-) = 0;; @@ -307,7 +363,9 @@ val mapReverse2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t val mapReverse2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t ``` `mapReverse2 xs ys f` + equivalent to `reverse (zipBy xs ys f)` + ```ocaml mapReverse2 [1;2;3] [1;2] (+) = [4;2] ``` @@ -318,6 +376,7 @@ val forEach2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> unit val forEach2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> unit ``` `forEach2 xs ys f` stop with the shorter list + ``` val reduce2U : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) Js.Fn.arity3 -> 'a ``` @@ -325,7 +384,9 @@ val reduce2U : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) Js.Fn.arity3 -> 'a val reduce2 : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) -> 'a ``` `reduce2 xs ys init f ` + Applies `f` to each element of `xs` and `ys` from beginning to end. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. + ```ocaml reduce2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; reduce2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [2 +5;1 + 4 ];; (*add appends at end *) @@ -342,7 +403,9 @@ val reduceReverse2U : val reduceReverse2 : 'a t -> 'b t -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c ``` `reduceReverse2 xs ys init f ` + Applies `f` to each element of `xs` and `ys` from end to beginning. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. + ```ocaml reduceReverse2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; reduceReverse2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [1 + 4;2 + 5];; (*add appends at end *) @@ -354,6 +417,7 @@ val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool val every : 'a t -> ('a -> bool) -> bool ``` `every xs p` + returns true if all elements satisfy p, where p is a predicate: a function taking an element and returning a bool. ```ocaml every [] (fun x -> x mod 2 = 0) = true;; @@ -367,6 +431,7 @@ val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool val some : 'a t -> ('a -> bool) -> bool ``` `some xs p` + returns true if at least one of the elements in xs satifies p, where p is a predicate: a function taking an element and returning a bool. ```ocaml some [] (fun x -> x mod 2 = 0) = false ;; @@ -380,6 +445,7 @@ val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool ``` `every2 xs ys p` returns true if predicate `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + ```ocaml every2 [1;2;3] [0;1] (>) = true;; every2 [] [1] (fun x y -> x > y) = true;; @@ -393,6 +459,7 @@ val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool ``` `some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + ```ocaml some2 [0;2] [1;0;3] (>) = true ;; some2 [] [1] (fun x y -> x > y) = false;; @@ -402,7 +469,9 @@ val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool val cmpByLength : 'a t -> 'a t -> int ``` `cmpByLength l1 l2` + Compare two lists solely by length. Returns \-1 if `length l1` is less than `length l2`, 0 if `length l1` equals `length l2`, and 1 if `length l1` is greater than `length l2`. + ```ocaml cmpByLength [1;2] [3;4;5;6] = -1;; cmpByLength [1;2;3] [4;5;6] = 0;; @@ -415,6 +484,7 @@ val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int ``` Compare elements one by one `f x y`. `f` returns + - a negative number if `x` is “less than” `y` - zero if `x` is “equal to” `y` - a positive number if `x` is “greater than” `y` The comparison returns the first non-zero result of `f`, or zero if `f` returns zero for all `x` and `y`. If all items have compared equal, but `xs` is exhausted first, return \-1. (`xs` is shorter) If all items have compared equal, but `ys` is exhausted first, return 1 (`xs` is longer) @@ -426,6 +496,7 @@ Compare elements one by one `f x y`. `f` returns cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; ``` **Attention**: The total ordering of List is different from Array, for Array, we compare the length first and, only if the lengths are equal, elements one by one. For lists, we just compare elements one by one + ``` val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -433,6 +504,7 @@ val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool ``` `eq xs ys eqElem` check equality of `xs` and `ys` using `eqElem` for equality on elements, where `eqElem` is a function that returns true if items `x` and `y` meet some criterion for equality, false otherwise. `eq` false if length of `xs` and `ys` are not the same. + ```ocaml eq [1;2;3] [1;2] (=) = false ;; eq [1;2] [1;2] (=) = true;; @@ -445,6 +517,7 @@ val hasU : 'a t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool val has : 'a t -> 'b -> ('a -> 'b -> bool) -> bool ``` `has xs eqFcn` returns true if the list contains at least one element for which `eqFcn x` returns true + ```ocaml has [1;2;3] 2 (=) = true;; has [1;2;3] 4 (=) = false;; @@ -457,6 +530,7 @@ val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option val getBy : 'a t -> ('a -> bool) -> 'a option ``` `getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. + ```ocaml getBy [1;4;3;2] (fun x -> x mod 2 = 0) = Some 4 getBy [15;13;11] (fun x -> x mod 2 = 0) = None @@ -468,6 +542,7 @@ val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t val keep : 'a t -> ('a -> bool) -> 'a t ``` `keep xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` + ```ocaml keep [1;2;3;4] (fun x -> x mod 2 = 0) = [2;4] @@ -479,6 +554,7 @@ val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t ``` `keepWithIndex xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` + ```ocaml keepWithIndex [1;2;3;4] (fun _x i -> i mod 2 = 0) = @@ -491,6 +567,7 @@ val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b t val keepMap : 'a t -> ('a -> 'b option) -> 'b t ``` `keepMap xs f` applies `f` to each element of `xs`. If `f xi` returns `Some value`, then `value` is kept in the resulting list; if `f xi` returns `None`, the element is not retained in the result. + ```ocaml keepMap [1;2;3;4] (fun x -> if x mod 2 = 0 then Some (-x ) else None) = @@ -503,6 +580,7 @@ val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t val partition : 'a t -> ('a -> bool) -> 'a t * 'a t ``` `partition xs p` creates a pair of lists; the first list consists of all elements of `xs` that satisfy the predicate function `p`; the second list consists of all elements of `xs` that do not satisfy `p` + ```ocaml partition [1;2;3;4] (fun x -> x mod 2 = 0) = ([2;4], [1;3]) @@ -511,6 +589,7 @@ val partition : 'a t -> ('a -> bool) -> 'a t * 'a t val unzip : ('a * 'b) t -> 'a t * 'b t ``` `unzip xs` takes a list of pairs and creates a pair of lists. The first list contains all the first items of the pairs; the second list contains all the second items. + ```ocaml unzip [(1,2) ; (3,4)] = ([1;3], [2;4]);; unzip [(1,2) ; (3,4) ; (5,6) ; (7,8)] = ([1;3;5;7], [2;4;6;8]);; @@ -526,7 +605,9 @@ val getAssocU : val getAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> 'c option ``` `getAssoc xs k eq` + return the second element of a pair in `xs` where the first element equals `x` as per the predicate function `eq`, or `None` if not found + ```ocaml getAssoc [ 1, "a"; 2, "b"; 3, "c"] 2 (=) = Some "b" getAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = Some "afternoon" @@ -538,6 +619,7 @@ val hasAssocU : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool val hasAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> bool ``` `hasAssoc xs k eq` return true if there is a pair in `xs` where the first element equals `k` as per the predicate funtion `eq` + ```ocaml hasAssoc [1, "a"; 2, "b"; 3,"c"] 1 (=) = true;; hasAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = true;; @@ -553,6 +635,7 @@ val removeAssocU : val removeAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> ('a * 'c) t ``` `removeAssoc xs k eq` Return a list after removing the first pair whose first value is `k` per the equality predicate `eq`; if not found, return a new list identical to `xs`. + ```ocaml removeAssoc [1,"a"; 2, "b"; 3, "c" ] 1 (=) = [2, "b"; 3, "c"] @@ -571,6 +654,7 @@ val setAssocU : val setAssoc : ('a * 'c) t -> 'a -> 'c -> ('a -> 'a -> bool) -> ('a * 'c) t ``` `setAssoc xs k v eq` if `k` exists in `xs` by satisfying the `eq` predicate, return a new list with the key and value replaced by the new `k` and `v`; otherwise, return a new list with the pair `k, v` added to the head of `xs`. + ```ocaml setAssoc [1,"a"; 2, "b"; 3, "c"] 2 "x" (=) = [1,"a"; 2, "x"; 3,"c"] ;; @@ -582,6 +666,7 @@ val setAssoc : ('a * 'c) t -> 'a -> 'c -> ('a -> 'a -> bool) -> ('a * 'c) t (fun a b -> a mod 12 = b mod 12) = [9, "morning"; 15, "afternoon"; 22, "night"] ``` Note carefully the last example\! Since `15 mod 12` equals `3 mod 12`, *both* the key and value are replaced in the list. + ``` val sortU : 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a t ``` @@ -589,6 +674,7 @@ val sortU : 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a t val sort : 'a t -> ('a -> 'a -> int) -> 'a t ``` `sort xs` Returns a sorted list. + ```ocaml sort [5; 4; 9; 3; 7] (fun a b -> a - b) = [3; 4; 5; 7; 9] ``` \ No newline at end of file diff --git a/docs/api/melange/Belt-Map-Dict.md b/docs/api/melange/Belt-Map-Dict.md index 2c198bbe4..61b1e8167 100644 --- a/docs/api/melange/Belt-Map-Dict.md +++ b/docs/api/melange/Belt-Map-Dict.md @@ -1,6 +1,10 @@ + # Module `Map.Dict` + This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + **Advanced usage only** + ``` type ('key, 'value, 'id) t ``` @@ -49,6 +53,7 @@ val eq : bool ``` `eq m1 m2 cmp` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + ``` val findFirstByU : ('k, 'v, 'id) t -> @@ -59,6 +64,7 @@ val findFirstByU : val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option ``` `findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; @@ -70,6 +76,7 @@ val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit ``` `forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val reduceU : ('k, 'a, 'id) t -> @@ -81,6 +88,7 @@ val reduceU : val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b ``` `reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + ``` val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -88,6 +96,7 @@ val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool ``` `every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + ``` val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -95,6 +104,7 @@ val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool ``` `some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + ``` val size : ('k, 'a, 'id) t -> int ``` @@ -102,6 +112,7 @@ val size : ('k, 'a, 'id) t -> int val toList : ('k, 'a, 'id) t -> ('k * 'a) list ``` In increasing order. + ``` val toArray : ('k, 'a, 'id) t -> ('k * 'a) array ``` @@ -158,10 +169,12 @@ val getExn : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a val checkInvariantInternal : (_, _, _) t -> unit ``` **raise** when invariant is not held + ``` val remove : ('a, 'b, 'id) t -> 'a -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t ``` `remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. + ``` val removeMany : ('a, 'b, 'id) t -> @@ -173,6 +186,7 @@ val removeMany : val set : ('a, 'b, 'id) t -> 'a -> 'b -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t ``` `set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + ``` val updateU : ('a, 'b, 'id) t -> @@ -206,6 +220,7 @@ val merge : ('a, 'd, 'id) t ``` `merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + ``` val mergeMany : ('a, 'b, 'id) t -> @@ -223,6 +238,7 @@ val keepU : val keep : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> ('k, 'a, 'id) t ``` `keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + ``` val partitionU : ('k, 'a, 'id) t -> @@ -236,6 +252,7 @@ val partition : ('k, 'a, 'id) t * ('k, 'a, 'id) t ``` `partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + ``` val split : ('a, 'b, 'id) t -> @@ -244,6 +261,7 @@ val split : (('a, 'b, 'id) t * ('a, 'b, 'id) t) * 'b option ``` `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + ``` val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t ``` @@ -251,6 +269,7 @@ val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t ``` `map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapWithKeyU : ('k, 'a, 'id) t -> diff --git a/docs/api/melange/Belt-Map-Int.md b/docs/api/melange/Belt-Map-Int.md index 36f9bfce3..fe3ddaa90 100644 --- a/docs/api/melange/Belt-Map-Int.md +++ b/docs/api/melange/Belt-Map-Int.md @@ -1,5 +1,8 @@ + # Module `Map.Int` + Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + ``` type key = int ``` @@ -7,6 +10,7 @@ type key = int type 'value t ``` The type of maps from type `key` to type `'value`. + ``` val empty : 'v t ``` @@ -29,6 +33,7 @@ val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool ``` `eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. + ``` val findFirstByU : 'v t -> @@ -39,6 +44,7 @@ val findFirstByU : val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option ``` `findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; @@ -50,6 +56,7 @@ val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit val forEach : 'v t -> (key -> 'v -> unit) -> unit ``` `forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 ``` @@ -57,6 +64,7 @@ val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 ``` `reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + ``` val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool ``` @@ -64,6 +72,7 @@ val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool val every : 'v t -> (key -> 'v -> bool) -> bool ``` `every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + ``` val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool ``` @@ -71,6 +80,7 @@ val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool val some : 'v t -> (key -> 'v -> bool) -> bool ``` `some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + ``` val size : 'v t -> int ``` @@ -78,6 +88,7 @@ val size : 'v t -> int val toList : 'v t -> (key * 'v) list ``` In increasing order. + ``` val toArray : 'v t -> (key * 'v) array ``` @@ -130,10 +141,12 @@ val getExn : 'v t -> key -> 'v val checkInvariantInternal : _ t -> unit ``` **raise** when invariant is not held + ``` val remove : 'v t -> key -> 'v t ``` `remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. + ``` val removeMany : 'v t -> key array -> 'v t ``` @@ -141,6 +154,7 @@ val removeMany : 'v t -> key array -> 'v t val set : 'v t -> key -> 'v -> 'v t ``` `set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + ``` val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t ``` @@ -162,6 +176,7 @@ val merge : 'c t ``` `merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + ``` val mergeMany : 'v t -> (key * 'v) array -> 'v t ``` @@ -172,6 +187,7 @@ val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t val keep : 'v t -> (key -> 'v -> bool) -> 'v t ``` `keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + ``` val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t ``` @@ -179,10 +195,12 @@ val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t ``` `partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + ``` val split : key -> 'v t -> 'v t * 'v option * 'v t ``` `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + ``` val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t ``` @@ -190,6 +208,7 @@ val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t val map : 'v t -> ('v -> 'v2) -> 'v2 t ``` `map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t ``` diff --git a/docs/api/melange/Belt-Map-String.md b/docs/api/melange/Belt-Map-String.md index 89ba1550b..1fa79b3e6 100644 --- a/docs/api/melange/Belt-Map-String.md +++ b/docs/api/melange/Belt-Map-String.md @@ -1,5 +1,8 @@ + # Module `Map.String` + specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + ``` type key = string ``` @@ -7,6 +10,7 @@ type key = string type 'value t ``` The type of maps from type `key` to type `'value`. + ``` val empty : 'v t ``` @@ -29,6 +33,7 @@ val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool ``` `eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. + ``` val findFirstByU : 'v t -> @@ -39,6 +44,7 @@ val findFirstByU : val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option ``` `findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; @@ -50,6 +56,7 @@ val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit val forEach : 'v t -> (key -> 'v -> unit) -> unit ``` `forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 ``` @@ -57,6 +64,7 @@ val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 ``` `reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + ``` val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool ``` @@ -64,6 +72,7 @@ val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool val every : 'v t -> (key -> 'v -> bool) -> bool ``` `every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + ``` val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool ``` @@ -71,6 +80,7 @@ val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool val some : 'v t -> (key -> 'v -> bool) -> bool ``` `some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + ``` val size : 'v t -> int ``` @@ -78,6 +88,7 @@ val size : 'v t -> int val toList : 'v t -> (key * 'v) list ``` In increasing order. + ``` val toArray : 'v t -> (key * 'v) array ``` @@ -130,10 +141,12 @@ val getExn : 'v t -> key -> 'v val checkInvariantInternal : _ t -> unit ``` **raise** when invariant is not held + ``` val remove : 'v t -> key -> 'v t ``` `remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. + ``` val removeMany : 'v t -> key array -> 'v t ``` @@ -141,6 +154,7 @@ val removeMany : 'v t -> key array -> 'v t val set : 'v t -> key -> 'v -> 'v t ``` `set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + ``` val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t ``` @@ -162,6 +176,7 @@ val merge : 'c t ``` `merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + ``` val mergeMany : 'v t -> (key * 'v) array -> 'v t ``` @@ -172,6 +187,7 @@ val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t val keep : 'v t -> (key -> 'v -> bool) -> 'v t ``` `keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + ``` val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t ``` @@ -179,10 +195,12 @@ val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t ``` `partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + ``` val split : key -> 'v t -> 'v t * 'v option * 'v t ``` `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + ``` val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t ``` @@ -190,6 +208,7 @@ val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t val map : 'v t -> ('v -> 'v2) -> 'v2 t ``` `map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t ``` diff --git a/docs/api/melange/Belt-Map.md b/docs/api/melange/Belt-Map.md index 6a24b66a6..23dfe9607 100644 --- a/docs/api/melange/Belt-Map.md +++ b/docs/api/melange/Belt-Map.md @@ -1,12 +1,22 @@ + # Module `Belt.Map` + [`Belt.Map`](#), + The top level provides generic **immutable** map operations. + It also has three specialized inner modules [`Belt.Map.Int`](./Belt-Map-Int.md), [`Belt.Map.String`](./Belt-Map-String.md) and + [`Belt.Map.Dict`](./Belt-Map-Dict.md): This module separates data from function which is more verbose but slightly more efficient + A *immutable* sorted map module which allows customize *compare* behavior. + The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. + Example usage: + ```ocaml module PairComparator = Belt.Id.MakeComparable(struct type t = int * int @@ -20,25 +30,33 @@ Example usage: let myMap2 = Belt.Map.set myMap (1, 2) "myValue" ``` The API documentation below will assume a predeclared comparator module for integers, IntCmp + ``` module Int : sig ... end ``` Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + ``` module String : sig ... end ``` specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + ``` module Dict : sig ... end ``` This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + ``` type ('key, 'value, 'identity) t ``` `('key, 'identity) t` + `'key` is the field type + `'value` is the element type + `'identity` the identity of the collection + ``` type ('key, 'id) id = (module Belt__.Belt_Id.Comparable @@ -46,10 +64,12 @@ type ('key, 'id) id = and type t = 'key) ``` The identity needed for making an empty map + ``` val make : id:('k, 'id) id -> ('k, 'v, 'id) t ``` `make ~id` creates a new map by taking in the comparator + ```ocaml let m = Belt.Map.make ~id:(module IntCmp) ``` @@ -57,6 +77,7 @@ val make : id:('k, 'id) id -> ('k, 'v, 'id) t val isEmpty : (_, _, _) t -> bool ``` `isEmpty m` checks whether a map m is empty + ```ocaml isEmpty (fromArray [|1,"1"|] ~id:(module IntCmp)) = false ``` @@ -64,6 +85,7 @@ val isEmpty : (_, _, _) t -> bool val has : ('k, 'v, 'id) t -> 'k -> bool ``` `has m k` checks whether m has the key k + ```ocaml has (fromArray [|1,"1"|] ~id:(module IntCmp)) 1 = true ``` @@ -78,8 +100,11 @@ val cmpU : val cmp : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> int) -> int ``` `cmp m0 m1 vcmp` + Total ordering of map given total ordering of value function. + It will compare size first and each element following the order one by one. + ``` val eqU : ('k, 'v, 'id) t -> @@ -91,6 +116,7 @@ val eqU : val eq : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> bool) -> bool ``` `eq m1 m2 veq` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `veq` is the equality predicate used to compare the data associated with the keys. + ``` val findFirstByU : ('k, 'v, 'id) t -> @@ -101,6 +127,7 @@ val findFirstByU : val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option ``` `findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; @@ -112,6 +139,7 @@ val forEachU : ('k, 'v, 'id) t -> ('k -> 'v -> unit) Js.Fn.arity2 -> unit val forEach : ('k, 'v, 'id) t -> ('k -> 'v -> unit) -> unit ``` `forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; let acc = ref [] ;; @@ -130,6 +158,7 @@ val reduceU : val reduce : ('k, 'v, 'id) t -> 'acc -> ('acc -> 'k -> 'v -> 'acc) -> 'acc ``` `reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; reduce s0 [] (fun acc k v -> (k,v) acc ) = [4,"4";3,"3";2,"2";1,"1"];; @@ -141,6 +170,7 @@ val everyU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool val every : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool ``` `every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + ``` val someU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool ``` @@ -148,10 +178,12 @@ val someU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool val some : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool ``` `some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + ``` val size : ('k, 'v, 'id) t -> int ``` `size s` + ```ocaml size (fromArray [2,"2"; 2,"1"; 3,"3"] ~id:(module IntCmp)) = 2 ;; ``` @@ -159,6 +191,7 @@ val size : ('k, 'v, 'id) t -> int val toArray : ('k, 'v, 'id) t -> ('k * 'v) array ``` `toArray s` + ```ocaml toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] ``` @@ -166,11 +199,14 @@ val toArray : ('k, 'v, 'id) t -> ('k * 'v) array val toList : ('k, 'v, 'id) t -> ('k * 'v) list ``` In increasing order + **See** [`toArray`](./#val-toArray) + ``` val fromArray : ('k * 'v) array -> id:('k, 'id) id -> ('k, 'v, 'id) t ``` `fromArray kvs ~id` + ```ocaml toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] ``` @@ -178,6 +214,7 @@ val fromArray : ('k * 'v) array -> id:('k, 'id) id -> ('k, 'v, 'id) t val keysToArray : ('k, 'v, 'id) t -> 'k array ``` `keysToArray s` + ```ocaml keysToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [|1;2;3|];; @@ -186,6 +223,7 @@ val keysToArray : ('k, 'v, 'id) t -> 'k array val valuesToArray : ('k, 'v, 'id) t -> 'v array ``` `valuesToArray s` + ```ocaml valuesToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [|"1";"2";"3"|];; @@ -194,42 +232,51 @@ val valuesToArray : ('k, 'v, 'id) t -> 'v array val minKey : ('k, _, _) t -> 'k option ``` `minKey s` + returns the minimum key, None if not exist ``` val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined ``` **See** [`minKey`](./#val-minKey) + ``` val maxKey : ('k, _, _) t -> 'k option ``` `maxKey s` + returns the maximum key, None if not exist ``` val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined ``` **See** [`maxKey`](./#val-maxKey) + ``` val minimum : ('k, 'v, _) t -> ('k * 'v) option ``` `minimum s` + returns the minimum key value pair, None if not exist ``` val minUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined ``` **See** [`minimum`](./#val-minimum) + ``` val maximum : ('k, 'v, _) t -> ('k * 'v) option ``` `maximum s` + returns the maximum key value pair, None if not exist ``` val maxUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined ``` **See** [`maximum`](./#val-maximum) + ``` val get : ('k, 'v, 'id) t -> 'k -> 'v option ``` `get s k` + ```ocaml get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = Some "2";; @@ -240,23 +287,30 @@ val get : ('k, 'v, 'id) t -> 'k -> 'v option val getUndefined : ('k, 'v, 'id) t -> 'k -> 'v Js.undefined ``` **See** [`get`](./#val-get) + returns undefined when not found ``` val getWithDefault : ('k, 'v, 'id) t -> 'k -> 'v -> 'v ``` `getWithDefault s k default` + **See** [`get`](./#val-get) + returns default when k is not found ``` val getExn : ('k, 'v, 'id) t -> 'k -> 'v ``` `getExn s k` + **See** [`getExn`](./#val-getExn) + **raise** when `k` not exist + ``` val remove : ('k, 'v, 'id) t -> 'k -> ('k, 'v, 'id) t ``` `remove m x` when `x` is not in `m`, `m` is returned reference unchanged. + ```ocaml let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; @@ -269,11 +323,14 @@ val remove : ('k, 'v, 'id) t -> 'k -> ('k, 'v, 'id) t val removeMany : ('k, 'v, 'id) t -> 'k array -> ('k, 'v, 'id) t ``` `removeMany s xs` + Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` + ``` val set : ('k, 'v, 'id) t -> 'k -> 'v -> ('k, 'v, 'id) t ``` `set m x y ` returns a map containing the same bindings as `m`, with a new binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + ```ocaml let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; @@ -296,11 +353,14 @@ val update : ('k, 'v, 'id) t ``` `update m x f` returns a map containing the same bindings as `m`, except for the binding of `x`. Depending on the value of `y` where `y` is `f (get x m)`, the binding of `x` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `x` is associated to `z` in the resulting map. + ``` val mergeMany : ('k, 'v, 'id) t -> ('k * 'v) array -> ('k, 'v, 'id) t ``` `mergeMany s xs` + Add each of `xs` to `s`, note unlike [`set`](./#val-set), the reference of return value might be changed even if all values in `xs` exist `s` + ``` val mergeU : ('k, 'v, 'id) t -> @@ -316,6 +376,7 @@ val merge : ('k, 'v3, 'id) t ``` `merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + ``` val keepU : ('k, 'v, 'id) t -> @@ -326,6 +387,7 @@ val keepU : val keep : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k, 'v, 'id) t ``` `keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + ``` val partitionU : ('k, 'v, 'id) t -> @@ -339,6 +401,7 @@ val partition : ('k, 'v, 'id) t * ('k, 'v, 'id) t ``` `partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + ``` val split : ('k, 'v, 'id) t -> @@ -346,6 +409,7 @@ val split : (('k, 'v, 'id) t * ('k, 'v, 'id) t) * 'v option ``` `split x m` returns a tuple `(l r), data`, where `l` is the map with all the bindings of `m` whose 'k is strictly less than `x`; `r` is the map with all the bindings of `m` whose 'k is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + ``` val mapU : ('k, 'v, 'id) t -> ('v -> 'v2) Js.Fn.arity1 -> ('k, 'v2, 'id) t ``` @@ -353,6 +417,7 @@ val mapU : ('k, 'v, 'id) t -> ('v -> 'v2) Js.Fn.arity1 -> ('k, 'v2, 'id) t val map : ('k, 'v, 'id) t -> ('v -> 'v2) -> ('k, 'v2, 'id) t ``` `map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapWithKeyU : ('k, 'v, 'id) t -> @@ -363,18 +428,24 @@ val mapWithKeyU : val mapWithKey : ('k, 'v, 'id) t -> ('k -> 'v -> 'v2) -> ('k, 'v2, 'id) t ``` `mapWithKey m f` + The same as [`map`](./#val-map) except that `f` is supplied with one more argument: the key + ``` val getData : ('k, 'v, 'id) t -> ('k, 'v, 'id) Belt__.Belt_MapDict.t ``` `getData s0` + **Advanced usage only** + returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing ``` val getId : ('k, 'v, 'id) t -> ('k, 'id) id ``` `getId s0` + **Advanced usage only** + returns the identity of s0 ``` val packIdData : @@ -383,5 +454,7 @@ val packIdData : ('k, 'v, 'id) t ``` `packIdData ~id ~data` + **Advanced usage only** + returns the packed collection \ No newline at end of file diff --git a/docs/api/melange/Belt-MutableMap-Int.md b/docs/api/melange/Belt-MutableMap-Int.md index 290569dea..09b46fa13 100644 --- a/docs/api/melange/Belt-MutableMap-Int.md +++ b/docs/api/melange/Belt-MutableMap-Int.md @@ -1,4 +1,6 @@ + # Module `MutableMap.Int` + ``` type key = int ``` @@ -24,6 +26,7 @@ val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int ``` `cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair + ``` val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -31,6 +34,7 @@ val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool ``` `eq m1 m2 cmp` + ``` val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit ``` @@ -38,6 +42,7 @@ val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit val forEach : 'a t -> (key -> 'a -> unit) -> unit ``` `forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. + ``` val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b ``` @@ -45,6 +50,7 @@ val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b ``` `reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + ``` val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -52,6 +58,7 @@ val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool val every : 'a t -> (key -> 'a -> bool) -> bool ``` `every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. + ``` val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -59,6 +66,7 @@ val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool val some : 'a t -> (key -> 'a -> bool) -> bool ``` `some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. + ``` val size : 'a t -> int ``` @@ -66,10 +74,12 @@ val size : 'a t -> int val toList : 'a t -> (key * 'a) list ``` In increasing order + ``` val toArray : 'a t -> (key * 'a) array ``` In increasing order + ``` val fromArray : (key * 'a) array -> 'a t ``` @@ -119,10 +129,12 @@ val getExn : 'a t -> key -> 'a val checkInvariantInternal : _ t -> unit ``` **raise** when invariant is not held + ``` val remove : 'a t -> key -> unit ``` `remove m x` do the in-place modification + ``` val removeMany : 'a t -> key array -> unit ``` @@ -130,6 +142,7 @@ val removeMany : 'a t -> key array -> unit val set : 'a t -> key -> 'a -> unit ``` `set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. + ``` val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit ``` @@ -143,6 +156,7 @@ val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t val map : 'a t -> ('a -> 'b) -> 'b t ``` `map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t ``` diff --git a/docs/api/melange/Belt-MutableMap-String.md b/docs/api/melange/Belt-MutableMap-String.md index 8462f026b..8743e1b84 100644 --- a/docs/api/melange/Belt-MutableMap-String.md +++ b/docs/api/melange/Belt-MutableMap-String.md @@ -1,4 +1,6 @@ + # Module `MutableMap.String` + ``` type key = string ``` @@ -24,6 +26,7 @@ val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int ``` `cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair + ``` val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -31,6 +34,7 @@ val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool ``` `eq m1 m2 cmp` + ``` val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit ``` @@ -38,6 +42,7 @@ val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit val forEach : 'a t -> (key -> 'a -> unit) -> unit ``` `forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. + ``` val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b ``` @@ -45,6 +50,7 @@ val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b ``` `reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + ``` val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -52,6 +58,7 @@ val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool val every : 'a t -> (key -> 'a -> bool) -> bool ``` `every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. + ``` val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -59,6 +66,7 @@ val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool val some : 'a t -> (key -> 'a -> bool) -> bool ``` `some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. + ``` val size : 'a t -> int ``` @@ -66,10 +74,12 @@ val size : 'a t -> int val toList : 'a t -> (key * 'a) list ``` In increasing order + ``` val toArray : 'a t -> (key * 'a) array ``` In increasing order + ``` val fromArray : (key * 'a) array -> 'a t ``` @@ -119,10 +129,12 @@ val getExn : 'a t -> key -> 'a val checkInvariantInternal : _ t -> unit ``` **raise** when invariant is not held + ``` val remove : 'a t -> key -> unit ``` `remove m x` do the in-place modification + ``` val removeMany : 'a t -> key array -> unit ``` @@ -130,6 +142,7 @@ val removeMany : 'a t -> key array -> unit val set : 'a t -> key -> 'a -> unit ``` `set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. + ``` val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit ``` @@ -143,6 +156,7 @@ val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t val map : 'a t -> ('a -> 'b) -> 'b t ``` `map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t ``` diff --git a/docs/api/melange/Belt-MutableMap.md b/docs/api/melange/Belt-MutableMap.md index ab3a5dfd6..cf079ddd2 100644 --- a/docs/api/melange/Belt-MutableMap.md +++ b/docs/api/melange/Belt-MutableMap.md @@ -1,7 +1,12 @@ + # Module `Belt.MutableMap` + [`Belt.MutableMap`](#) + The top level provides generic **mutable** map operations. + It also has two specialized inner modules [`Belt.MutableMap.Int`](./Belt-MutableMap-Int.md) and [`Belt.MutableMap.String`](./Belt-MutableMap-String.md) + ``` module Int : sig ... end ``` @@ -9,7 +14,9 @@ module Int : sig ... end module String : sig ... end ``` A **mutable** sorted map module which allows customize *compare* behavior. + Same as Belt.Map, but mutable. + ``` type ('k, 'v, 'id) t ``` @@ -42,6 +49,7 @@ val cmpU : val cmp : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> int) -> int ``` `cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair + ``` val eqU : ('k, 'a, 'id) t -> @@ -53,6 +61,7 @@ val eqU : val eq : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> bool) -> bool ``` `eq m1 m2 eqf` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `eqf` is the equality predicate used to compare the data associated with the keys. + ``` val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit ``` @@ -60,6 +69,7 @@ val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit ``` `forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val reduceU : ('k, 'a, 'id) t -> @@ -71,6 +81,7 @@ val reduceU : val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b ``` `reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + ``` val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -78,6 +89,7 @@ val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool ``` `every m p` checks if all the bindings of the map satisfy the predicate `p`. + ``` val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool ``` @@ -85,6 +97,7 @@ val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool ``` `some m p` checks if at least one binding of the map satisfy the predicate `p`. + ``` val size : ('k, 'a, 'id) t -> int ``` @@ -92,10 +105,12 @@ val size : ('k, 'a, 'id) t -> int val toList : ('k, 'a, 'id) t -> ('k * 'a) list ``` In increasing order + ``` val toArray : ('k, 'a, 'id) t -> ('k * 'a) array ``` In increasing order + ``` val fromArray : ('k * 'a) array -> id:('k, 'id) id -> ('k, 'a, 'id) t ``` @@ -145,10 +160,12 @@ val getExn : ('k, 'a, 'id) t -> 'k -> 'a val checkInvariantInternal : (_, _, _) t -> unit ``` **raise** when invariant is not held + ``` val remove : ('k, 'a, 'id) t -> 'k -> unit ``` `remove m x` do the in-place modification, + ``` val removeMany : ('k, 'a, 'id) t -> 'k array -> unit ``` @@ -156,6 +173,7 @@ val removeMany : ('k, 'a, 'id) t -> 'k array -> unit val set : ('k, 'a, 'id) t -> 'k -> 'a -> unit ``` `set m x y ` do the in-place modification + ``` val updateU : ('k, 'a, 'id) t -> @@ -176,6 +194,7 @@ val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t ``` `map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapWithKeyU : ('k, 'a, 'id) t -> diff --git a/docs/api/melange/Belt-MutableQueue.md b/docs/api/melange/Belt-MutableQueue.md index 4fa2ddaac..fcb94e0a5 100644 --- a/docs/api/melange/Belt-MutableQueue.md +++ b/docs/api/melange/Belt-MutableQueue.md @@ -1,12 +1,19 @@ + # Module `Belt.MutableQueue` + [`Belt.MutableQueue`](#) + An FIFO(first in first out) queue data structure + First-in first-out queues. + This module implements queues (FIFOs), with in-place modification. + ``` type 'a t ``` The type of queues containing elements of type `'a`. + ``` val make : unit -> 'a t ``` @@ -15,6 +22,7 @@ returns a new queue, initially empty. val clear : 'a t -> unit ``` Discard all elements from the queue. + ``` val isEmpty : 'a t -> bool ``` @@ -23,40 +31,51 @@ returns true if the given queue is empty, false otherwise. val fromArray : 'a array -> 'a t ``` `fromArray a` is equivalent to `Array.forEach a (add q a)` + ``` val add : 'a t -> 'a -> unit ``` `add q x` adds the element `x` at the end of the queue `q`. + ``` val peek : 'a t -> 'a option ``` `peekOpt q` returns the first element in queue `q`, without removing it from the queue. + ``` val peekUndefined : 'a t -> 'a Js.undefined ``` `peekUndefined q` returns `undefined` if not found + ``` val peekExn : 'a t -> 'a ``` `peekExn q` + **raise** an exception if `q` is empty + ``` val pop : 'a t -> 'a option ``` `pop q` removes and returns the first element in queue `q`. + ``` val popUndefined : 'a t -> 'a Js.undefined ``` `popUndefined q` removes and returns the first element in queue `q`. it will return undefined if it is already empty + ``` val popExn : 'a t -> 'a ``` `popExn q` + **raise** an exception if `q` is empty + ``` val copy : 'a t -> 'a t ``` `copy q` + returns a fresh queue ``` val size : 'a t -> int @@ -75,6 +94,7 @@ val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit val forEach : 'a t -> ('a -> unit) -> unit ``` `forEach q f` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. + ``` val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b ``` @@ -82,11 +102,13 @@ val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b ``` `reduce q accu f` is equivalent to `List.reduce l accu f`, where `l` is the list of `q`'s elements. The queue remains unchanged. + ``` val transfer : 'a t -> 'a t -> unit ``` `transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `forEach (fun x -> add x q2) q1; clear q1`, but runs in constant time. + ``` val toArray : 'a t -> 'a array ``` -First added will be in the beginning of the array \ No newline at end of file +First added will be in the beginning of the array diff --git a/docs/api/melange/Belt-MutableSet-Int.md b/docs/api/melange/Belt-MutableSet-Int.md index 0c2a24edd..5c5d225e5 100644 --- a/docs/api/melange/Belt-MutableSet-Int.md +++ b/docs/api/melange/Belt-MutableSet-Int.md @@ -1,16 +1,24 @@ + # Module `MutableSet.Int` + Specalized when key type is `int`, more efficient than the generic type + This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. + It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + **See** [`Belt.MutableSet`](./Belt-MutableSet.md) + ``` type value = int ``` The type of the set elements. + ``` type t ``` The type of sets. + ``` val make : unit -> t ``` @@ -72,6 +80,7 @@ val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit val forEach : t -> (value -> unit) -> unit ``` In increasing order + ``` val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a ``` @@ -79,6 +88,7 @@ val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a ``` Iterate in increasing order. + ``` val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -86,6 +96,7 @@ val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool val every : t -> (value -> bool) -> bool ``` `every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + ``` val someU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -93,6 +104,7 @@ val someU : t -> (value -> bool) Js.Fn.arity1 -> bool val some : t -> (value -> bool) -> bool ``` `some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + ``` val keepU : t -> (value -> bool) Js.Fn.arity1 -> t ``` @@ -100,6 +112,7 @@ val keepU : t -> (value -> bool) Js.Fn.arity1 -> t val keep : t -> (value -> bool) -> t ``` `keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. + ``` val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t ``` @@ -107,6 +120,7 @@ val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t val partition : t -> (value -> bool) -> t * t ``` `partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + ``` val size : t -> int ``` @@ -114,10 +128,12 @@ val size : t -> int val toList : t -> value list ``` In increasing order with respect + ``` val toArray : t -> value array ``` In increasing order with respect + ``` val minimum : t -> value option ``` @@ -143,7 +159,8 @@ val getExn : t -> value -> value val split : t -> value -> (t * t) * bool ``` `split s key` return a fresh copy of each + ``` val checkInvariantInternal : t -> unit ``` -**raise** when invariant is not held \ No newline at end of file +**raise** when invariant is not held diff --git a/docs/api/melange/Belt-MutableSet-String.md b/docs/api/melange/Belt-MutableSet-String.md index 2782f17a9..df5e825f6 100644 --- a/docs/api/melange/Belt-MutableSet-String.md +++ b/docs/api/melange/Belt-MutableSet-String.md @@ -1,16 +1,24 @@ + # Module `MutableSet.String` + Specalized when key type is `string`, more efficient than the generic type + This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. + It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + **See** [`Belt.MutableSet`](./Belt-MutableSet.md) + ``` type value = string ``` The type of the set elements. + ``` type t ``` The type of sets. + ``` val make : unit -> t ``` @@ -72,6 +80,7 @@ val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit val forEach : t -> (value -> unit) -> unit ``` In increasing order + ``` val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a ``` @@ -79,6 +88,7 @@ val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a ``` Iterate in increasing order. + ``` val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -86,6 +96,7 @@ val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool val every : t -> (value -> bool) -> bool ``` `every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + ``` val someU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -93,6 +104,7 @@ val someU : t -> (value -> bool) Js.Fn.arity1 -> bool val some : t -> (value -> bool) -> bool ``` `some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + ``` val keepU : t -> (value -> bool) Js.Fn.arity1 -> t ``` @@ -100,6 +112,7 @@ val keepU : t -> (value -> bool) Js.Fn.arity1 -> t val keep : t -> (value -> bool) -> t ``` `keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. + ``` val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t ``` @@ -107,6 +120,7 @@ val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t val partition : t -> (value -> bool) -> t * t ``` `partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + ``` val size : t -> int ``` @@ -114,10 +128,12 @@ val size : t -> int val toList : t -> value list ``` In increasing order with respect + ``` val toArray : t -> value array ``` In increasing order with respect + ``` val minimum : t -> value option ``` @@ -143,7 +159,8 @@ val getExn : t -> value -> value val split : t -> value -> (t * t) * bool ``` `split s key` return a fresh copy of each + ``` val checkInvariantInternal : t -> unit ``` -**raise** when invariant is not held \ No newline at end of file +**raise** when invariant is not held diff --git a/docs/api/melange/Belt-MutableSet.md b/docs/api/melange/Belt-MutableSet.md index 3c76a34cc..ab101f1c9 100644 --- a/docs/api/melange/Belt-MutableSet.md +++ b/docs/api/melange/Belt-MutableSet.md @@ -1,17 +1,26 @@ + # Module `Belt.MutableSet` + [`Belt.MutableSet`](#) + The top level provides generic **mutable** set operations. + It also has two specialized inner modules [`Belt.MutableSet.Int`](./Belt-MutableSet-Int.md) and [`Belt.MutableSet.String`](./Belt-MutableSet-String.md) + A *mutable* sorted set module which allows customize *compare* behavior. + Same as Belt.Set, but mutable. + ``` module Int : sig ... end ``` Specalized when key type is `int`, more efficient than the generic type + ``` module String : sig ... end ``` Specalized when key type is `string`, more efficient than the generic type + ``` type ('k, 'id) t ``` @@ -85,6 +94,7 @@ val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit val forEach : ('value, 'id) t -> ('value -> unit) -> unit ``` `forEach m f` applies `f` in turn to all elements of `m`. In increasing order + ``` val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a ``` @@ -92,6 +102,7 @@ val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a ``` In increasing order. + ``` val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool ``` @@ -99,6 +110,7 @@ val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool val every : ('value, 'id) t -> ('value -> bool) -> bool ``` `every s p` checks if all elements of the set satisfy the predicate `p`. Order unspecified + ``` val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool ``` @@ -106,6 +118,7 @@ val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool val some : ('value, 'id) t -> ('value -> bool) -> bool ``` `some p s` checks if at least one element of the set satisfies the predicate `p`. + ``` val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t ``` @@ -113,6 +126,7 @@ val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t ``` `keep s p` returns the set of all elements in `s` that satisfy predicate `p`. + ``` val partitionU : ('value, 'id) t -> @@ -126,6 +140,7 @@ val partition : ('value, 'id) t * ('value, 'id) t ``` `partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + ``` val size : ('value, 'id) t -> int ``` @@ -133,10 +148,12 @@ val size : ('value, 'id) t -> int val toList : ('value, 'id) t -> 'value list ``` In increasing order + ``` val toArray : ('value, 'id) t -> 'value array ``` In increasing order + ``` val minimum : ('value, 'id) t -> 'value option ``` @@ -165,7 +182,8 @@ val split : (('value, 'id) t * ('value, 'id) t) * bool ``` `split s x` returns a triple `((l, r), present)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. `l,r` are freshly made, no sharing with `s` + ``` val checkInvariantInternal : (_, _) t -> unit ``` -**raise** when invariant is not held \ No newline at end of file +**raise** when invariant is not held diff --git a/docs/api/melange/Belt-MutableStack.md b/docs/api/melange/Belt-MutableStack.md index a40dcaf0c..291f3caa3 100644 --- a/docs/api/melange/Belt-MutableStack.md +++ b/docs/api/melange/Belt-MutableStack.md @@ -1,8 +1,14 @@ + # Module `Belt.MutableStack` + [`Belt.MutableStack`](#) + An FILO(first in last out) stack data structure + First in last out stack. + This module implements stacks, with in-place modification. + ``` type 'a t ``` @@ -14,10 +20,12 @@ returns a new stack, initially empty. val clear : 'a t -> unit ``` Discard all elements from the stack. + ``` val copy : 'a t -> 'a t ``` `copy x` O(1) operation, return a new stack + ``` val push : 'a t -> 'a -> unit ``` @@ -51,4 +59,4 @@ val dynamicPopIterU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit ``` val dynamicPopIter : 'a t -> ('a -> unit) -> unit ``` -`dynamicPopIter s f ` apply `f` to each element of `s`. The item is poped before applying `f`, `s` will be empty after this opeartion. This function is useful for worklist algorithm \ No newline at end of file +`dynamicPopIter s f ` apply `f` to each element of `s`. The item is poped before applying `f`, `s` will be empty after this opeartion. This function is useful for worklist algorithm diff --git a/docs/api/melange/Belt-Option.md b/docs/api/melange/Belt-Option.md index 2fd13b0d9..a13563de7 100644 --- a/docs/api/melange/Belt-Option.md +++ b/docs/api/melange/Belt-Option.md @@ -1,17 +1,26 @@ + # Module `Belt.Option` + [`Belt.Option`](#) + Utilities for option data type. + [`Belt.Option`](#) + Utilities for option data type + ``` val keepU : 'a option -> ('a -> bool) Js.Fn.arity1 -> 'a option ``` Uncurried version of `keep` + ``` val keep : 'a option -> ('a -> bool) -> 'a option ``` `keep optionValue p` + If `optionValue` is `Some value` and `p value = true`, it returns `Some value`; otherwise returns `None` + ```ocaml keep (Some 10)(fun x -> x > 5);; (* returns [Some 10] *) keep (Some 4)(fun x -> x > 5);; (* returns [None] *) @@ -21,11 +30,14 @@ If `optionValue` is `Some value` and `p value = true`, it returns `Some value`; val forEachU : 'a option -> ('a -> unit) Js.Fn.arity1 -> unit ``` Uncurried version of `forEach` + ``` val forEach : 'a option -> ('a -> unit) -> unit ``` `forEach optionValue f` + If `optionValue` is `Some value`, it calls `f value`; otherwise returns `()` + ```ocaml forEach (Some "thing")(fun x -> Js.log x);; (* logs "thing" *) forEach None (fun x -> Js.log x);; (* returns () *) @@ -34,6 +46,7 @@ If `optionValue` is `Some value`, it calls `f value`; otherwise returns `()` val getExn : 'a option -> 'a ``` `getExn optionalValue` Returns `value` if `optionalValue` is `Some value`, otherwise raises `getExn` + ```ocaml getExn (Some 3) = 3;; getExn None (* Raises getExn error *) @@ -42,15 +55,19 @@ val getExn : 'a option -> 'a val getUnsafe : 'a option -> 'a ``` `getUnsafe x` returns x This is an unsafe operation, it assumes x is neither not None or (Some (None .. )) + ``` val mapWithDefaultU : 'a option -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b ``` Uncurried version of `mapWithDefault` + ``` val mapWithDefault : 'a option -> 'b -> ('a -> 'b) -> 'b ``` `mapWithDefault optionValue default f` + If `optionValue` is `Some value`, returns `f value`; otherwise returns `default` + ```ocaml mapWithDefault (Some 3) 0 (fun x -> x + 5) = 8;; mapWithDefault None 0 (fun x -> x + 5) = 0;; @@ -59,11 +76,14 @@ If `optionValue` is `Some value`, returns `f value`; otherwise returns `default` val mapU : 'a option -> ('a -> 'b) Js.Fn.arity1 -> 'b option ``` Uncurried version of `map` + ``` val map : 'a option -> ('a -> 'b) -> 'b option ``` `map optionValue f` + If `optionValue` is `Some value`, returns `Some (f value)`; otherwise returns `None` + ```ocaml map (Some 3) (fun x -> x * x) = (Some 9);; map None (fun x -> x * x) = None;; @@ -72,11 +92,14 @@ If `optionValue` is `Some value`, returns `Some (f value)`; otherwise returns `N val flatMapU : 'a option -> ('a -> 'b option) Js.Fn.arity1 -> 'b option ``` Uncurried version of `flatMap` + ``` val flatMap : 'a option -> ('a -> 'b option) -> 'b option ``` `flatMap optionValue f` + If `optionValue` is `Some value`, returns `f value`; otherwise returns `None` The function `f` must have a return type of `'a option` + ```ocaml let f (x : float) = if x >= 0.0 then @@ -92,7 +115,9 @@ If `optionValue` is `Some value`, returns `f value`; otherwise returns `None` Th val getWithDefault : 'a option -> 'a -> 'a ``` `getWithDefault optionalValue default` + If `optionalValue` is `Some value`, returns `value`, otherwise `default` + ```ocaml getWithDefault (Some 1812) 1066 = 1812;; getWithDefault None 1066 = 1066;; @@ -101,7 +126,9 @@ If `optionalValue` is `Some value`, returns `value`, otherwise `default` val orElse : 'a option -> 'a option -> 'a option ``` `orElse optionalValue otherOptional` + If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOptional` + ```ocaml orElse (Some 1812) (Some 1066) = Some 1812;; orElse None (Some 1066) = Some 1066;; @@ -111,22 +138,30 @@ If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOption val isSome : 'a option -> bool ``` Returns `true` if the argument is `Some value`, `false` otherwise + ``` val isNone : 'a option -> bool ``` Returns `true` if the argument is `None`, `false` otherwise + ``` val eqU : 'a option -> 'b option -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool ``` Uncurried version of `eq` + ``` val eq : 'a option -> 'b option -> ('a -> 'b -> bool) -> bool ``` `eq optValue1 optvalue2 predicate` + Evaluates two optional values for equality with respect to a predicate function. + If both `optValue1` and `optValue2` are `None`, returns `true`. + If one of the arguments is `Some value` and the other is `None`, returns `false` + If arguments are `Some value1` and `Some value2`, returns the result of `predicate value1 value2`; the `predicate` function must return a `bool` + ```ocaml let clockEqual = (fun a b -> a mod 12 = b mod 12);; eq (Some 3) (Some 15) clockEqual = true;; @@ -138,15 +173,22 @@ If arguments are `Some value1` and `Some value2`, returns the result of `predica val cmpU : 'a option -> 'b option -> ('a -> 'b -> int) Js.Fn.arity2 -> int ``` Uncurried version of `cmp` + ``` val cmp : 'a option -> 'b option -> ('a -> 'b -> int) -> int ``` `cmp optValue1 optvalue2 comparisonFcn` + Compares two optional values with respect to a comparison function + If both `optValue1` and `optValue2` are `None`, returns 0. + If the first argument is `Some value1` and the second is `None`, returns 1 (something is greater than nothing) + If the first argument is `None` and the second is `Some value2`, returns \-1 (nothing is less than something) + If the arguments are `Some value1` and `Some value2`, returns the result of `comparisonFcn value1 value2`; `comparisonFcn` takes two arguments and returns \-1 if the first argument is less than the second, 0 if the arguments are equal, and 1 if the first argument is greater than the second. + ```ocaml let clockCompare = fun a b -> compare (a mod 12) (b mod 12);; cmp (Some 3) (Some 15) clockCompare = 0;; diff --git a/docs/api/melange/Belt-Range.md b/docs/api/melange/Belt-Range.md index d9f449398..fabb4625e 100644 --- a/docs/api/melange/Belt-Range.md +++ b/docs/api/melange/Belt-Range.md @@ -1,7 +1,12 @@ + # Module `Belt.Range` + [`Belt.Range`](#) + Utilities for a closed range `(from, start)` + A small module to provide a inclusive range operations `[start, finsish]`, it use a for-loop internally instead of creating an array + ``` val forEachU : int -> int -> (int -> unit) Js.Fn.arity1 -> unit ``` @@ -9,7 +14,9 @@ val forEachU : int -> int -> (int -> unit) Js.Fn.arity1 -> unit val forEach : int -> int -> (int -> unit) -> unit ``` `forEach start finish action` + equivalent to `Belt.Array.(forEach (range start finish) action)` + ``` val everyU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool ``` @@ -17,7 +24,9 @@ val everyU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool val every : int -> int -> (int -> bool) -> bool ``` `every start finish p` + equivalent to `Belt.Array.(every (range start finish) p )` + ``` val everyByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool ``` @@ -25,8 +34,11 @@ val everyByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool val everyBy : int -> int -> step:int -> (int -> bool) -> bool ``` `everyBy start finish ~step p` + **See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) + equivalent to `Belt.Array.(every (rangeBy start finish ~step) p)` + ``` val someU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool ``` @@ -34,7 +46,9 @@ val someU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool val some : int -> int -> (int -> bool) -> bool ``` `some start finish p` + equivalent to `Belt.Array.(some (range start finish) p)` + ``` val someByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool ``` @@ -42,5 +56,7 @@ val someByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool val someBy : int -> int -> step:int -> (int -> bool) -> bool ``` `someBy start finish ~step p` + **See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) -equivalent to `Belt.Array.(some (rangeBy start finish ~step) p)` \ No newline at end of file + +equivalent to `Belt.Array.(some (rangeBy start finish ~step) p)` diff --git a/docs/api/melange/Belt-Result.md b/docs/api/melange/Belt-Result.md index 8ac52a7b6..093023ba0 100644 --- a/docs/api/melange/Belt-Result.md +++ b/docs/api/melange/Belt-Result.md @@ -1,8 +1,14 @@ + # Module `Belt.Result` + [`Belt.Result`](#) + Utilities for result data type. + `Belt.Result` is a data type with two variants: `Ok` and `Error`. Each of these variants can contain data, and those two pieces of data need not have the same data type. `Belt.Result` is useful when you need to not only determine whether some data is valid or not (use `Belt.Option` for that), but also keep information about the invalid data. + In the examples, we presume the existence of two variables: + ```ocaml let good = Ok 42 let bad = Error "Invalid data" @@ -23,7 +29,9 @@ type ('a, 'b) t = ('a, 'b) result = val getExn : ('a, 'b) t -> 'a ``` `getExn res` + when `res` is `Ok n`, returns `n` when `res` is `Error m`, **raise** an exception + ```ocaml getExn good = 42;; getExn bad;; (* raises exception *) @@ -35,7 +43,9 @@ val mapWithDefaultU : ('a, 'c) t -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b val mapWithDefault : ('a, 'c) t -> 'b -> ('a -> 'b) -> 'b ``` `mapWithDefault res default f` + When `res` is `Ok n`, returns `f n`, otherwise `default`. + ```ocaml mapWithDefault good 0 (fun x -> x / 2) = 21 mapWithDefault bad 0 (fun x -> x / 2) = 0 @@ -47,7 +57,9 @@ val mapU : ('a, 'c) t -> ('a -> 'b) Js.Fn.arity1 -> ('b, 'c) t val map : ('a, 'c) t -> ('a -> 'b) -> ('b, 'c) t ``` `map res f` + When `res` is `Ok n`, returns `Ok (f n)`. Otherwise returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns an ordinary value. + ```ocaml let f x = sqrt (float_of_int x) map (Ok 64) f = Ok 8.0 @@ -60,7 +72,9 @@ val flatMapU : ('a, 'c) t -> ('a -> ('b, 'c) t) Js.Fn.arity1 -> ('b, 'c) t val flatMap : ('a, 'c) t -> ('a -> ('b, 'c) t) -> ('b, 'c) t ``` `flatMap res f` + When `res` is `Ok n`, returns `f n`. Otherwise, returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns a `Belt.Result`. + ```ocaml let recip x = if x != 0.0 @@ -77,7 +91,9 @@ let recip x = val getWithDefault : ('a, 'b) t -> 'a -> 'a ``` `getWithDefault res defaultValue` + if `res` is `Ok n`, returns `n`, otherwise `default` + ```ocaml getWithDefault (Ok 42) 0 = 42 getWithDefault (Error "Invalid Data") = 0 @@ -86,12 +102,16 @@ if `res` is `Ok n`, returns `n`, otherwise `default` val isOk : ('a, 'b) t -> bool ``` `isOk res` + Returns `true` if `res` is of the form `Ok n`, `false` if it is the `Error e` variant. + ``` val isError : ('a, 'b) t -> bool ``` `isError res` + Returns `true` if `res` is of the form `Error e`, `false` if it is the `Ok n` variant. + ``` val eqU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool ``` @@ -99,7 +119,9 @@ val eqU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool val eq : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) -> bool ``` `eq res1 res2 f` + Determine if two `Belt.Result` variables are equal with respect to an equality function. If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If one of `res1` and `res2` are of the form `Error e`, return false If both `res1` and `res2` are of the form `Error e`, return true + ```ocaml let good1 = Ok 42 let good2 = Ok 32 @@ -121,8 +143,11 @@ val cmpU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) Js.Fn.arity2 -> int val cmp : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) -> int ``` `cmp res1 res2 f` + Compare two `Belt.Result` variables with respect to a comparison function. The comparison function returns \-1 if the first variable is "less than" the second, 0 if the two variables are equal, and 1 if the first is "greater than" the second. + If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If `res1` is of the form `Error e` and `res2` of the form `Ok n`, return \-1 (nothing is less than something) If `res1` is of the form `Ok n` and `res2` of the form `Error e`, return 1 (something is greater than nothing) If both `res1` and `res2` are of the form `Error e`, return 0 (equal) + ```ocaml let good1 = Ok 59 let good2 = Ok 37 diff --git a/docs/api/melange/Belt-Set-Dict.md b/docs/api/melange/Belt-Set-Dict.md index 24342585f..249bfc951 100644 --- a/docs/api/melange/Belt-Set-Dict.md +++ b/docs/api/melange/Belt-Set-Dict.md @@ -1,5 +1,8 @@ + # Module `Set.Dict` + This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + ``` type ('value, 'identity) t ``` @@ -25,6 +28,7 @@ val has : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> bool val add : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> ('value, 'id) t ``` `add s x` If `x` was already in `s`, `s` is returned unchanged. + ``` val mergeMany : ('value, 'id) t -> @@ -40,6 +44,7 @@ val remove : ('value, 'id) t ``` `remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + ``` val removeMany : ('value, 'id) t -> @@ -76,14 +81,17 @@ val subset : bool ``` `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + ``` val cmp : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. + ``` val eq : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> bool ``` `eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + ``` val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit ``` @@ -91,6 +99,7 @@ val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit val forEach : ('value, 'id) t -> ('value -> unit) -> unit ``` `forEach s f` applies `f` in turn to all elements of `s`. In increasing order + ``` val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a ``` @@ -98,6 +107,7 @@ val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a ``` Iterate in increasing order. + ``` val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool ``` @@ -105,6 +115,7 @@ val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool val every : ('value, 'id) t -> ('value -> bool) -> bool ``` `every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + ``` val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool ``` @@ -112,6 +123,7 @@ val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool val some : ('value, 'id) t -> ('value -> bool) -> bool ``` `some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + ``` val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t ``` @@ -119,6 +131,7 @@ val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t ``` `keep p s` returns the set of all elements in `s` that satisfy predicate `p`. + ``` val partitionU : ('value, 'id) t -> @@ -132,6 +145,7 @@ val partition : ('value, 'id) t * ('value, 'id) t ``` `partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + ``` val size : ('value, 'id) t -> int ``` @@ -139,6 +153,7 @@ val size : ('value, 'id) t -> int val toList : ('value, 'id) t -> 'value list ``` In increasing order + ``` val toArray : ('value, 'id) t -> 'value array ``` @@ -175,7 +190,8 @@ val split : (('value, 'id) t * ('value, 'id) t) * bool ``` `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + ``` val checkInvariantInternal : (_, _) t -> unit ``` -**raise** when invariant is not held \ No newline at end of file +**raise** when invariant is not held diff --git a/docs/api/melange/Belt-Set-Int.md b/docs/api/melange/Belt-Set-Int.md index 4c8f6f545..697d28cf4 100644 --- a/docs/api/melange/Belt-Set-Int.md +++ b/docs/api/melange/Belt-Set-Int.md @@ -1,15 +1,22 @@ + # Module `Set.Int` + Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) + **See** [`Belt.Set`](./Belt-Set.md) + ``` type value = int ``` The type of the set elements. + ``` type t ``` The type of sets. + ``` val empty : t ``` @@ -29,6 +36,7 @@ val has : t -> value -> bool val add : t -> value -> t ``` `add s x` If `x` was already in `s`, `s` is returned unchanged. + ``` val mergeMany : t -> value array -> t ``` @@ -36,6 +44,7 @@ val mergeMany : t -> value array -> t val remove : t -> value -> t ``` `remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + ``` val removeMany : t -> value array -> t ``` @@ -52,14 +61,17 @@ val diff : t -> t -> t val subset : t -> t -> bool ``` `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + ``` val cmp : t -> t -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. + ``` val eq : t -> t -> bool ``` `eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + ``` val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit ``` @@ -67,6 +79,7 @@ val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit val forEach : t -> (value -> unit) -> unit ``` `forEach s f` applies `f` in turn to all elements of `s`. In increasing order + ``` val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a ``` @@ -74,6 +87,7 @@ val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a ``` Iterate in increasing order. + ``` val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -81,6 +95,7 @@ val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool val every : t -> (value -> bool) -> bool ``` `every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + ``` val someU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -88,6 +103,7 @@ val someU : t -> (value -> bool) Js.Fn.arity1 -> bool val some : t -> (value -> bool) -> bool ``` `some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + ``` val keepU : t -> (value -> bool) Js.Fn.arity1 -> t ``` @@ -95,6 +111,7 @@ val keepU : t -> (value -> bool) Js.Fn.arity1 -> t val keep : t -> (value -> bool) -> t ``` `keep p s` returns the set of all elements in `s` that satisfy predicate `p`. + ``` val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t ``` @@ -102,6 +119,7 @@ val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t val partition : t -> (value -> bool) -> t * t ``` `partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + ``` val size : t -> int ``` @@ -109,6 +127,7 @@ val size : t -> int val toList : t -> value list ``` In increasing order + ``` val toArray : t -> value array ``` @@ -137,7 +156,8 @@ val getExn : t -> value -> value val split : t -> value -> (t * t) * bool ``` `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + ``` val checkInvariantInternal : t -> unit ``` -**raise** when invariant is not held \ No newline at end of file +**raise** when invariant is not held diff --git a/docs/api/melange/Belt-Set-String.md b/docs/api/melange/Belt-Set-String.md index 2b2206c01..cd17e0b37 100644 --- a/docs/api/melange/Belt-Set-String.md +++ b/docs/api/melange/Belt-Set-String.md @@ -1,15 +1,22 @@ + # Module `Set.String` + Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) + **See** [`Belt.Set`](./Belt-Set.md) + ``` type value = string ``` The type of the set elements. + ``` type t ``` The type of sets. + ``` val empty : t ``` @@ -29,6 +36,7 @@ val has : t -> value -> bool val add : t -> value -> t ``` `add s x` If `x` was already in `s`, `s` is returned unchanged. + ``` val mergeMany : t -> value array -> t ``` @@ -36,6 +44,7 @@ val mergeMany : t -> value array -> t val remove : t -> value -> t ``` `remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + ``` val removeMany : t -> value array -> t ``` @@ -52,14 +61,17 @@ val diff : t -> t -> t val subset : t -> t -> bool ``` `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + ``` val cmp : t -> t -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. + ``` val eq : t -> t -> bool ``` `eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + ``` val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit ``` @@ -67,6 +79,7 @@ val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit val forEach : t -> (value -> unit) -> unit ``` `forEach s f` applies `f` in turn to all elements of `s`. In increasing order + ``` val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a ``` @@ -74,6 +87,7 @@ val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a ``` Iterate in increasing order. + ``` val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -81,6 +95,7 @@ val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool val every : t -> (value -> bool) -> bool ``` `every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + ``` val someU : t -> (value -> bool) Js.Fn.arity1 -> bool ``` @@ -88,6 +103,7 @@ val someU : t -> (value -> bool) Js.Fn.arity1 -> bool val some : t -> (value -> bool) -> bool ``` `some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + ``` val keepU : t -> (value -> bool) Js.Fn.arity1 -> t ``` @@ -95,6 +111,7 @@ val keepU : t -> (value -> bool) Js.Fn.arity1 -> t val keep : t -> (value -> bool) -> t ``` `keep p s` returns the set of all elements in `s` that satisfy predicate `p`. + ``` val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t ``` @@ -102,6 +119,7 @@ val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t val partition : t -> (value -> bool) -> t * t ``` `partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + ``` val size : t -> int ``` @@ -109,6 +127,7 @@ val size : t -> int val toList : t -> value list ``` In increasing order + ``` val toArray : t -> value array ``` @@ -137,7 +156,8 @@ val getExn : t -> value -> value val split : t -> value -> (t * t) * bool ``` `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + ``` val checkInvariantInternal : t -> unit ``` -**raise** when invariant is not held \ No newline at end of file +**raise** when invariant is not held diff --git a/docs/api/melange/Belt-Set.md b/docs/api/melange/Belt-Set.md index 12aec7e95..d923eb6f2 100644 --- a/docs/api/melange/Belt-Set.md +++ b/docs/api/melange/Belt-Set.md @@ -1,12 +1,22 @@ + # Module `Belt.Set` + [`Belt.Set`](#) + The top level provides generic **immutable** set operations. + It also has three specialized inner modules [`Belt.Set.Int`](./Belt-Set-Int.md), [`Belt.Set.String`](./Belt-Set-String.md) and + [`Belt.Set.Dict`](./Belt-Set-Dict.md): This module separates data from function which is more verbose but slightly more efficient + A *immutable* sorted set module which allows customize *compare* behavior. + The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. + Example usage: + ```ocaml module PairComparator = Belt.Id.MakeComparable(struct type t = int * int @@ -20,24 +30,31 @@ Example usage: let mySet2 = Belt.Set.add mySet (1, 2) ``` The API documentation below will assume a predeclared comparator module for integers, IntCmp + ``` module Int : sig ... end ``` Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + ``` module String : sig ... end ``` Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + ``` module Dict : sig ... end ``` This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + ``` type ('value, 'identity) t ``` `('value, 'identity) t` + `'value` is the element type + `'identity` the identity of the collection + ``` type ('value, 'id) id = (module Belt__.Belt_Id.Comparable @@ -45,10 +62,12 @@ type ('value, 'id) id = and type t = 'value) ``` The identity needed for making a set from scratch + ``` val make : id:('value, 'id) id -> ('value, 'id) t ``` `make ~id` creates a new set by taking in the comparator + ```ocaml let s = make ~id:(module IntCmp) ``` @@ -56,6 +75,7 @@ val make : id:('value, 'id) id -> ('value, 'id) t val fromArray : 'value array -> id:('value, 'id) id -> ('value, 'id) t ``` `fromArray xs ~id` + ```ocaml toArray (fromArray [1;3;2;4] (module IntCmp)) = [1;2;3;4] ``` @@ -66,8 +86,11 @@ val fromSortedArrayUnsafe : ('value, 'id) t ``` `fromSortedArrayUnsafe xs ~id` + The same as [`fromArray`](./#val-fromArray) except it is after assuming the input array `x` is already sorted + **Unsafe** + ``` val isEmpty : (_, _) t -> bool ``` @@ -87,6 +110,7 @@ val has : ('value, 'id) t -> 'value -> bool val add : ('value, 'id) t -> 'value -> ('value, 'id) t ``` `add s x` If `x` was already in `s`, `s` is returned unchanged. + ```ocaml let s0 = make ~id:(module IntCmp);; let s1 = add s0 1 ;; @@ -102,11 +126,14 @@ val add : ('value, 'id) t -> 'value -> ('value, 'id) t val mergeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t ``` `mergeMany s xs` + Adding each of `xs` to `s`, note unlike [`add`](./#val-add), the reference of return value might be changed even if all values in `xs` exist `s` + ``` val remove : ('value, 'id) t -> 'value -> ('value, 'id) t ``` `remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|2;3;1;4;5|];; let s1 = remove s0 1 ;; @@ -121,11 +148,14 @@ val remove : ('value, 'id) t -> 'value -> ('value, 'id) t val removeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t ``` `removeMany s xs` + Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` + ``` val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t ``` `union s0 s1` + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; @@ -135,6 +165,7 @@ val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t ``` `intersect s0 s1` + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; @@ -144,6 +175,7 @@ val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t ``` `diff s0 s1` + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; @@ -154,6 +186,7 @@ val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t val subset : ('value, 'id) t -> ('value, 'id) t -> bool ``` `subset s0 s1` + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; @@ -166,10 +199,12 @@ val subset : ('value, 'id) t -> ('value, 'id) t -> bool val cmp : ('value, 'id) t -> ('value, 'id) t -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. It compare `size` first and then iterate over each element following the order of elements + ``` val eq : ('value, 'id) t -> ('value, 'id) t -> bool ``` `eq s0 s1` + returns true if toArray s0 = toArray s1 ``` val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit @@ -178,6 +213,7 @@ val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit val forEach : ('value, 'id) t -> ('value -> unit) -> unit ``` `forEach s f` applies `f` in turn to all elements of `s`. In increasing order + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; let acc = ref [] ;; @@ -191,6 +227,7 @@ val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a ``` In increasing order. + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; reduce s0 [] Belt.List.add = [6;5;3;2];; @@ -202,6 +239,7 @@ val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool val every : ('value, 'id) t -> ('value -> bool) -> bool ``` `every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + ``` val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool ``` @@ -209,6 +247,7 @@ val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool val some : ('value, 'id) t -> ('value -> bool) -> bool ``` `some p s` checks if at least one element of the set satisfies the predicate `p`. + ``` val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t ``` @@ -216,6 +255,7 @@ val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t ``` `keep m p` returns the set of all elements in `s` that satisfy predicate `p`. + ``` val partitionU : ('value, 'id) t -> @@ -229,10 +269,12 @@ val partition : ('value, 'id) t * ('value, 'id) t ``` `partition m p` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + ``` val size : ('value, 'id) t -> int ``` `size s` + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; size s0 = 4;; @@ -241,6 +283,7 @@ val size : ('value, 'id) t -> int val toArray : ('value, 'id) t -> 'value array ``` `toArray s0` + ```ocaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; toArray s0 = [|2;3;5;6|];; @@ -249,41 +292,51 @@ val toArray : ('value, 'id) t -> 'value array val toList : ('value, 'id) t -> 'value list ``` In increasing order + **See** [`toArray`](./#val-toArray) + ``` val minimum : ('value, 'id) t -> 'value option ``` `minimum s0` + returns the minimum element of the collection, None if it is empty ``` val minUndefined : ('value, 'id) t -> 'value Js.undefined ``` `minUndefined s0` + returns the minimum element of the collection, undefined if it is empty ``` val maximum : ('value, 'id) t -> 'value option ``` `maximum s0` + returns the maximum element of the collection, None if it is empty ``` val maxUndefined : ('value, 'id) t -> 'value Js.undefined ``` `maxUndefined s0` + returns the maximum element of the collection, undefined if it is empty ``` val get : ('value, 'id) t -> 'value -> 'value option ``` `get s0 k` + returns the reference of the value k' which is equivalent to k using the comparator specifiecd by this collection, None if it does not exist ``` val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined ``` **See** [`get`](./#val-get) + ``` val getExn : ('value, 'id) t -> 'value -> 'value ``` **See** [`get`](./#val-get) + **raise** if not exist + ``` val split : ('value, 'id) t -> @@ -291,19 +344,25 @@ val split : (('value, 'id) t * ('value, 'id) t) * bool ``` `split set ele` + returns a tuple ((smaller, larger), present), present is true when ele exist in set Below are operations only when better performance needed, it is still safe API but more verbose. More API will be exposed by needs + ``` val getData : ('value, 'id) t -> ('value, 'id) Belt__.Belt_SetDict.t ``` `getData s0` + **Advanced usage only** + returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing ``` val getId : ('value, 'id) t -> ('value, 'id) id ``` `getId s0` + **Advanced usage only** + returns the identity of s0 ``` val packIdData : @@ -312,5 +371,7 @@ val packIdData : ('value, 'id) t ``` `packIdData ~id ~data` + **Advanced usage only** + returns the packed collection \ No newline at end of file diff --git a/docs/api/melange/Belt-SortArray-Int.md b/docs/api/melange/Belt-SortArray-Int.md index bbb11f8f2..44bd7b00f 100644 --- a/docs/api/melange/Belt-SortArray-Int.md +++ b/docs/api/melange/Belt-SortArray-Int.md @@ -1,6 +1,10 @@ + # Module `SortArray.Int` + Specalized when key type is `int`, more efficient than the generic type + This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined + ``` type element = int ``` @@ -8,22 +12,28 @@ type element = int val strictlySortedLength : element array -> int ``` The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed + returns \+n means increasing order -n means negative order ``` val isSorted : element array -> bool ``` `sorted xs` return true if `xs` is in non strict increasing order + ``` val stableSortInPlace : element array -> unit ``` The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed + ``` val stableSort : element array -> element array ``` The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed + ``` val binarySearch : element array -> element -> int ``` If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. + If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` \ No newline at end of file + +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/melange/Belt-SortArray-String.md b/docs/api/melange/Belt-SortArray-String.md index 7393c633f..842fd2dd0 100644 --- a/docs/api/melange/Belt-SortArray-String.md +++ b/docs/api/melange/Belt-SortArray-String.md @@ -1,6 +1,10 @@ + # Module `SortArray.String` + Specalized when key type is `string`, more efficient than the generic type + This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined + ``` type element = string ``` @@ -8,22 +12,28 @@ type element = string val strictlySortedLength : element array -> int ``` The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed + returns \+n means increasing order -n means negative order ``` val isSorted : element array -> bool ``` `sorted xs` return true if `xs` is in non strict increasing order + ``` val stableSortInPlace : element array -> unit ``` The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed + ``` val stableSort : element array -> element array ``` The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed + ``` val binarySearch : element array -> element -> int ``` If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. + If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` \ No newline at end of file + +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/melange/Belt-SortArray.md b/docs/api/melange/Belt-SortArray.md index e65ff2cb8..67893ed3b 100644 --- a/docs/api/melange/Belt-SortArray.md +++ b/docs/api/melange/Belt-SortArray.md @@ -1,16 +1,24 @@ + # Module `Belt.SortArray` + [`Belt.SortArray`](#) + The top level provides some generic sort related utilities. + It also has two specialized inner modules [`Belt.SortArray.Int`](./Belt-SortArray-Int.md) and [`Belt.SortArray.String`](./Belt-SortArray-String.md) + A module for Array sort relevant utiliites + ``` module Int : sig ... end ``` Specalized when key type is `int`, more efficient than the generic type + ``` module String : sig ... end ``` Specalized when key type is `string`, more efficient than the generic type + ``` val strictlySortedLengthU : 'a array -> ('a -> 'a -> bool) Js.Fn.arity2 -> int ``` @@ -18,6 +26,7 @@ val strictlySortedLengthU : 'a array -> ('a -> 'a -> bool) Js.Fn.arity2 -> int val strictlySortedLength : 'a array -> ('a -> 'a -> bool) -> int ``` `strictlySortedLenght xs cmp` return `+n` means increasing order `-n` means negative order + ```ocaml strictlySortedLength [|1;2;3;4;3|] (fun x y -> x < y) = 4;; strictlySortedLength [||] (fun x y -> x < y) = 0;; @@ -31,6 +40,7 @@ val isSortedU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> bool val isSorted : 'a array -> ('a -> 'a -> int) -> bool ``` `isSorted arr cmp` + returns true if array is increasingly sorted (equal is okay ) isSorted \[\|1;1;2;3;4\|\] (fun x y -\> compare x y) = true ``` val stableSortInPlaceByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> unit @@ -39,7 +49,9 @@ val stableSortInPlaceByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> unit val stableSortInPlaceBy : 'a array -> ('a -> 'a -> int) -> unit ``` `stableSortBy xs cmp` + Sort xs in place using comparator `cmp`, the stable means if the elements are equal, their order will be preserved + ``` val stableSortByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a array ``` @@ -47,8 +59,10 @@ val stableSortByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a array val stableSortBy : 'a array -> ('a -> 'a -> int) -> 'a array ``` `stableSort xs cmp` + returns a fresh array The same as [`stableSortInPlaceBy`](./#val-stableSortInPlaceBy) except that `xs` is not modified + ``` val binarySearchByU : 'a array -> 'a -> ('a -> 'a -> int) Js.Fn.arity2 -> int ``` @@ -56,8 +70,11 @@ val binarySearchByU : 'a array -> 'a -> ('a -> 'a -> int) Js.Fn.arity2 -> int val binarySearchBy : 'a array -> 'a -> ('a -> 'a -> int) -> int ``` If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. + If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) + for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` + ```ocaml binarySearchBy [|1;2;3;4;33;35;36|] 33 = 4;; lnot (binarySearchBy [|1;3;5;7|] 4) = 2;; diff --git a/docs/api/melange/Belt.md b/docs/api/melange/Belt.md index 4bfdfcbc4..59effce75 100644 --- a/docs/api/melange/Belt.md +++ b/docs/api/melange/Belt.md @@ -1,21 +1,33 @@ + # Module `Belt` + A stdlib shipped with Melange + This stdlib is still in *beta* but we encourage you to try it out and give us feedback. + **Motivation** + The motivation for creating such library is to provide Melange users a better end-to-end user experience, since the original OCaml stdlib was not written with JS in mind. Below is a list of areas this lib aims to improve: -0. Consistency in name convention: camlCase, and arguments order -1. Exception thrown functions are all suffixed with *Exn*, e.g, *getExn* -2. Better performance and smaller code size running on JS platform + +1. Consistency in name convention: camlCase, and arguments order +2. Exception thrown functions are all suffixed with *Exn*, e.g, *getExn* +3. Better performance and smaller code size running on JS platform **Name Convention** + For higher order functions, it will be suffixed **U** if it takes uncurried callback. + ```ocaml val forEach : 'a t -> ('a -> unit) -> unit val forEachU : 'a t -> ('a -> unit [\@u]) -> unit ``` In general, uncurried version will be faster, but it may be less familiar to people who have a background in functional programming. + **A special encoding for collection safety** + When we create a collection library for a custom data type we need a way to provide a comparator function. Take *Set* for example, suppose its element type is a pair of ints, it needs a custom *compare* function that takes two tuples and returns their order. The *Set* could not just be typed as ` Set.t (int * int) `, its customized *compare* function needs to manifest itself in the signature, otherwise, if the user creates another customized *compare* function, the two collection could mix which would result in runtime error. + The original OCaml stdlib solved the problem using *functor* which creates a big closure at runtime and makes dead code elimination much harder. We use a phantom type to solve the problem: + ```ocaml module Comparable1 = Belt.Id.MakeComparable(struct type t = int * int @@ -38,91 +50,119 @@ end) let mySet2 = Belt.Set.make ~id:(module Comparable2) ``` Here, the compiler would infer `mySet1` and `mySet2` having different type, so e.g. a \`merge\` operation that tries to merge these two sets will correctly fail. + ```ocaml val mySet1 : ((int * int), Comparable1.identity) t val mySet2 : ((int * int), Comparable2.identity) t ``` `Comparable1.identity` and `Comparable2.identity` are not the same using our encoding scheme. + **Collection Hierarchy** + In general, we provide a generic collection module, but also create specialized modules for commonly used data type. Take *Belt.Set* for example, we provide: + ```ocaml Belt.Set Belt.Set.Int Belt.Set.String ``` The specialized modules *Belt.Set.Int*, *Belt.Set.String* are in general more efficient. + Currently, both *Belt\_Set* and *Belt.Set* are accessible to users for some technical reasons, we **strongly recommend** users stick to qualified import, *Belt.Set*, we may hide the internal, *i.e*, *Belt\_Set* in the future + ``` module Id : sig ... end ``` [`Belt.Id`](./Belt-Id.md) + ``` module Array : sig ... end ``` [`Belt.Array`](./Belt-Array.md) + ``` module SortArray : sig ... end ``` [`Belt.SortArray`](./Belt-SortArray.md) + ``` module MutableQueue : sig ... end ``` [`Belt.MutableQueue`](./Belt-MutableQueue.md) + ``` module MutableStack : sig ... end ``` [`Belt.MutableStack`](./Belt-MutableStack.md) + ``` module List : sig ... end ``` [`Belt.List`](./Belt-List.md) + ``` module Range : sig ... end ``` [`Belt.Range`](./Belt-Range.md) + ``` module Set : sig ... end ``` [`Belt.Set`](./Belt-Set.md) + ``` module Map : sig ... end ``` [`Belt.Map`](./Belt-Map.md), + ``` module MutableSet : sig ... end ``` [`Belt.MutableSet`](./Belt-MutableSet.md) + ``` module MutableMap : sig ... end ``` [`Belt.MutableMap`](./Belt-MutableMap.md) + ``` module HashSet : sig ... end ``` [`Belt.HashSet`](./Belt-HashSet.md) + ``` module HashMap : sig ... end ``` [`Belt.HashMap`](./Belt-HashMap.md) + ``` module Option : sig ... end ``` [`Belt.Option`](./Belt-Option.md) + [`Belt.Result`](./Belt-Result.md) + Utilities for result data type. + ``` module Result : sig ... end ``` [`Belt.Result`](./Belt-Result.md) + [`Belt.Int`](./Belt-Int.md) + Utilities for Int. + ``` module Int : sig ... end ``` [`Belt.Int`](./Belt-Int.md) Utililites for Int + [`Belt.Float`](./Belt-Float.md) + Utilities for Float. + ``` module Float : sig ... end ``` -[`Belt.Float`](./Belt-Float.md) Utililites for Float \ No newline at end of file +[`Belt.Float`](./Belt-Float.md) Utililites for Float diff --git a/docs/api/melange/Dom-Storage.md b/docs/api/melange/Dom-Storage.md index 74141fea8..5196172ac 100644 --- a/docs/api/melange/Dom-Storage.md +++ b/docs/api/melange/Dom-Storage.md @@ -1,4 +1,6 @@ + # Module `Dom.Storage` + ``` type t ``` diff --git a/docs/api/melange/Dom.md b/docs/api/melange/Dom.md index 780013266..37f92a4ef 100644 --- a/docs/api/melange/Dom.md +++ b/docs/api/melange/Dom.md @@ -1,4 +1,6 @@ + # Module `Dom` + ``` type _baseClass ``` diff --git a/docs/api/melange/Js-Array.md b/docs/api/melange/Js-Array.md index 6beb51e44..dff910797 100644 --- a/docs/api/melange/Js-Array.md +++ b/docs/api/melange/Js-Array.md @@ -1,6 +1,10 @@ + # Module `Js.Array` + Bindings to the functions in `Array.prototype` + JavaScript Array API + ``` type 'a t = 'a array ``` @@ -20,6 +24,7 @@ val isArray : 'a -> bool val length : 'a array -> int ``` Mutating functions + ``` val copyWithin : to_:int -> ?start:int -> ?end_:int -> 'a t -> 'a t ``` @@ -30,6 +35,7 @@ val fill : value:'a -> ?start:int -> ?end_:int -> 'a t -> 'a t val pop : 'a t -> 'a option ``` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/push + ``` val push : value:'a -> 'a t -> int ``` @@ -73,10 +79,12 @@ val concatMany : arrays:'a t array -> 'a t -> 'a t val includes : value:'a -> 'a t -> bool ``` ES2015 + ``` val join : ?sep:string -> 'a t -> string ``` Accessor functions + ``` val indexOf : value:'a -> ?start:int -> 'a t -> int ``` @@ -99,6 +107,7 @@ val toString : 'a t -> string val toLocaleString : 'a t -> string ``` Iteration functions + ``` val entries : 'a t -> (int * 'a) Js.iterator ``` diff --git a/docs/api/melange/Js-Bigint.md b/docs/api/melange/Js-Bigint.md index 76fcb0573..d4b488ac6 100644 --- a/docs/api/melange/Js-Bigint.md +++ b/docs/api/melange/Js-Bigint.md @@ -1,6 +1,10 @@ + # Module `Js.Bigint` + Bindings to functions in JavaScript's `BigInt` + JavaScript BigInt API + ``` type t = Js.bigint ``` @@ -8,14 +12,17 @@ type t = Js.bigint val make : 'a -> t ``` `make repr` creates a new BigInt from the representation `repr`. `repr` can be a number, a string, boolean, etc. + ``` val asIntN : precision:int -> t -> t ``` `asIntN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as a signed integer. + ``` val asUintN : precision:int -> t -> t ``` `asUintN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as an unsigned integer. + ``` type toLocaleStringOptions = { ``` @@ -32,10 +39,12 @@ val toLocaleString : string ``` `toLocaleString bigint` returns a string with a language-sensitive representation of this BigInt. + ``` val toString : t -> string ``` `toString bigint` returns a string representing the specified BigInt value. + ``` val neg : t -> t ``` @@ -46,14 +55,17 @@ val add : t -> t -> t val sub : t -> t -> t ``` Subtraction. + ``` val mul : t -> t -> t ``` Multiplication. + ``` val div : t -> t -> t ``` Division. + ``` val rem : t -> t -> t ``` \ No newline at end of file diff --git a/docs/api/melange/Js-Blob.md b/docs/api/melange/Js-Blob.md index 367bd075b..89b228319 100644 --- a/docs/api/melange/Js-Blob.md +++ b/docs/api/melange/Js-Blob.md @@ -1,5 +1,8 @@ + # Module `Js.Blob` + Bindings to Blob + ``` type t = Js.blob ``` @@ -8,8 +11,10 @@ type options = { ``` `type_ : string option;` A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". + ``endings : [ `transparent | `native ] option;`` How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the blob without changing them. To convert newlines to the host system's native convention, specify the value native. + ``` } ``` @@ -17,27 +22,33 @@ How to interpret newline characters (\\n) within the contents, if the data is te val make : string Js.iterator -> ?options:options -> unit -> t ``` `make (Js.Array.values contents_array)` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. + ``` val size : t -> float ``` `size t` returns the size of the Blob in bytes + ``` val type_ : t -> string ``` `type_ t` returns the MIME type of the file. + ``` val arrayBuffer : t -> Js.arrayBuffer Js.promise ``` `arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. + ``` val bytes : t -> Js.uint8Array Js.promise ``` `bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the blob as an array of bytes. + ``` val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t ``` `slice ?start ?end_ ?contentType t` creates and returns a new Blob object which contains data from a subset of the blob on which it's called. + ``` val text : t -> string Js.promise ``` -`text t` returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. \ No newline at end of file +`text t` returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. diff --git a/docs/api/melange/Js-Console.md b/docs/api/melange/Js-Console.md index f382ef362..b68a7e2de 100644 --- a/docs/api/melange/Js-Console.md +++ b/docs/api/melange/Js-Console.md @@ -1,4 +1,6 @@ + # Module `Js.Console` + ``` val log : 'a -> unit ``` diff --git a/docs/api/melange/Js-Date.md b/docs/api/melange/Js-Date.md index c03601b6a..3d66c2b18 100644 --- a/docs/api/melange/Js-Date.md +++ b/docs/api/melange/Js-Date.md @@ -1,6 +1,10 @@ + # Module `Js.Date` + Bindings to the functions in JS's `Date.prototype` + JavaScript Date API + ``` type t ``` @@ -8,10 +12,12 @@ type t val valueOf : t -> float ``` returns the primitive value of this date, equivalent to getTime + ``` val make : unit -> t ``` returns a date representing the current time + ``` val fromFloat : float -> t ``` @@ -83,18 +89,22 @@ val utcWithYMDHMS : val now : unit -> float ``` returns the number of milliseconds since Unix epoch + ``` val parseAsFloat : string -> float ``` returns NaN if passed invalid date string + ``` val getDate : t -> float ``` return the day of the month (1-31) + ``` val getDay : t -> float ``` returns the day of the week (0-6) + ``` val getFullYear : t -> float ``` @@ -111,6 +121,7 @@ val getMinutes : t -> float val getMonth : t -> float ``` returns the month (0-11) + ``` val getSeconds : t -> float ``` @@ -118,6 +129,7 @@ val getSeconds : t -> float val getTime : t -> float ``` returns the number of milliseconds since Unix epoch + ``` val getTimezoneOffset : t -> float ``` @@ -125,10 +137,12 @@ val getTimezoneOffset : t -> float val getUTCDate : t -> float ``` return the day of the month (1-31) + ``` val getUTCDay : t -> float ``` returns the day of the week (0-6) + ``` val getUTCFullYear : t -> float ``` @@ -145,6 +159,7 @@ val getUTCMinutes : t -> float val getUTCMonth : t -> float ``` returns the month (0-11) + ``` val getUTCSeconds : t -> float ``` diff --git a/docs/api/melange/Js-Dict.md b/docs/api/melange/Js-Dict.md index a04a5a5ac..3a0f74eb6 100644 --- a/docs/api/melange/Js-Dict.md +++ b/docs/api/melange/Js-Dict.md @@ -1,22 +1,30 @@ + # Module `Js.Dict` + Utility functions to treat a JS object as a dictionary + ``` type 'a t = 'a Js.dict ``` Dictionary type (ie an '{ }' JS object). However it is restricted to hold a single type; therefore values must have the same type. + This Dictionary type is mostly used with the `Js_json.t` type. + ``` type key = string ``` Key type + ``` val get : 'a t -> key -> 'a option ``` `get dict key` returns `None` if the `key` is not found in the dictionary, `Some value` otherwise + ``` val unsafeGet : 'a t -> key -> 'a ``` `unsafeGet dict key` return the value if the `key` exists, otherwise an **undefined** value is returned. Must be used only when the existence of a key is certain. (i.e. when having called `keys` function previously. + ```ocaml Array.iter (fun key -> Js.log (Js_dict.unsafeGet dic key)) (Js_dict.keys dict) ``` @@ -24,35 +32,43 @@ Array.iter (fun key -> Js.log (Js_dict.unsafeGet dic key)) (Js_dict.keys dict) val set : 'a t -> key -> 'a -> unit ``` `set dict key value` sets the `key`/`value` in `dict` + ``` val keys : 'a t -> string array ``` `keys dict` returns all the keys in the dictionary `dict` + ``` val empty : unit -> 'a t ``` `empty ()` returns an empty dictionary + ``` val unsafeDeleteKey : (string t -> string -> unit) Js.Fn.arity2 ``` Experimental internal function + ``` val entries : 'a t -> (key * 'a) array ``` `entries dict` returns the key value pairs in `dict` (ES2017) + ``` val values : 'a t -> 'a array ``` `values dict` returns the values in `dict` (ES2017) + ``` val fromList : (key * 'a) list -> 'a t ``` `fromList entries` creates a new dictionary containing each `(key, value)` pair in `entries` + ``` val fromArray : (key * 'a) array -> 'a t ``` `fromArray entries` creates a new dictionary containing each `(key, value)` pair in `entries` + ``` val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t ``` -`map f dict` maps `dict` to a new dictionary with the same keys, using `f` to map each value \ No newline at end of file +`map f dict` maps `dict` to a new dictionary with the same keys, using `f` to map each value diff --git a/docs/api/melange/Js-Exn.md b/docs/api/melange/Js-Exn.md index ecaf084c3..afea42336 100644 --- a/docs/api/melange/Js-Exn.md +++ b/docs/api/melange/Js-Exn.md @@ -1,5 +1,8 @@ + # Module `Js.Exn` + Utilities for dealing with Js exceptions + ``` type t ``` @@ -31,12 +34,16 @@ val fileName : t -> string option val isCamlExceptionOrOpenVariant : 'a -> bool ``` internal use only + ``` val anyToExnInternal : 'a -> exn ``` `anyToExnInternal obj` will take any value `obj` and wrap it in a Js.Exn.Error if given value is not an exn already. If `obj` is an exn, it will return `obj` without any changes. + This function is mostly useful for cases where you want to unify a type of a value that potentially is either exn, a JS error, or any other JS value really (e.g. for a value passed to a Promise.catch callback) + IMPORTANT: This is an internal API and may be changed / removed any time in the future. + ```ocaml switch (Js.Exn.unsafeAnyToExn("test")) { | Js.Exn.Error(v) => @@ -50,6 +57,7 @@ IMPORTANT: This is an internal API and may be changed / removed any time in the val raiseError : string -> 'a ``` Raise Js exception Error object with stacktrace + ``` val raiseEvalError : string -> 'a ``` diff --git a/docs/api/melange/Js-File.md b/docs/api/melange/Js-File.md index 083a8c32a..71a732734 100644 --- a/docs/api/melange/Js-File.md +++ b/docs/api/melange/Js-File.md @@ -1,5 +1,8 @@ + # Module `Js.File` + Bindings to File + ``` type t = Js.file ``` @@ -8,10 +11,13 @@ type options = { ``` `type_ : string option;` A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". + ``endings : [ `transparent | `native ] option;`` How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the file without changing them. To convert newlines to the host system's native convention, specify the value native. + `lastModified : float option;` A number representing the number of milliseconds between the Unix time epoch and when the file was last modified. Defaults to a value of Date.now(). + ``` } ``` @@ -24,35 +30,43 @@ val make : t ``` `make contents_array ~filename` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. + ``` val lastModified : t -> float ``` `lastModified t` accesses the read-only property of the File interface, which provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + ``` val name : t -> string ``` The `name t` read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property. + ``` val size : t -> float ``` `size t` returns the size of the File in bytes + ``` val type_ : t -> string ``` `type_ t` returns the MIME type of the file. + ``` val arrayBuffer : t -> Js.arrayBuffer Js.promise ``` `arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. + ``` val bytes : t -> Js.uint8Array Js.promise ``` `bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the file as an array of bytes. + ``` val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t ``` `slice ?start ?end_ ?contentType t` creates and returns a new File object which contains data from a subset of the file on which it's called. + ``` val text : t -> string Js.promise ``` -`text t` returns a Promise that resolves with a string containing the contents of the file, interpreted as UTF-8. \ No newline at end of file +`text t` returns a Promise that resolves with a string containing the contents of the file, interpreted as UTF-8. diff --git a/docs/api/melange/Js-Float.md b/docs/api/melange/Js-Float.md index 07a90c876..fa4803615 100644 --- a/docs/api/melange/Js-Float.md +++ b/docs/api/melange/Js-Float.md @@ -1,6 +1,10 @@ + # Module `Js.Float` + Bindings to functions in JavaScript's `Number` that deal with floats + Provides functions for inspecting and manipulating `float`s + ``` type t = float ``` @@ -8,19 +12,25 @@ type t = float val _NaN : t ``` The special value "Not a Number" + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) MDN ``` val isNaN : t -> bool ``` Tests if the given value is `_NaN` + Note that both `_NaN = _NaN` and `_NaN == _NaN` will return `false`. `isNaN` is therefore necessary to test for `_NaN`. + **Returns** `true` if the given value is `_NaN`, `false` otherwise + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) MDN ``` val isFinite : t -> bool ``` Tests if the given value is finite + **Returns** `true` if the given value is a finite number, `false` otherwise + ```ocaml (* returns [false] *) let _ = Js.Float.isFinite infinity @@ -39,9 +49,13 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val toExponential : ?digits:int -> t -> string ``` Formats a `float` using exponential (scientific) notation + **digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). + **Returns** a `string` representing the given value in exponential notation + The output will be rounded or padded with zeroes if necessary. + raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) ```ocaml Js.Float.toExponential 77.1234 = "7.71234e+1" @@ -53,9 +67,13 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val toFixed : ?digits:int -> t -> string ``` Formats a `float` using fixed point notation + **digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). Defaults to `0`. + **Returns** a `string` representing the given value in fixed-point notation (usually) + The output will be rounded or padded with zeroes if necessary. + raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) ```ocaml Js.Float.toFixed 12345.6789 = "12346" @@ -68,10 +86,15 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val toPrecision : ?digits:int -> t -> string ``` Formats a `float` using some fairly arbitrary rules + **digits** specifies how many digits should appear in total. The value must between 0 and some arbitrary number that's hopefully at least larger than 20 (for Node it's 21. Why? Who knows). + **Returns** a `string` representing the given value in fixed-point or scientific notation + The output will be rounded or padded with zeroes if necessary. + `toPrecision` differs from `toFixed` in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. + raises `RangeError` if digits is not in the range accepted by this function (what do you mean "vague"?) ```ocaml Js.Float.toPrecision 12345.6789 = "12345.6789" @@ -84,8 +107,11 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val toString : ?radix:int -> t -> string ``` Formats a `float` as a string + **radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). + **Returns** a `string` representing the given value in fixed-point (usually) + raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) ```ocaml Js.Float.toString 12345.6789 = "12345.6789" @@ -99,7 +125,9 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val fromString : string -> t ``` Parses the given `string` into a `float` using JavaScript semantics + **Returns** the number as a `float` if successfully parsed, `_NaN` otherwise. + ```ocaml Js.Float.fromString "123" = 123. Js.Float.fromString "12.3" = 12.3 diff --git a/docs/api/melange/Js-FormData.md b/docs/api/melange/Js-FormData.md index c1b922975..57c30522d 100644 --- a/docs/api/melange/Js-FormData.md +++ b/docs/api/melange/Js-FormData.md @@ -1,5 +1,8 @@ + # Module `Js.FormData` + Bindings to FormData + ``` type t ``` @@ -7,10 +10,12 @@ type t type entryValue ``` The values returned by the \`get`,All`\` and iteration functions is either a string or a Blob. Melange uses an abstract type and defers to users of the API to handle it according to their application needs. + ``` val make : unit -> t ``` `make ()` creates a new `FormData` object, initially empty. + ``` val append : name:string -> @@ -19,6 +24,7 @@ val append : unit ``` `append t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. + ``` val appendBlob : name:string -> @@ -28,18 +34,22 @@ val appendBlob : unit ``` `appendBlob t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. This method differs from `append` in that instances in the Blob hierarchy can pass a third filename argument. + ``` val delete : name:string -> t -> unit ``` `delete t ~name` deletes a key and its value(s) from a FormData object. + ``` val get : name:string -> t -> entryValue option ``` `get t ~name` returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use [`getAll`](./#val-getAll) instead. + ``` val getAll : name:string -> t -> entryValue array ``` `getAll t ~name` returns all the values associated with a given key from within a FormData object. + ``` val set : name:string -> @@ -48,6 +58,7 @@ val set : unit ``` `set t ~name ~value` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. + ``` val setBlob : name:string -> @@ -57,19 +68,23 @@ val setBlob : unit ``` `setBlob t ~name ~value ?filename` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. This method differs from `set` in that instances in the Blob hierarchy can pass a third filename argument. + ``` val has : name:string -> t -> bool ``` `has ~name t` returns whether a FormData object contains a certain key. + ``` val keys : t -> string Js.iterator ``` `keys t` returns an iterator which iterates through all keys contained in the FormData. The keys are strings. + ``` val values : t -> entryValue Js.iterator ``` `values t` returns an iterator which iterates through all values contained in the FormData. The values are strings or Blob objects. + ``` val entries : t -> (string * entryValue) Js.iterator ``` -`entries t` returns an iterator which iterates through all key/value pairs contained in the FormData. \ No newline at end of file +`entries t` returns an iterator which iterates through all key/value pairs contained in the FormData. diff --git a/docs/api/melange/Js-Global.md b/docs/api/melange/Js-Global.md index 50d8ab446..b8e00b08f 100644 --- a/docs/api/melange/Js-Global.md +++ b/docs/api/melange/Js-Global.md @@ -1,18 +1,25 @@ + # Module `Js.Global` + Bindings to functions in the JS global namespace + Contains functions available in the global scope (`window` in a browser context) + ``` type intervalId ``` Identify an interval started by [`setInterval`](./#val-setInterval) + ``` type timeoutId ``` Identify timeout started by [`setTimeout`](./#val-setTimeout) + ``` val clearInterval : intervalId -> unit ``` Clear an interval started by [`setInterval`](./#val-setInterval) + ```ocaml (* API for a somewhat aggressive snoozing alarm clock *) @@ -33,6 +40,7 @@ see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/ val clearTimeout : timeoutId -> unit ``` Clear a timeout started by [`setTimeout`](./#val-setTimeout) + ```ocaml (* A simple model of a code monkey's brain *) @@ -50,7 +58,9 @@ see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/ val setInterval : f:(unit -> unit) -> int -> intervalId ``` *Repeatedly* executes a callback with a specified interval (in milliseconds) between calls + **Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout + see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN ```ocaml (* Will count up and print the count to the console every second *) @@ -67,7 +77,9 @@ let _ = val setIntervalFloat : f:(unit -> unit) -> float -> intervalId ``` *Repeatedly* executes a callback with a specified interval (in milliseconds) between calls + **Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout + see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN ```ocaml (* Will count up and print the count to the console every second *) @@ -84,7 +96,9 @@ let _ = val setTimeout : f:(unit -> unit) -> int -> timeoutId ``` Execute a callback after a specified delay (in milliseconds) + **returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout + see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN ```ocaml (* Prints "Timed out!" in the console after one second *) @@ -98,7 +112,9 @@ let _ = val setTimeoutFloat : f:(unit -> unit) -> float -> timeoutId ``` Execute a callback after a specified delay (in milliseconds) + **returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout + see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN ```ocaml (* Prints "Timed out!" in the console after one second *) @@ -112,19 +128,23 @@ let _ = val encodeURI : string -> string ``` URL-encodes a string. + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) MDN ``` val decodeURI : string -> string ``` Decodes a URL-enmcoded string produced by `encodeURI` + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) MDN ``` val encodeURIComponent : string -> string ``` URL-encodes a string, including characters with special meaning in a URI. + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) MDN ``` val decodeURIComponent : string -> string ``` Decodes a URL-enmcoded string produced by `encodeURIComponent` + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) MDN \ No newline at end of file diff --git a/docs/api/melange/Js-Int.md b/docs/api/melange/Js-Int.md index ebf8be907..08c28ca4a 100644 --- a/docs/api/melange/Js-Int.md +++ b/docs/api/melange/Js-Int.md @@ -1,17 +1,26 @@ + # Module `Js.Int` + Bindings to functions in JavaScript's `Number` that deal with ints + Provides functions for inspecting and manipulating `int`s + ``` type t = int ``` If we use number, we need coerce to int32 by adding \`\|0\`, otherwise \`+0\` can be wrong. Most JS API is float oriented, it may overflow int32 or comes with `NAN` + ``` val toExponential : ?digits:t -> t -> string ``` Formats an `int` using exponential (scientific) notation + **digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). + **Returns** a `string` representing the given value in exponential notation + The output will be rounded or padded with zeroes if necessary. + raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) ```ocaml Js.Int.toExponential 77 = "7.7e+1" @@ -23,10 +32,15 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val toPrecision : ?digits:t -> t -> string ``` Formats an `int` using some fairly arbitrary rules + **digits** specifies how many digits should appear in total. The value must between 1 and some 100. + **Returns** a `string` representing the given value in fixed-point or scientific notation + The output will be rounded or padded with zeroes if necessary. + `toPrecision` differs from [`Js.Float.toFixed`](./Js-Float.md#val-toFixed) in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. + raises `RangeError` if digits is not between 1 and 100. ```ocaml Js.Int.toPrecision 123456789 = "123456789" @@ -38,8 +52,11 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val toString : ?radix:t -> t -> string ``` Formats an `int` as a string + **radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). + **Returns** a `string` representing the given value in fixed-point (usually) + raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) ```ocaml Js.Int.toString 123456789 = "123456789" diff --git a/docs/api/melange/Js-Iterator.md b/docs/api/melange/Js-Iterator.md index e466789f7..3f07302ff 100644 --- a/docs/api/melange/Js-Iterator.md +++ b/docs/api/melange/Js-Iterator.md @@ -1,5 +1,8 @@ + # Module `Js.Iterator` + Bindings to functions on `Iterator` + ``` type 'a t = 'a Js.iterator ``` diff --git a/docs/api/melange/Js-Json.md b/docs/api/melange/Js-Json.md index 460764d0e..f23f571bf 100644 --- a/docs/api/melange/Js-Json.md +++ b/docs/api/melange/Js-Json.md @@ -1,11 +1,18 @@ + # Module `Js.Json` + Utility functions to manipulate JSON values + Efficient JSON encoding using JavaScript API @see \ MDN + + ### Types + ``` type t ``` The JSON data structure + ``` type _ kind = ``` @@ -31,6 +38,7 @@ type _ kind = ``` Underlying type of a JSON value + ``` type tagged_t = ``` @@ -58,7 +66,9 @@ type tagged_t = ``` ``` + ### Accessor + ``` val classify : t -> tagged_t ``` @@ -66,79 +76,104 @@ val classify : t -> tagged_t val test : 'a -> 'b kind -> bool ``` `test v kind` returns true if `v` is of `kind` + ``` val decodeString : t -> string option ``` `decodeString json` returns `Some s` if `json` is a string, `None` otherwise + ``` val decodeNumber : t -> float option ``` `decodeNumber json` returns `Some n` if `json` is a number, `None` otherwise + ``` val decodeObject : t -> t Js.dict option ``` `decodeObject json` returns `Some o` if `json` is an object, `None` otherwise + ``` val decodeArray : t -> t array option ``` `decodeArray json` returns `Some a` if `json` is an array, `None` otherwise + ``` val decodeBoolean : t -> bool option ``` `decodeBoolean json` returns `Some b` if `json` is a boolean, `None` otherwise + ``` val decodeNull : t -> 'a Js.null option ``` `decodeNull json` returns `Some null` if `json` is a null, `None` otherwise + + ### Construtors + Those functions allows the construction of an arbitrary complex JSON values. + ``` val null : t ``` `null` is the singleton null JSON value + ``` val string : string -> t ``` `string s` makes a JSON string of the `string` `s` + ``` val number : float -> t ``` `number n` makes a JSON number of the `float` `n` + ``` val boolean : bool -> t ``` `boolean b` makes a JSON boolean of the `bool` `b` + ``` val object_ : t Js.dict -> t ``` `object_ dict` makes a JSON object of the `Js.dict` `dict` + ``` val array : t array -> t ``` `array a` makes a JSON array of the `Js.Json.t array` `a` + The functions below are specialized for specific array type which happened to be already JSON object in the Melange runtime. Therefore they are more efficient (constant time rather than linear conversion). + ``` val stringArray : string array -> t ``` `stringArray a` makes a JSON array of the `string array` `a` + ``` val numberArray : float array -> t ``` `numberArray a` makes a JSON array of the `float array` `a` + ``` val booleanArray : bool array -> t ``` `booleanArray` makes a JSON array of the `bool array` `a` + ``` val objectArray : t Js.dict array -> t ``` `objectArray a` makes a JSON array of the `JsDict.t array` `a` + + ### String conversion + ``` val parseExn : string -> t ``` `parseExn s` parses the string `s` into a JSON data structure + **Returns** a JSON data structure + raises `SyntaxError` if given string is not a valid JSON. Note SyntaxError is a JavaScript exception. ```ocaml (* parse a simple JSON string *) @@ -187,7 +222,9 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val stringify : t -> string ``` `stringify json` formats the JSON data structure as a string + **Returns** the string representation of a given JSON data structure + ```ocaml (* Creates and stringifies a simple JS object *) @@ -204,7 +241,9 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val stringifyWithSpace : t -> int -> string ``` `stringify json` formats the JSON data structure as a string + **Returns** the string representation of a given JSON data structure + ```ocaml (* Creates and stringifies a simple JS object with spacing *) @@ -221,22 +260,26 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val stringifyAny : 'a -> string option ``` `stringifyAny value` formats any `value` into a JSON string + ```ocaml (* prints ``"foo", "bar"`` *) Js.log (Js.Json.stringifyAny [| "foo"; "bar" |]) ``` see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN Best-effort serialization, it tries to seralize as many objects as possible and deserialize it back + ``` val deserializeUnsafe : string -> 'a ``` It is unsafe in two aspects + - It may throw during parsing - when you cast it to a specific type, it may have a type mismatch ``` val serializeExn : 'a -> string ``` It will raise in such situations: + - The object can not be serlialized to a JSON - There are cycles - Some JS engines can not stringify deeply nested json objects \ No newline at end of file diff --git a/docs/api/melange/Js-Map.md b/docs/api/melange/Js-Map.md index 06bc79977..51c7817bf 100644 --- a/docs/api/melange/Js-Map.md +++ b/docs/api/melange/Js-Map.md @@ -1,6 +1,10 @@ + # Module `Js.Map` + Bindings to functions in `Map` + ES6 Map API + ``` type ('k, 'v) t ``` diff --git a/docs/api/melange/Js-Math.md b/docs/api/melange/Js-Math.md index 1ff75cc38..5d799dbda 100644 --- a/docs/api/melange/Js-Math.md +++ b/docs/api/melange/Js-Math.md @@ -1,118 +1,150 @@ + # Module `Js.Math` + Bindings to the functions in the `Math` object + JavaScript Math API + ``` val _E : float ``` Euler's number + ``` val _LN2 : float ``` natural logarithm of 2 + ``` val _LN10 : float ``` natural logarithm of 10 + ``` val _LOG2E : float ``` base 2 logarithm of E + ``` val _LOG10E : float ``` base 10 logarithm of E + ``` val _PI : float ``` Pi... (ratio of the circumference and diameter of a circle) + ``` val _SQRT1_2 : float ``` square root of 1/2 + ``` val _SQRT2 : float ``` square root of 2 + ``` val abs_int : int -> int ``` absolute value + ``` val abs_float : float -> float ``` absolute value + ``` val acos : float -> float ``` arccosine in radians, can return NaN + ``` val acosh : float -> float ``` hyperbolic arccosine in raidans, can return NaN, ES2015 + ``` val asin : float -> float ``` arcsine in radians, can return NaN + ``` val asinh : float -> float ``` hyperbolic arcsine in raidans, ES2015 + ``` val atan : float -> float ``` arctangent in radians + ``` val atanh : float -> float ``` hyperbolic arctangent in radians, can return NaN, ES2015 + ``` val atan2 : y:float -> x:float -> float ``` arctangent of the quotient of x and y, mostly... this one's a bit weird + ``` val cbrt : float -> float ``` cube root, can return NaN, ES2015 + ``` val unsafe_ceil_int : float -> int ``` may return values not representable by `int` + ``` val ceil_int : float -> int ``` smallest int greater than or equal to the argument + ``` val ceil_float : float -> float ``` smallest float greater than or equal to the argument + ``` val clz32 : int -> int ``` number of leading zero bits of the argument's 32 bit int representation, ES2015 + ``` val cos : float -> float ``` cosine in radians + ``` val cosh : float -> float ``` hyperbolic cosine in radians, ES2015 + ``` val exp : float -> float ``` natural exponentional + ``` val expm1 : float -> float ``` natural exponential minus 1, ES2015 + ``` val unsafe_floor_int : float -> int ``` may return values not representable by `int` + ``` val floor_int : float -> int ``` largest int greater than or equal to the arugment + ``` val floor_float : float -> float ``` @@ -120,119 +152,148 @@ val floor_float : float -> float val fround : float -> float ``` round to nearest single precision float, ES2015 + ``` val hypot : float -> float -> float ``` pythagorean equation, ES2015 + ``` val hypotMany : float array -> float ``` generalized pythagorean equation, ES2015 + ``` val imul : int -> int -> int ``` 32-bit integer multiplication, ES2015 + ``` val log : float -> float ``` natural logarithm, can return NaN + ``` val log1p : float -> float ``` natural logarithm of 1 \+ the argument, can return NaN, ES2015 + ``` val log10 : float -> float ``` base 10 logarithm, can return NaN, ES2015 + ``` val log2 : float -> float ``` base 2 logarithm, can return NaN, ES2015 + ``` val max_int : int -> int -> int ``` max value + ``` val maxMany_int : int array -> int ``` max value + ``` val max_float : float -> float -> float ``` max value + ``` val maxMany_float : float array -> float ``` max value + ``` val min_int : int -> int -> int ``` min value + ``` val minMany_int : int array -> int ``` min value + ``` val min_float : float -> float -> float ``` min value + ``` val minMany_float : float array -> float ``` min value + ``` val pow_float : base:float -> exp:float -> float ``` base to the power of the exponent + ``` val random : unit -> float ``` random number in \[0,1) + ``` val random_int : int -> int -> int ``` random number in \[min,max) + ``` val unsafe_round : float -> int ``` rounds to nearest integer, returns a value not representable as `int` if NaN + ``` val round : float -> float ``` rounds to nearest integer + ``` val sign_int : int -> int ``` the sign of the argument, 1, \-1 or 0, ES2015 + ``` val sign_float : float -> float ``` the sign of the argument, 1, \-1, 0, \-0 or NaN, ES2015 + ``` val sin : float -> float ``` sine in radians + ``` val sinh : float -> float ``` hyperbolic sine in radians, ES2015 + ``` val sqrt : float -> float ``` square root, can return NaN + ``` val tan : float -> float ``` tangent in radians + ``` val tanh : float -> float ``` hyperbolic tangent in radians, ES2015 + ``` val unsafe_trunc : float -> int ``` truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 + ``` val trunc : float -> float ``` -truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 \ No newline at end of file +truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 diff --git a/docs/api/melange/Js-Null.md b/docs/api/melange/Js-Null.md index ce0b91bb8..46aa576d8 100644 --- a/docs/api/melange/Js-Null.md +++ b/docs/api/melange/Js-Null.md @@ -1,18 +1,25 @@ + # Module `Js.Null` + Utility functions on [`null`](./Js.md#type-null) + Provides functionality for dealing with the `'a Js.null` type + ``` type +'a t = 'a Js.null ``` Local alias for `'a Js.null` + ``` val return : 'a -> 'a t ``` Constructs a value of `'a Js.null` containing a value of `'a` + ``` val empty : 'a t ``` The empty value, `null` + ``` val getUnsafe : 'a t -> 'a ``` @@ -26,7 +33,9 @@ val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t ``` Maps the contained value using the given function + If `'a Js.null` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.null` + ```ocaml let maybeGreetWorld (maybeGreeting: string Js.null) = Js.Null.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") @@ -35,7 +44,9 @@ let maybeGreetWorld (maybeGreeting: string Js.null) = val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit ``` Iterates over the contained value with the given function + If `'a Js.null` contains a value, that value is unwrapped and applied to the given function. + ```ocaml let maybeSay (maybeMessage: string Js.null) = Js.Null.iter maybeMessage ~f:(fun message -> Js.log message) @@ -45,6 +56,7 @@ val fromOption : 'a option -> 'a t ``` Maps `'a option` to `'a Js.null` +
Some a -> return a
None -> empty @@ -55,6 +67,7 @@ val toOption : 'a t -> 'a option ``` Maps `'a Js.null` to `'a option` +
return a -> Some a
empty -> None diff --git a/docs/api/melange/Js-Nullable.md b/docs/api/melange/Js-Nullable.md index f3aec1cf7..c4f7ffb3c 100644 --- a/docs/api/melange/Js-Nullable.md +++ b/docs/api/melange/Js-Nullable.md @@ -1,26 +1,35 @@ + # Module `Js.Nullable` + Utility functions on [`nullable`](./Js.md#type-nullable) + Contains functionality for dealing with values that can be both `null` and `undefined` + ``` type +'a t = 'a Js.nullable ``` Local alias for `'a Js.nullable` + ``` val return : 'a -> 'a t ``` Constructs a value of `'a Js.nullable` containing a value of `'a` + ``` val isNullable : 'a t -> bool ``` Returns `true` if the given value is `null` or `undefined`, `false` otherwise + ``` val null : 'a t ``` The `null` value of type `'a Js.nullable` + ``` val undefined : 'a t ``` The `undefined` value of type `'a Js.nullable` + ``` val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t ``` @@ -28,7 +37,9 @@ val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t ``` Binds the contained value using the given function + If `'a Js.nullable` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.nullable` + ```ocaml let maybeGreetWorld (maybeGreeting: string Js.nullable) = Js.Nullable.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") @@ -37,7 +48,9 @@ let maybeGreetWorld (maybeGreeting: string Js.nullable) = val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit ``` Iterates over the contained value with the given function + If `'a Js.nullable` contains a value, that value is unwrapped and applied to the given function. + ```ocaml let maybeSay (maybeMessage: string Js.nullable) = Js.Nullable.iter maybeMessage ~f:(fun message -> Js.log message) @@ -47,6 +60,7 @@ val fromOption : 'a option -> 'a t ``` Maps `'a option` to `'a Js.nullable` +
Some a -> return a
None -> undefined @@ -57,6 +71,7 @@ val toOption : 'a t -> 'a option ``` Maps `'a Js.nullable` to `'a option` +
return a -> Some a
undefined -> None diff --git a/docs/api/melange/Js-Obj.md b/docs/api/melange/Js-Obj.md index ac6cff4da..7ff457710 100644 --- a/docs/api/melange/Js-Obj.md +++ b/docs/api/melange/Js-Obj.md @@ -1,5 +1,8 @@ + # Module `Js.Obj` + Utility functions on \`Js.t\` JS objects + ``` val empty : unit -> < .. > Js.t ``` @@ -10,6 +13,7 @@ val assign : < .. > Js.t -> < .. > Js.t -> < .. > Js.t val merge : < .. > Js.t -> < .. > Js.t -> < .. > Js.t ``` `merge obj1 obj2` assigns the properties in `obj2` to a copy of `obj1`. The function returns a new object, and both arguments are not mutated + ``` val keys : _ Js.t -> string array ``` \ No newline at end of file diff --git a/docs/api/melange/Js-Promise.md b/docs/api/melange/Js-Promise.md index 7aaaf8a58..2a493825c 100644 --- a/docs/api/melange/Js-Promise.md +++ b/docs/api/melange/Js-Promise.md @@ -1,6 +1,10 @@ + # Module `Js.Promise` + Bindings to JS `Promise` functions + Specialized bindings to Promise. Note: For simplicity, this binding does not track the error type, it treat it as an opaque type + ``` type +'a t = 'a Js.promise ``` diff --git a/docs/api/melange/Js-Re.md b/docs/api/melange/Js-Re.md index 54a7f30c5..36f5547da 100644 --- a/docs/api/melange/Js-Re.md +++ b/docs/api/melange/Js-Re.md @@ -1,9 +1,17 @@ + # Module `Js.Re` + Bindings to the functions in `RegExp.prototype` + Provides bindings for JavaScript Regular Expressions + + ##### Syntax sugar + Melange provides a bit of syntax sugar for regex literals: `[%re "/foo/g"]` will evaluate to a [`t`](./#type-t) that can be passed around and used like usual. + **Note:** This is not an immutable API. A RegExp object with the `global` ("g") flag set will modify the [`lastIndex`](./#val-lastIndex) property when the RegExp object is used, and subsequent uses will continue the search from the previous [`lastIndex`](./#val-lastIndex). + ```ocaml let maybeMatches = Js.String.exec ~str:"banana" [\[%re "/na+/g"\]] ``` @@ -13,27 +21,34 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular\_Expr type t = Js.re ``` the RegExp object + ``` type result ``` the result of a executing a RegExp on a string + ``` val captures : result -> string Js.nullable array ``` an array of the match and captures, the first is the full match and the remaining are the substring captures + ``` val index : result -> int ``` 0-based index of the match in the input string + ``` val input : result -> string ``` the original input string + ``` val fromString : string -> t ``` Constructs a RegExp object ([`t`](./#type-t)) from a string + Regex literals (`[%re "/.../"]`) should generally be preferred, but `fromString` is very useful when you need to insert a string into a regex. + ```ocaml (* A function that extracts the content of the first element with the given tag *) @@ -48,7 +63,9 @@ let contentOf tag xmlString = val fromStringWithFlags : string -> flags:string -> t ``` Constructs a RegExp object ([`t`](./#type-t)) from a string with the given `flags` + See [`fromString`](./#val-fromString) + Valid flags:
g global @@ -58,23 +75,29 @@ Valid flags:
y sticky (es2015)
+ ``` val flags : t -> string ``` returns the enabled flags as a string + ``` val global : t -> bool ``` returns a bool indicating whether the `global` flag is set + ``` val ignoreCase : t -> bool ``` returns a bool indicating whether the `ignoreCase` flag is set + ``` val lastIndex : t -> int ``` returns the index where the next match will start its search + This property will be modified when the RegExp object is used, if the `global` ("g") flag is set. + ```ocaml (* Finds and prints successive matches *) @@ -96,27 +119,34 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val setLastIndex : t -> int -> unit ``` sets the index at which the next match will start its search from + ``` val multiline : t -> bool ``` returns a bool indicating whether the `multiline` flag is set + ``` val source : t -> string ``` returns the pattern as a string + ``` val sticky : t -> bool ``` returns a bool indicating whether the `sticky` flag is set + ``` val unicode : t -> bool ``` returns a bool indicating whether the `unicode` flag is set + ``` val exec : str:string -> t -> result option ``` executes a search on a given string using the given RegExp object + **returns** `Some` [`result`](./#type-result) if a match is found, `None` otherwise + ```ocaml (* Match "quick brown" followed by "jumps", ignoring characters in between * Remember "brown" and "jumps" @@ -131,7 +161,9 @@ see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_O val test : str:string -> t -> bool ``` tests whether the given RegExp object will match a given string + **returns** `true` if a match is found, `false` otherwise + ```ocaml (* A simple implementation of Js.String.startsWith *) diff --git a/docs/api/melange/Js-Set.md b/docs/api/melange/Js-Set.md index 7224e0291..bd1087307 100644 --- a/docs/api/melange/Js-Set.md +++ b/docs/api/melange/Js-Set.md @@ -1,6 +1,10 @@ + # Module `Js.Set` + Bindings to functions in `Set` + ES6 Set API + ``` type 'a t ``` diff --git a/docs/api/melange/Js-String.md b/docs/api/melange/Js-String.md index 669859455..ff90c544a 100644 --- a/docs/api/melange/Js-String.md +++ b/docs/api/melange/Js-String.md @@ -1,6 +1,10 @@ + # Module `Js.String` + Bindings to the functions in `String.prototype` + JavaScript String API + ``` type t = string ``` @@ -8,6 +12,7 @@ type t = string val make : 'a -> t ``` `make value` converts the given value to a string + ```ocaml make 3.5 = "3.5";; make [|1;2;3|]) = "1,2,3";; @@ -16,6 +21,7 @@ val make : 'a -> t val fromCharCode : int -> t ``` `fromCharCode n` creates a string containing the character corresponding to that number; *n* ranges from 0 to 65535. If out of range, the lower 16 bits of the value are used. Thus, `fromCharCode 0x1F63A` gives the same result as `fromCharCode 0xF63A`. + ```ocaml fromCharCode 65 = "A";; fromCharCode 0x3c8 = {js|ψ|js};; @@ -26,6 +32,7 @@ val fromCharCode : int -> t val fromCharCodeMany : int array -> t ``` `fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given numbers, using the same rules as `fromCharCode`. + ```ocaml fromCharCodeMany([|0xd55c, 0xae00, 33|]) = {js|한글!|js};; ``` @@ -33,6 +40,7 @@ val fromCharCodeMany : int array -> t val fromCodePoint : int -> t ``` `fromCodePoint n` creates a string containing the character corresponding to that numeric code point. If the number is not a valid code point, **raises** `RangeError`. Thus, `fromCodePoint 0x1F63A` will produce a correct value, unlike `fromCharCode 0x1F63A`, and `fromCodePoint -5` will raise a `RangeError`. + ```ocaml fromCodePoint 65 = "A";; fromCodePoint 0x3c8 = {js|ψ|js};; @@ -43,6 +51,7 @@ val fromCodePoint : int -> t val fromCodePointMany : int array -> t ``` `fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given code point numbers, using the same rules as `fromCodePoint`. + ```ocaml fromCodePointMany([|0xd55c; 0xae00; 0x1f63a|]) = {js|한글😺|js} ``` @@ -50,6 +59,7 @@ val fromCodePointMany : int array -> t val length : t -> int ``` `length s` returns the length of the given string. + ```ocaml length "abcd" = 4;; ``` @@ -57,6 +67,7 @@ val length : t -> int val get : t -> int -> t ``` `get s n` returns as a string the character at the given index number. If `n` is out of range, this function returns `undefined`, so at some point this function may be modified to return `t option`. + ```ocaml get "Reason" 0 = "R";; get "Reason" 4 = "o";; @@ -66,6 +77,7 @@ val get : t -> int -> t val charAt : index:int -> t -> t ``` `charAt ~index s` gets the character at position `index` within string `s`. If `index` is negative or greater than the length of `s`, returns the empty string. If the string contains characters outside the range `\u0000-\uffff`, it will return the first 16-bit value at that position in the string. + ```ocaml charAt ~index:0 "Reason" = "R" charAt ~index:12 "Reason" = ""; @@ -75,6 +87,7 @@ val charAt : index:int -> t -> t val charCodeAt : index:int -> t -> float ``` `charCodeAt s ~index` returns the character code at position `index` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to `0x10000`. The return type is `float` because this function returns `NaN` if `index` is less than zero or greater than the length of the string. + ```ocaml charCodeAt ~index:0 {js|😺|js} = 0xd83d codePointAt ~index:0 {js|😺|js} = Some 0x1f63a @@ -83,15 +96,18 @@ val charCodeAt : index:int -> t -> float val codePointAt : index:int -> t -> int option ``` `codePointAt s ~index` returns the code point at position `index` within string `s` as a `Some` value. The return value handles code points greater than or equal to `0x10000`. If there is no code point at the given position, the function returns `None`. + ```ocaml codePointAt ~index:1 {js|¿😺?|js} = Some 0x1f63a codePointAt ~index:5 "abc" = None ``` ES2015 + ``` val concat : other:t -> t -> t ``` `concat ~other:str2 str1` returns a new string with `str2` added after `str1`. + ```ocaml concat ~other:"bell" "cow" = "cowbell";; ``` @@ -99,6 +115,7 @@ val concat : other:t -> t -> t val concatMany : strings:t array -> t -> t ``` `concatMany ~strings original` returns a new string consisting of each item of the array of strings `strings` added to the `original` string. + ```ocaml concatMany ~strings:[|"2nd"; "3rd"; "4th"|] "1st" = "1st2nd3rd4th";; ``` @@ -106,6 +123,7 @@ val concatMany : strings:t array -> t -> t val endsWith : suffix:t -> ?len:int -> t -> bool ``` `endsWith ~suffix ?len str` returns `true` if the `str` ends with `suffix`, `false` otherwise. If `len` is specified, \`endsWith\` only takes into account the first `len` characters. + ```ocaml endsWith ~suffix:"cd" ~len:4 "abcd" = true;; endsWith ~suffix:"cd" ~len:3 "abcde" = false;; @@ -119,6 +137,7 @@ val endsWith : suffix:t -> ?len:int -> t -> bool val includes : search:t -> ?start:int -> t -> bool ``` `includes ~search ?start s` returns `true` if `search` is found anywhere within `s` starting at character number `start` (where 0 is the first character), `false` otherwise. + ```ocaml includes ~search:"gram" "programmer" = true;; includes ~search:"er" "programmer" = true;; @@ -132,6 +151,7 @@ val includes : search:t -> ?start:int -> t -> bool val indexOf : search:t -> ?start:int -> t -> int ``` `indexOf ~search ?start s` returns the position at which `search` was found within `s` starting at character position `start`, or `-1` if `search` is not found in that portion of `s`. The return value is relative to the beginning of the string, no matter where the search started from. + ```ocaml indexOf ~search:"ok" "bookseller" = 2;; indexOf ~search:"sell" "bookseller" = 4;; @@ -145,6 +165,7 @@ val indexOf : search:t -> ?start:int -> t -> int val lastIndexOf : search:t -> ?start:int -> t -> int ``` `lastIndexOf ~search ~start s` returns the position of the *last* occurrence of `searchValue` within `s`, searching backwards from the given `start` position. Returns `-1` if `searchValue` is not in `s`. The return value is always relative to the beginning of the string. + ```ocaml lastIndexOf ~search:"ok" "bookseller" = 2;; lastIndexOf ~search:"ee" "beekeeper" = 4;; @@ -158,6 +179,7 @@ val lastIndexOf : search:t -> ?start:int -> t -> int val localeCompare : other:t -> t -> float ``` `localeCompare ~other:comparison reference` returns: + - a negative value if `reference` comes before `comparison` in sort order - zero if `reference` and `comparison` have the same sort order - a positive value if `reference` comes after `comparison` in sort order @@ -171,9 +193,11 @@ val localeCompare : other:t -> t -> float val match_ : regexp:Js.re -> t -> t option array option ``` `match ~regexp str` matches a string against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the `g` modifier, if there is a match, the return value is `Some array` where the array contains: + - The entire matched string - Any capture groups if the `regexp` had parentheses For regular expressions with the `g` modifier, a matched expression returns `Some array` with all the matched substrings and no capture groups. + ```ocaml match "The better bats" ~regexp:[%re "/b[aeiou]t/"] = Some [|"bet"|] match "The better bats" ~regexp:[%re "/b[aeiou]t/g"] = Some [|"bet";"bat"|] @@ -184,17 +208,21 @@ For regular expressions with the `g` modifier, a matched expression returns `Som val normalize : ?form:[ `NFC | `NFD | `NFKC | `NFKD ] -> t -> t ``` `normalize ~form str` returns the normalized Unicode string using the specified form of normalization, which may be one of: + - `` `NFC `` — Normalization Form Canonical Composition. - `` `NFD `` — Normalization Form Canonical Decomposition. - `` `NFKC `` — Normalization Form Compatibility Composition. - `` `NFKD `` — Normalization Form Compatibility Decomposition. If `form` is omitted, `` `NFC `` is used. + Consider the character `ã`, which can be represented as the single codepoint `\u00e3` or the combination of a lower case letter A `\u0061` and a combining tilde `\u0303`. Normalization ensures that both can be stored in an equivalent binary representation. + see [https://www.unicode.org/reports/tr15/tr15-45.html](https://www.unicode.org/reports/tr15/tr15-45.html) Unicode technical report for details ``` val repeat : count:int -> t -> t ``` `repeat ~count s` returns a string that consists of `count` repetitions of `s`. Raises `RangeError` if `n` is negative. + ```ocaml repeat ~count:3 "ha" = "hahaha" repeat ~count:0 "empty" = "" @@ -203,7 +231,9 @@ val repeat : count:int -> t -> t val replace : search:t -> replacement:t -> t -> t ``` `replace ~search ~replacement string` returns a new string which is identical to `string` except with the first matching instance of `search` replaced by `replacement`. + `search` is treated as a verbatim string to match, not a regular expression. + ```ocaml replace ~search:"old" ~replacement:"new" "old string" = "new string" replace ~search:"the" ~replacement:"this" "the cat and the dog" = "this cat and the dog" @@ -212,6 +242,7 @@ val replace : search:t -> replacement:t -> t -> t val replaceByRe : regexp:Js.re -> replacement:t -> t -> t ``` `replaceByRe ~regexp ~replacement string` returns a new string where occurrences matching `regexp` have been replaced by `replacement`. + ```ocaml replaceByRe ~regexp:[%re "/[aeiou]/g"] ~replacement:"x" "vowels be gone" = "vxwxls bx gxnx" replaceByRe ~regexp:[%re "/(\\w+) (\\w+)/"] ~replacement:"$2, $1" "Juan Fulano" = "Fulano, Juan" @@ -220,6 +251,7 @@ val replaceByRe : regexp:Js.re -> replacement:t -> t -> t val unsafeReplaceBy0 : regexp:Js.re -> f:(t -> int -> t -> t) -> t -> t ``` `unsafeReplaceBy0 ~regexp ~f s` returns a new string with some or all matches of a pattern with no capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the offset at which the match begins, and the whole string being matched + ```ocaml let str = "beautiful vowels" let re = [%re "/[aeiou]/g"] @@ -230,10 +262,12 @@ let replaced = Js.String.unsafeReplaceBy0 ~regexp:re ~f:matchFn str let () = Js.log replaced (* prints "bEAUtifUl vOwEls" *) ``` @see \ MDN + ``` val unsafeReplaceBy1 : regexp:Js.re -> f:(t -> t -> int -> t -> t) -> t -> t ``` `unsafeReplaceBy1 ~regexp ~f s` returns a new string with some or all matches of a pattern with one set of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. + ```ocaml let str = "increment 23" let re = [%re "/increment (\\d+)/g"] @@ -245,6 +279,7 @@ let replaced = Js.String.unsafeReplaceBy1 ~regexp:re ~f:matchFn str let () = Js.log replaced (* prints "increment 23 is 24" *) ``` @see \ MDN + ``` val unsafeReplaceBy2 : regexp:Js.re -> @@ -253,6 +288,7 @@ val unsafeReplaceBy2 : t ``` `unsafeReplaceBy2 ~regexp ~f s` returns a new string with some or all matches of a pattern with two sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. + ```ocaml let str = "7 times 6" let re = [%re "/(\\d+) times (\\d+)/"] @@ -272,11 +308,13 @@ val unsafeReplaceBy3 : t ``` `unsafeReplaceBy3 ~regexp ~f s` returns a new string with some or all matches of a pattern with three sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN ``` val search : regexp:Js.re -> t -> int ``` `search ~regexp str` returns the starting position of the first match of `regexp` in the given `str`, or \-1 if there is no match. + ```ocaml search ~regexp:[%re "/\\d+/"] "testing 1 2 3" = 8;; search ~regexp:[%re "/\\d+/"] "no numbers" = -1;; @@ -285,9 +323,13 @@ search ~regexp:[%re "/\\d+/"] "no numbers" = -1;; val slice : ?start:int -> ?end_:int -> t -> t ``` `slice ?start ?end str` returns the substring of `str` starting at character `start` up to but not including `end` + If either `start` or `end` is negative, then it is evaluated as `length str - start` (or `length str - end`). + If `end` is greater than the length of `str`, then it is treated as `length str`. + If `start` is greater than `end`, `slice` returns the empty string. + ```ocaml slice ~start:2 ~end_:5 "abcdefg" = "cde";; slice ~start:2 ~end_:9 "abcdefg" = "cdefg";; @@ -298,6 +340,7 @@ If `start` is greater than `end`, `slice` returns the empty string. val split : ?sep:t -> ?limit:int -> t -> t array ``` `split ?sep ?limit str` splits the given `str` at every occurrence of `sep` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. + ```ocaml split ~sep:"/" ~limit: 3 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"|];; split ~sep:"/" ~limit: 0 "ant/bee/cat/dog/elk" = [| |];; @@ -307,16 +350,19 @@ val split : ?sep:t -> ?limit:int -> t -> t array val splitByRe : regexp:Js.re -> ?limit:int -> t -> t option array ``` `splitByRe str ~regexp ?limit ()` splits the given `str` at every occurrence of `regexp` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. + ```ocaml splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:3 "one: two: three: four" = [|"one"; "two"; "three"|];; splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:0 "one: two: three: four" = [| |];; splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:8 "one: two: three: four" = [|"one"; "two"; "three"; "four"|];; ``` ; + ``` val startsWith : prefix:t -> ?start:int -> t -> bool ``` `startsWith ~prefix ?start str` returns `true` if the `str` starts with `prefix` starting at position `start`, `false` otherwise. If `start` is negative, the search starts at the beginning of `str`. + ```ocaml startsWith ~prefix:"Hello" ~start:0 "Hello, World!" = true;; startsWith ~prefix:"World" ~start:7 "Hello, World!" = true;; @@ -326,10 +372,14 @@ val startsWith : prefix:t -> ?start:int -> t -> bool val substr : ?start:int -> ?len:int -> t -> t ``` `substr ?start ?len str` returns the substring of `str` of length `len` starting at position `start`. + If `start` is less than zero, the starting position is the length of `str` + - `start`. If `start` is greater than or equal to the length of `str`, returns the empty string. + If `len` is less than or equal to zero, returns the empty string. + ```ocaml substr ~start:3 ~len:4 "abcdefghij" = "defghij" substr ~start:(-3) ~len:4 "abcdefghij" = "hij" @@ -340,9 +390,13 @@ deprecated This function is deprecated, see https://developer.mozilla.org/en-US/ val substring : ?start:int -> ?end_:int -> t -> t ``` `substring ~start ~end_ str` returns characters `start` up to but not including `end_` from `str`. + If `start` is less than zero, it is treated as zero. + If `end_` is zero or negative, the empty string is returned. + If `start` is greater than `end_`, the start and finish points are swapped. + ```ocaml substring ~start:3 ~end_:6 "playground" = "ygr";; substring ~start:6 ~end_:3 "playground" = "ygr";; @@ -352,6 +406,7 @@ If `start` is greater than `end_`, the start and finish points are swapped. val toLowerCase : t -> t ``` `toLowerCase str` converts `str` to lower case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can give different results depending upon context, for example with the Greek letter sigma, which has two different lower case forms when it is the last character in a string or not. + ```ocaml toLowerCase "ABC" = "abc";; toLowerCase {js|ΣΠ|js} = {js|σπ|js};; @@ -361,10 +416,12 @@ val toLowerCase : t -> t val toLocaleLowerCase : t -> t ``` `toLocaleLowerCase str` converts `str` to lower case using the current locale + ``` val toUpperCase : t -> t ``` `toUpperCase str` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can expand the number of letters in the result; for example the German `ß` capitalizes to two `S`es in a row. + ```ocaml toUpperCase "abc" = "ABC";; toUpperCase {js|Straße|js} = {js|STRASSE|js};; @@ -374,10 +431,12 @@ val toUpperCase : t -> t val toLocaleUpperCase : t -> t ``` `toLocaleUpperCase str` converts `str` to upper case using the current locale + ``` val trim : t -> t ``` `trim str` returns a string that is `str` with whitespace stripped from both ends. Internal whitespace is not removed. + ```ocaml trim " abc def " = "abc def" trim "\n\r\t abc def \n\n\t\r " = "abc def" @@ -386,6 +445,7 @@ val trim : t -> t val anchor : name:t -> t -> t ``` `anchor ~name:anchorName anchorText` creates a string with an HTML `` element with `name` attribute of `anchorName` and `anchorText` as its content. + ```ocaml anchor ~name:"page1" "Page One" = "Page One" ``` @@ -394,6 +454,7 @@ deprecated This function is deprecated, see https://developer.mozilla.org/en-US/ val link : href:t -> t -> t ``` `link ~href:urlText linkText` creates a string with an HTML `` element with `href` attribute of `urlText` and `linkText` as its content. + ```ocaml link ~href:"page2.html" "Go to page two" = "Go to page two" ``` diff --git a/docs/api/melange/Js-Typed_array-ArrayBuffer.md b/docs/api/melange/Js-Typed_array-ArrayBuffer.md index 50d3ea15f..3331025db 100644 --- a/docs/api/melange/Js-Typed_array-ArrayBuffer.md +++ b/docs/api/melange/Js-Typed_array-ArrayBuffer.md @@ -1,5 +1,8 @@ + # Module `Typed_array.ArrayBuffer` + The underlying buffer that the typed arrays provide views of + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) MDN ``` type t = Js.arrayBuffer @@ -8,6 +11,7 @@ type t = Js.arrayBuffer val make : int -> t ``` takes length. initializes elements to 0 + ``` val byteLength : t -> int ``` diff --git a/docs/api/melange/Js-Typed_array-DataView.md b/docs/api/melange/Js-Typed_array-DataView.md index 02c62fac5..1d1ad1f0f 100644 --- a/docs/api/melange/Js-Typed_array-DataView.md +++ b/docs/api/melange/Js-Typed_array-DataView.md @@ -1,5 +1,8 @@ + # Module `Typed_array.DataView` + The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) MDN ``` type t diff --git a/docs/api/melange/Js-Typed_array-Float32Array.md b/docs/api/melange/Js-Typed_array-Float32Array.md index e1e08788f..77ea7f873 100644 --- a/docs/api/melange/Js-Typed_array-Float32Array.md +++ b/docs/api/melange/Js-Typed_array-Float32Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Float32Array` + ``` type elt = float ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Float64Array.md b/docs/api/melange/Js-Typed_array-Float64Array.md index e060e474a..47a2c9062 100644 --- a/docs/api/melange/Js-Typed_array-Float64Array.md +++ b/docs/api/melange/Js-Typed_array-Float64Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Float64Array` + ``` type elt = float ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Int16Array.md b/docs/api/melange/Js-Typed_array-Int16Array.md index d77ce67b4..efd85abba 100644 --- a/docs/api/melange/Js-Typed_array-Int16Array.md +++ b/docs/api/melange/Js-Typed_array-Int16Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Int16Array` + ``` type elt = int ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Int32Array.md b/docs/api/melange/Js-Typed_array-Int32Array.md index 6bf740756..459de0957 100644 --- a/docs/api/melange/Js-Typed_array-Int32Array.md +++ b/docs/api/melange/Js-Typed_array-Int32Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Int32Array` + ``` type elt = int32 ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Int8Array.md b/docs/api/melange/Js-Typed_array-Int8Array.md index 27ed0e8e0..fd129f858 100644 --- a/docs/api/melange/Js-Typed_array-Int8Array.md +++ b/docs/api/melange/Js-Typed_array-Int8Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Int8Array` + ``` type elt = int ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Uint16Array.md b/docs/api/melange/Js-Typed_array-Uint16Array.md index b707c4554..44568a6d6 100644 --- a/docs/api/melange/Js-Typed_array-Uint16Array.md +++ b/docs/api/melange/Js-Typed_array-Uint16Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Uint16Array` + ``` type elt = int ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Uint32Array.md b/docs/api/melange/Js-Typed_array-Uint32Array.md index 8bbb4b111..2faa8f753 100644 --- a/docs/api/melange/Js-Typed_array-Uint32Array.md +++ b/docs/api/melange/Js-Typed_array-Uint32Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Uint32Array` + ``` type elt = int ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Uint8Array.md b/docs/api/melange/Js-Typed_array-Uint8Array.md index 9a7a9fb6e..e3a3890d2 100644 --- a/docs/api/melange/Js-Typed_array-Uint8Array.md +++ b/docs/api/melange/Js-Typed_array-Uint8Array.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Uint8Array` + ``` type elt = int ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md b/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md index c3705dc55..27966ace2 100644 --- a/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md +++ b/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md @@ -1,4 +1,6 @@ + # Module `Typed_array.Uint8ClampedArray` + ``` type elt = int ``` @@ -66,6 +68,7 @@ val lastIndexOfFrom : value:elt -> from:int -> t -> int val slice : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val copy : t -> t ``` @@ -73,6 +76,7 @@ val copy : t -> t val subarray : ?start:int -> ?end_:int -> t -> t ``` `start` is inclusive, `end_` exclusive + ``` val toString : t -> string ``` diff --git a/docs/api/melange/Js-Typed_array.md b/docs/api/melange/Js-Typed_array.md index 0a25633c6..4716bb636 100644 --- a/docs/api/melange/Js-Typed_array.md +++ b/docs/api/melange/Js-Typed_array.md @@ -1,11 +1,16 @@ + # Module `Js.Typed_array` + Bindings to the functions in `TypedArray.prototype` + JavaScript Typed Array API + see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) MDN ``` module ArrayBuffer : sig ... end ``` The underlying buffer that the typed arrays provide views of + ``` module Int8Array : sig ... end ``` @@ -36,4 +41,4 @@ module Float64Array : sig ... end ``` module DataView : sig ... end ``` -The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. \ No newline at end of file +The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. diff --git a/docs/api/melange/Js-Types.md b/docs/api/melange/Js-Types.md index 768992327..d9e8e32ab 100644 --- a/docs/api/melange/Js-Types.md +++ b/docs/api/melange/Js-Types.md @@ -1,13 +1,18 @@ + # Module `Js.Types` + Utility functions for runtime reflection on JS types + ``` type symbol ``` Js symbol type only available in ES6 + ``` type bigint_val ``` Js bigint type only available in ES2020 + ``` type obj_val ``` @@ -15,10 +20,12 @@ type obj_val type undefined_val ``` This type has only one value `undefined` + ``` type null_val ``` This type has only one value `null` + ``` type function_val ``` diff --git a/docs/api/melange/Js-Undefined.md b/docs/api/melange/Js-Undefined.md index cc431b358..749c64f50 100644 --- a/docs/api/melange/Js-Undefined.md +++ b/docs/api/melange/Js-Undefined.md @@ -1,22 +1,30 @@ + # Module `Js.Undefined` + Utility functions on [`undefined`](./Js.md#type-undefined) + Provides functionality for dealing with the `'a Js.undefined` type + ``` type +'a t = 'a Js.undefined ``` Local alias for `'a Js.undefined` + ``` val return : 'a -> 'a t ``` Constructs a value of `'a Js.undefined` containing a value of `'a` + ``` val testAny : 'a -> bool ``` Returns `true` if the given value is `empty` (`undefined`) + ``` val empty : 'a t ``` The empty value, `undefined` + ``` val getUnsafe : 'a t -> 'a ``` @@ -30,7 +38,9 @@ val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t ``` Bind the contained value using the given function + If `'a Js.undefined` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.undefined` + ```ocaml let maybeGreetWorld (maybeGreeting: string Js.undefined) = Js.Undefined.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") @@ -39,7 +49,9 @@ let maybeGreetWorld (maybeGreeting: string Js.undefined) = val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit ``` Iterates over the contained value with the given function + If `'a Js.undefined` contains a value, that value is unwrapped and applied to the given function. + ```ocaml let maybeSay (maybeMessage: string Js.undefined) = Js.Undefined.iter maybeMessage ~f:(fun message -> Js.log message) @@ -49,6 +61,7 @@ val fromOption : 'a option -> 'a t ``` Maps `'a option` to `'a Js.undefined` +
Some a -> return a
None -> empty @@ -59,6 +72,7 @@ val toOption : 'a t -> 'a option ``` Maps `'a Js.undefined` to `'a option` +
return a -> Some a
empty -> None diff --git a/docs/api/melange/Js-WeakMap.md b/docs/api/melange/Js-WeakMap.md index 00b9e32c9..a997042d8 100644 --- a/docs/api/melange/Js-WeakMap.md +++ b/docs/api/melange/Js-WeakMap.md @@ -1,6 +1,10 @@ + # Module `Js.WeakMap` + Bindings to functions in `WeakMap` + ES6 WeakMap API + ``` type ('k, 'v) t ``` diff --git a/docs/api/melange/Js-WeakSet.md b/docs/api/melange/Js-WeakSet.md index 5d8dfb549..a7f07d2ea 100644 --- a/docs/api/melange/Js-WeakSet.md +++ b/docs/api/melange/Js-WeakSet.md @@ -1,6 +1,10 @@ + # Module `Js.WeakSet` + Bindings to functions in `WeakSet` + ES6 WeakSet API + ``` type 'a t ``` diff --git a/docs/api/melange/Js.md b/docs/api/melange/Js.md index 641dfc46c..06b1fd244 100644 --- a/docs/api/melange/Js.md +++ b/docs/api/melange/Js.md @@ -1,48 +1,61 @@ + # Module `Js` + ``` type +'a null ``` A value of this type can be either `null` or `'a`. This type is the same as type `t` in [`Null`](./Js-Null.md) + ``` type +'a undefined ``` A value of this type can be either `undefined` or `'a`. This type is the same as type `t` in [`Undefined`](./Js-Undefined.md) + ``` type +'a nullable ``` A value of this type can be `undefined`, `null` or `'a`. This type is the same as type `t` n [`Nullable`](./Js-Nullable.md) + ``` type re ``` The type for JavaScript `RegExp` + ``` type 'a dict ``` The type for a simple key-value dictionary abstraction over native JavaScript objects + ``` type 'a iterator ``` The type for JavaScript iterators + ``` type 'a array_like ``` The type for array-like objects in JavaScript + ``` type bigint ``` The type for JavaScript BigInt + ``` type +'a promise ``` The type for JavaScript Promise + ``` type blob ``` The type for JavaScript [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + ``` type file ``` The type for JavaScript [File](https://developer.mozilla.org/en-US/docs/Web/API/File) + ``` type arrayBuffer ``` @@ -89,26 +102,32 @@ val isNullable : 'a nullable -> bool val import : 'a -> 'a promise ``` TODO(anmonteiro): document + ``` val testAny : 'a -> bool ``` The same as [`isNullable`](./#val-isNullable) except that it is more permissive on the types of input + ``` val null : 'a null ``` The same as `empty` in [`Js.Null`](./Js-Null.md) will be compiled as `null` + ``` val undefined : 'a undefined ``` The same as `empty` [`Js.Undefined`](./Js-Undefined.md) will be compiled as `undefined` + ``` val typeof : 'a -> string ``` `typeof x` will be compiled as `typeof x` in JS Please consider functions in [`Types`](./Js-Types.md) for a type safe way of reflection + ``` val log : 'a -> unit ``` A convenience function to log everything + ``` val log2 : 'a -> 'b -> unit ``` @@ -122,6 +141,7 @@ val log4 : 'a -> 'b -> 'c -> 'd -> unit val logMany : 'a array -> unit ``` A convenience function to log more than 4 arguments + ``` val eqNull : 'a -> 'a null -> bool ``` @@ -131,104 +151,131 @@ val eqUndefined : 'a -> 'a undefined -> bool ``` val eqNullable : 'a -> 'a nullable -> bool ``` + ##### Operators + ``` val unsafe_lt : 'a -> 'a -> bool ``` `unsafe_lt a b` will be compiled as `a < b`. It is marked as unsafe, since it is impossible to give a proper semantics for comparision which applies to any type + ``` val unsafe_le : 'a -> 'a -> bool ``` `unsafe_le a b` will be compiled as `a <= b`. See also [`unsafe_lt`](./#val-unsafe_lt) + ``` val unsafe_gt : 'a -> 'a -> bool ``` `unsafe_gt a b` will be compiled as `a > b`. See also [`unsafe_lt`](./#val-unsafe_lt) + ``` val unsafe_ge : 'a -> 'a -> bool ``` `unsafe_ge a b` will be compiled as `a >= b`. See also [`unsafe_lt`](./#val-unsafe_lt) + Types for JS objects + ``` type 'a t ``` This used to be mark a Js object type. + ``` module Exn : sig ... end ``` Utilities for dealing with Js exceptions + ``` module String : sig ... end ``` Bindings to the functions in `String.prototype` + ``` module Null : sig ... end ``` Utility functions on [`null`](./#type-null) + ``` module Undefined : sig ... end ``` Utility functions on [`undefined`](./#type-undefined) + ``` module Nullable : sig ... end ``` Utility functions on [`nullable`](./#type-nullable) + ``` module Array : sig ... end ``` Bindings to the functions in `Array.prototype` + ``` module Re : sig ... end ``` Bindings to the functions in `RegExp.prototype` + ``` module Promise : sig ... end ``` Bindings to JS `Promise` functions + ``` module Date : sig ... end ``` Bindings to the functions in JS's `Date.prototype` + ``` module Dict : sig ... end ``` Utility functions to treat a JS object as a dictionary + ``` module Global : sig ... end ``` Bindings to functions in the JS global namespace + ``` module Json : sig ... end ``` Utility functions to manipulate JSON values + ``` module Math : sig ... end ``` Bindings to the functions in the `Math` object + ``` module Obj : sig ... end ``` Utility functions on \`Js.t\` JS objects + ``` module Typed_array : sig ... end ``` Bindings to the functions in `TypedArray.prototype` + ``` module Types : sig ... end ``` Utility functions for runtime reflection on JS types + ``` module Float : sig ... end ``` Bindings to functions in JavaScript's `Number` that deal with floats + ``` module Int : sig ... end ``` Bindings to functions in JavaScript's `Number` that deal with ints + ``` module Bigint : sig ... end ``` Bindings to functions in JavaScript's `BigInt` + ``` module Console : sig ... end ``` @@ -236,31 +283,38 @@ module Console : sig ... end module Set : sig ... end ``` Bindings to functions in `Set` + ``` module WeakSet : sig ... end ``` Bindings to functions in `WeakSet` + ``` module Map : sig ... end ``` Bindings to functions in `Map` + ``` module WeakMap : sig ... end ``` Bindings to functions in `WeakMap` + ``` module Iterator : sig ... end ``` Bindings to functions on `Iterator` + ``` module Blob : sig ... end ``` Bindings to Blob + ``` module File : sig ... end ``` Bindings to File + ``` module FormData : sig ... end ``` -Bindings to FormData \ No newline at end of file +Bindings to FormData diff --git a/docs/api/melange/Node-Buffer.md b/docs/api/melange/Node-Buffer.md index 42d07998a..3488b30f6 100644 --- a/docs/api/melange/Node-Buffer.md +++ b/docs/api/melange/Node-Buffer.md @@ -1,5 +1,8 @@ + # Module `Node.Buffer` + Node Buffer API + ``` type t = Node.buffer ``` diff --git a/docs/api/melange/Node-Child_process.md b/docs/api/melange/Node-Child_process.md index 04e8a7034..5a3630c8c 100644 --- a/docs/api/melange/Node-Child_process.md +++ b/docs/api/melange/Node-Child_process.md @@ -1,5 +1,8 @@ + # Module `Node.Child_process` + Node Child Process API + ``` type option ``` diff --git a/docs/api/melange/Node-Fs-Watch.md b/docs/api/melange/Node-Fs-Watch.md index 96eab747a..581d242fa 100644 --- a/docs/api/melange/Node-Fs-Watch.md +++ b/docs/api/melange/Node-Fs-Watch.md @@ -1,4 +1,6 @@ + # Module `Fs.Watch` + ``` type t ``` @@ -17,6 +19,7 @@ val config : val watch : string -> ?config:config -> unit -> t ``` there is no need to accept listener, since we return a `watcher` back it can register event listener there. Currently we introduce a type `string_buffer`, for the `filename`, it will be `Buffer` when the encoding is `` `utf8 ``. This is dependent type which can be tracked by GADT in some way, but to make things simple, let's just introduce an or type + ``` val on : t -> diff --git a/docs/api/melange/Node-Fs.md b/docs/api/melange/Node-Fs.md index c3dbd68e0..b437a848f 100644 --- a/docs/api/melange/Node-Fs.md +++ b/docs/api/melange/Node-Fs.md @@ -1,10 +1,14 @@ + # Module `Node.Fs` + Node FS API + see [https://blogs.janestreet.com/a-and-a/](https://blogs.janestreet.com/a-and-a/) refernce documentation ``` val readdirSync : string -> string array ``` Most fs functions let you omit the callback argument. If you do, a default callback is used that rethrows errors. To get a trace to the original call site, set the \`NODE\_DEBUG\` environment variable. + ``` val renameSync : string -> string -> unit ``` @@ -15,6 +19,7 @@ type fd = private int type path = string ``` The relative path to a filename can be used. Remember, however, that this path will be relative to `process.cwd()`. + ``` module Watch : sig ... end ``` diff --git a/docs/api/melange/Node-Module.md b/docs/api/melange/Node-Module.md index 0cf22c308..26dbe1439 100644 --- a/docs/api/melange/Node-Module.md +++ b/docs/api/melange/Node-Module.md @@ -1,5 +1,8 @@ + # Module `Node.Module` + Node Module API + ``` val module_ : < __cache : Node.node_module Js.Dict.t > Js.t ``` \ No newline at end of file diff --git a/docs/api/melange/Node-Path.md b/docs/api/melange/Node-Path.md index 083fb8e33..0d7ebfd71 100644 --- a/docs/api/melange/Node-Path.md +++ b/docs/api/melange/Node-Path.md @@ -1,5 +1,8 @@ + # Module `Node.Path` + Node Path API + ``` val basename : string -> string ``` diff --git a/docs/api/melange/Node-Process.md b/docs/api/melange/Node-Process.md index d359e26d3..f2714be7b 100644 --- a/docs/api/melange/Node-Process.md +++ b/docs/api/melange/Node-Process.md @@ -1,4 +1,6 @@ + # Module `Node.Process` + ``` type t = < argv : string array @@ -27,6 +29,7 @@ val cwd : unit -> string val uptime : t -> unit -> float ``` The process.uptime() method returns the number of seconds the current Node.js process has been running.) + ``` val putEnvVar : string -> string -> unit ``` diff --git a/docs/api/melange/Node.md b/docs/api/melange/Node.md index 2b7829da6..2730c44a9 100644 --- a/docs/api/melange/Node.md +++ b/docs/api/melange/Node.md @@ -1,4 +1,6 @@ + # Module `Node` + ``` type node_exports ``` @@ -41,14 +43,17 @@ type _ string_buffer_kind = val test : string_buffer -> 't string_buffer_kind * 't ``` We expect a good inliner will eliminate such boxing in the future + ``` module Path : sig ... end ``` Node Path API + ``` module Fs : sig ... end ``` Node FS API + ``` module Process : sig ... end ``` @@ -56,11 +61,13 @@ module Process : sig ... end module Module : sig ... end ``` Node Module API + ``` module Buffer : sig ... end ``` Node Buffer API + ``` module Child_process : sig ... end ``` -Node Child Process API \ No newline at end of file +Node Child Process API diff --git a/docs/api/melange/Stdlib-Arg.md b/docs/api/melange/Stdlib-Arg.md index 330c16a09..9688b86ce 100644 --- a/docs/api/melange/Stdlib-Arg.md +++ b/docs/api/melange/Stdlib-Arg.md @@ -1,6 +1,10 @@ + # Module `Stdlib.Arg` + Parsing of command line arguments. + This module provides a general mechanism for extracting options and arguments from the command line to the program. For example: + ```ocaml let usage_msg = "append [-verbose] [] ... -o " let verbose = ref false @@ -19,10 +23,15 @@ This module provides a general mechanism for extracting options and arguments fr (* Main functionality here *) ``` Syntax of command lines: A keyword is a character string starting with a `-`. An option is a keyword alone or followed by an argument. The types of keywords are: `Unit`, `Bool`, `Set`, `Clear`, `String`, `Set_string`, `Int`, `Set_int`, `Float`, `Set_float`, `Tuple`, `Symbol`, `Rest`, `Rest_all` and `Expand`. + `Unit`, `Set` and `Clear` keywords take no argument. + A `Rest` or `Rest_all` keyword takes the remainder of the command line as arguments. (More explanations below.) + Every other keyword takes the following word on the command line as argument. For compatibility with GNU getopt\_long, `keyword=arg` is also allowed. Arguments not preceded by a keyword are called anonymous arguments. + Examples (`cmd` is assumed to be the command name): + - `cmd -flag `(a unit option) - `cmd -int 1 `(an int option with argument `1`) - `cmd -string foobar `(a string option with argument `"foobar"`) @@ -30,7 +39,9 @@ Examples (`cmd` is assumed to be the command name): - `cmd a b c `(three anonymous arguments: `"a"`, `"b"`, and `"c"`) - `cmd a b -- c d `(two anonymous arguments and a rest option with two arguments) `Rest` takes a function that is called repeatedly for each remaining command line argument. `Rest_all` takes a function that is called once, with the list of all remaining arguments. + Note that if no arguments follow a `Rest` keyword then the function is not called at all whereas the function for a `Rest_all` keyword is called with an empty list. + alert unsynchronized\_access The Arg module relies on a mutable global state, parsing functions should only be called from a single domain. ``` type spec = @@ -39,66 +50,82 @@ type spec = | Unit of unit -> unit ``` Call the function with unit argument + ``` | Bool of bool -> unit ``` Call the function with a bool argument + ``` | Set of bool ref ``` Set the reference to true + ``` | Clear of bool ref ``` Set the reference to false + ``` | String of string -> unit ``` Call the function with a string argument + ``` | Set_string of string ref ``` Set the reference to the string argument + ``` | Int of int -> unit ``` Call the function with an int argument + ``` | Set_int of int ref ``` Set the reference to the int argument + ``` | Float of float -> unit ``` Call the function with a float argument + ``` | Set_float of float ref ``` Set the reference to the float argument + ``` | Tuple of spec list ``` Take several arguments according to the spec list + ``` | Symbol of string list * string -> unit ``` Take one of the symbols as argument and call the function with the symbol + ``` | Rest of string -> unit ``` Stop interpreting keywords and call the function with each remaining argument + ``` | Rest_all of string list -> unit ``` Stop interpreting keywords and call the function with all remaining arguments + ``` | Expand of string -> string array ``` If the remaining arguments to process are of the form `["-foo"; "arg"] @ rest` where "foo" is registered as `Expand f`, then the arguments `f "arg" @ rest` are processed. Only allowed in `parse_and_expand_argv_dynamic`. + ``` ``` The concrete type describing the behavior associated with a keyword. + ``` type key = string ``` @@ -115,12 +142,16 @@ type anon_fun = string -> unit val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit ``` `Arg.parse speclist anon_fun usage_msg` parses the command line. `speclist` is a list of triples `(key, spec, doc)`. `key` is the option keyword, it must start with a `'-'` character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon_fun` is called on anonymous arguments. The functions in `spec` and `anon_fun` are called in the same order as their arguments appear on the command line. + If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows: + - The reason for the error: unknown option, invalid or missing argument, etc. - `usage_msg` - The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list. For the user to be able to specify anonymous arguments starting with a `-`, include for example `("-", String anon_fun, doc)` in `speclist`. + By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage_msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`. + ``` val parse_dynamic : (key * spec * doc) list ref -> @@ -129,6 +160,7 @@ val parse_dynamic : unit ``` Same as [`Arg.parse`](./#val-parse), except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form: + - command subcommand `options` where the list of options depends on the value of the subcommand argument. since 4.01 ``` @@ -141,6 +173,7 @@ val parse_argv : unit ``` `Arg.parse_argv ~current args speclist anon_fun usage_msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or [`Arg.current`](./#val-current). You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises [`Arg.Bad`](./#exception-Bad) with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises [`Arg.Help`](./#exception-Help) with the help message as argument. + ``` val parse_argv_dynamic : ?current:int ref -> @@ -151,6 +184,7 @@ val parse_argv_dynamic : unit ``` Same as [`Arg.parse_argv`](./#val-parse_argv), except that the `speclist` argument is a reference and may be updated during the parsing. See [`Arg.parse_dynamic`](./#val-parse_dynamic). + since 4.01 ``` val parse_and_expand_argv_dynamic : @@ -162,54 +196,66 @@ val parse_and_expand_argv_dynamic : unit ``` Same as [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic), except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic). + since 4.05 ``` val parse_expand : (key * spec * doc) list -> anon_fun -> usage_msg -> unit ``` Same as [`Arg.parse`](./#val-parse), except that the `Expand` arguments are allowed and the [`current`](./#val-current) reference is not updated. + since 4.05 ``` exception Help of string ``` Raised by `Arg.parse_argv` when the user asks for help. + ``` exception Bad of string ``` Functions in `spec` or `anon_fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by [`Arg.parse_argv`](./#val-parse_argv) in case of an error. + ``` val usage : (key * spec * doc) list -> usage_msg -> unit ``` `Arg.usage speclist usage_msg` prints to standard error an error message that includes the list of valid options. This is the same message that [`Arg.parse`](./#val-parse) prints in case of error. `speclist` and `usage_msg` are the same as for [`Arg.parse`](./#val-parse). + ``` val usage_string : (key * spec * doc) list -> usage_msg -> string ``` Returns the message that would have been printed by [`Arg.usage`](./#val-usage), if provided with the same parameters. + ``` val align : ?limit:int -> (key * spec * doc) list -> (key * spec * doc) list ``` Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line. + parameter limit options with keyword and message longer than limit will not be used to compute the alignment. ``` val current : int ref ``` Position (in [`Sys.argv`](./Stdlib-Sys.md#val-argv)) of the argument being processed. You can change this value, e.g. to force [`Arg.parse`](./#val-parse) to skip some arguments. [`Arg.parse`](./#val-parse) uses the initial value of [`Arg.current`](./#val-current) as the index of argument 0 (the program name) and starts parsing arguments at the next element. + ``` val read_arg : string -> string array ``` `Arg.read_arg file` reads newline-terminated command line arguments from file `file`. + since 4.05 ``` val read_arg0 : string -> string array ``` Identical to [`Arg.read_arg`](./#val-read_arg) but assumes null character terminated command line arguments. + since 4.05 ``` val write_arg : string -> string array -> unit ``` `Arg.write_arg file args` writes the arguments `args` newline-terminated into the file `file`. If any of the arguments in `args` contains a newline, use [`Arg.write_arg0`](./#val-write_arg0) instead. + since 4.05 ``` val write_arg0 : string -> string array -> unit ``` Identical to [`Arg.write_arg`](./#val-write_arg) but uses the null character for terminator instead of newline. + since 4.05 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Array.md b/docs/api/melange/Stdlib-Array.md index 592e665a1..9653f6b3d 100644 --- a/docs/api/melange/Stdlib-Array.md +++ b/docs/api/melange/Stdlib-Array.md @@ -1,118 +1,148 @@ + # Module `Stdlib.Array` + Array operations. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + ``` type 'a t = 'a array ``` An alias for the type of arrays. + ``` val length : 'a array -> int ``` Return the length (number of elements) of the given array. + ``` val get : 'a array -> int -> 'a ``` `get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). ``` val set : 'a array -> int -> 'a -> unit ``` `set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. ``` val make : int -> 'a -> 'a array ``` `make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. ``` val create_float : int -> float array ``` `create_float n` returns a fresh float array of length `n`, with uninitialized data. + since 4.03 ``` val init : int -> (int -> 'a) -> 'a array ``` `init n f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. ``` val make_matrix : int -> int -> 'a -> 'a array array ``` `make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. ``` val init_matrix : int -> int -> (int -> int -> 'a) -> 'a array array ``` `init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. since 5.2 ``` val append : 'a array -> 'a array -> 'a array ``` `append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. ``` val concat : 'a array list -> 'a array ``` Same as [`append`](./#val-append), but concatenates a list of arrays. + ``` val sub : 'a array -> int -> int -> 'a array ``` `sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. ``` val copy : 'a array -> 'a array ``` `copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. + ``` val fill : 'a array -> int -> int -> 'a -> unit ``` `fill a pos len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. ``` val blit : 'a array -> int -> 'a array -> int -> int -> unit ``` `blit src src_pos dst dst_pos len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. ``` val to_list : 'a array -> 'a list ``` `to_list a` returns the list of all the elements of `a`. + ``` val of_list : 'a list -> 'a array ``` `of_list l` returns a fresh array containing the elements of `l`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. + ## Iterators + ``` val iter : ('a -> unit) -> 'a array -> unit ``` `iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. + ``` val iteri : (int -> 'a -> unit) -> 'a array -> unit ``` Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. + ``` val map : ('a -> 'b) -> 'a array -> 'b array ``` `map f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. + ``` val map_inplace : ('a -> 'a) -> 'a array -> unit ``` `map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. + since 5.1 ``` val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array ``` Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. + ``` val mapi_inplace : (int -> 'a -> 'a) -> 'a array -> unit ``` Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. + since 5.1 ``` val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a array -> 'acc ``` `fold_left f init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. + ``` val fold_left_map : ('acc -> 'a -> 'acc * 'b) -> @@ -121,136 +151,182 @@ val fold_left_map : 'acc * 'b array ``` `fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. + since 4.13 ``` val fold_right : ('a -> 'acc -> 'acc) -> 'a array -> 'acc -> 'acc ``` `fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. + + ## Iterators on two arrays + ``` val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit ``` `iter2 f a b` applies function `f` to all the elements of `a` and `b`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. since 4.03 (4.05 in ArrayLabels) ``` val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array ``` `map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. since 4.03 (4.05 in ArrayLabels) + ## Array scanning + ``` val for_all : ('a -> bool) -> 'a array -> bool ``` `for_all f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. + since 4.03 ``` val exists : ('a -> bool) -> 'a array -> bool ``` `exists f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. + since 4.03 ``` val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool ``` Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. since 4.11 ``` val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool ``` Same as [`exists`](./#val-exists), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. since 4.11 ``` val mem : 'a -> 'a array -> bool ``` `mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). + since 4.03 ``` val memq : 'a -> 'a array -> bool ``` Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. + since 4.03 ``` val find_opt : ('a -> bool) -> 'a array -> 'a option ``` `find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. + since 4.13 ``` val find_index : ('a -> bool) -> 'a array -> int option ``` `find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + It returns `None` if there is no such element. + since 5.1 ``` val find_map : ('a -> 'b option) -> 'a array -> 'b option ``` `find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. + since 4.13 ``` val find_mapi : (int -> 'a -> 'b option) -> 'a array -> 'b option ``` Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 5.1 + ## Arrays of pairs + ``` val split : ('a * 'b) array -> 'a array * 'b array ``` `split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. + since 4.13 ``` val combine : 'a array -> 'b array -> ('a * 'b) array ``` `combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. + since 4.13 + ## Sorting and shuffling + ``` val sort : ('a -> 'a -> int) -> 'a array -> unit ``` Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. + The current implementation uses Heap Sort. It runs in constant stack space. + Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : + - `cmp x y` \> 0 if and only if `cmp y x` \< 0 - if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : + - `cmp a.(i) a.(j)` \>= 0 if i \>= j ``` val stable_sort : ('a -> 'a -> int) -> 'a array -> unit ``` Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. + The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). + ``` val fast_sort : ('a -> 'a -> int) -> 'a array -> unit ``` Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + ``` val shuffle : rand:(int -> int) -> 'a array -> unit ``` `shuffle rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. + `rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). + since 5.2 + ## Arrays and Sequences + ``` val to_seq : 'a array -> 'a Seq.t ``` Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. + since 4.07 ``` val to_seqi : 'a array -> (int * 'a) Seq.t ``` Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. + since 4.07 ``` val of_seq : 'a Seq.t -> 'a array ``` Create an array from the generator + since 4.07 + ## Arrays and concurrency safety + Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + ### Atomicity + Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. + For example, consider the following program: + ```ocaml let size = 100_000_000 let a = Array.make size 1 @@ -263,15 +339,27 @@ let d2 = Domain.spawn (fun () -> let () = Domain.join d1; Domain.join d2 ``` After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ### Data races + If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. + Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). + + ### Float arrays + Float arrays have two supplementary caveats in the presence of data races. + First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. + For instance, at the end of + ```ocaml let zeros = Array.make size 0. let max_floats = Array.make size Float.max_float @@ -281,4 +369,5 @@ let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) let () = Domain.join d1; Domain.join d2 ``` the `res` array might contain values that are neither `0.` nor `max_float`. -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. \ No newline at end of file + +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/melange/Stdlib-ArrayLabels.md b/docs/api/melange/Stdlib-ArrayLabels.md index 686488d76..22c66dcff 100644 --- a/docs/api/melange/Stdlib-ArrayLabels.md +++ b/docs/api/melange/Stdlib-ArrayLabels.md @@ -1,43 +1,55 @@ + # Module `Stdlib.ArrayLabels` + Array operations. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + ``` type 'a t = 'a array ``` An alias for the type of arrays. + ``` val length : 'a array -> int ``` Return the length (number of elements) of the given array. + ``` val get : 'a array -> int -> 'a ``` `get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). ``` val set : 'a array -> int -> 'a -> unit ``` `set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. ``` val make : int -> 'a -> 'a array ``` `make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. ``` val create_float : int -> float array ``` `create_float n` returns a fresh float array of length `n`, with uninitialized data. + since 4.03 ``` val init : int -> f:(int -> 'a) -> 'a array ``` `init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. ``` val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array ``` `make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. ``` val init_matrix : @@ -47,30 +59,36 @@ val init_matrix : 'a array array ``` `init_matrix ~dimx ~dimy ~f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. since 5.2 ``` val append : 'a array -> 'a array -> 'a array ``` `append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. ``` val concat : 'a array list -> 'a array ``` Same as [`append`](./#val-append), but concatenates a list of arrays. + ``` val sub : 'a array -> pos:int -> len:int -> 'a array ``` `sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. ``` val copy : 'a array -> 'a array ``` `copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. + ``` val fill : 'a array -> pos:int -> len:int -> 'a -> unit ``` `fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. ``` val blit : @@ -82,47 +100,59 @@ val blit : unit ``` `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. ``` val to_list : 'a array -> 'a list ``` `to_list a` returns the list of all the elements of `a`. + ``` val of_list : 'a list -> 'a array ``` `of_list l` returns a fresh array containing the elements of `l`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. + ## Iterators + ``` val iter : f:('a -> unit) -> 'a array -> unit ``` `iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. + ``` val iteri : f:(int -> 'a -> unit) -> 'a array -> unit ``` Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. + ``` val map : f:('a -> 'b) -> 'a array -> 'b array ``` `map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. + ``` val map_inplace : f:('a -> 'a) -> 'a array -> unit ``` `map_inplace ~f a` applies function `f` to all elements of `a`, and updates their values in place. + since 5.1 ``` val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array ``` Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. + ``` val mapi_inplace : f:(int -> 'a -> 'a) -> 'a array -> unit ``` Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. + since 5.1 ``` val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'acc ``` `fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. + ``` val fold_left_map : f:('acc -> 'a -> 'acc * 'b) -> @@ -131,136 +161,182 @@ val fold_left_map : 'acc * 'b array ``` `fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. + since 4.13 ``` val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> init:'acc -> 'acc ``` `fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. + + ## Iterators on two arrays + ``` val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit ``` `iter2 ~f a b` applies function `f` to all the elements of `a` and `b`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. since 4.03 (4.05 in ArrayLabels) ``` val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array ``` `map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. since 4.03 (4.05 in ArrayLabels) + ## Array scanning + ``` val for_all : f:('a -> bool) -> 'a array -> bool ``` `for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. + since 4.03 ``` val exists : f:('a -> bool) -> 'a array -> bool ``` `exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. + since 4.03 ``` val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool ``` Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. since 4.11 ``` val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool ``` Same as [`exists`](./#val-exists), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. since 4.11 ``` val mem : 'a -> set:'a array -> bool ``` `mem a ~set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). + since 4.03 ``` val memq : 'a -> set:'a array -> bool ``` Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. + since 4.03 ``` val find_opt : f:('a -> bool) -> 'a array -> 'a option ``` `find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. + since 4.13 ``` val find_index : f:('a -> bool) -> 'a array -> int option ``` `find_index ~f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + It returns `None` if there is no such element. + since 5.1 ``` val find_map : f:('a -> 'b option) -> 'a array -> 'b option ``` `find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. + since 4.13 ``` val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> 'b option ``` Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 5.1 + ## Arrays of pairs + ``` val split : ('a * 'b) array -> 'a array * 'b array ``` `split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. + since 4.13 ``` val combine : 'a array -> 'b array -> ('a * 'b) array ``` `combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. + since 4.13 + ## Sorting and shuffling + ``` val sort : cmp:('a -> 'a -> int) -> 'a array -> unit ``` Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. + The current implementation uses Heap Sort. It runs in constant stack space. + Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : + - `cmp x y` \> 0 if and only if `cmp y x` \< 0 - if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : + - `cmp a.(i) a.(j)` \>= 0 if i \>= j ``` val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit ``` Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. + The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). + ``` val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit ``` Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + ``` val shuffle : rand:(int -> int) -> 'a array -> unit ``` `shuffle ~rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. + `rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). + since 5.2 + ## Arrays and Sequences + ``` val to_seq : 'a array -> 'a Seq.t ``` Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. + since 4.07 ``` val to_seqi : 'a array -> (int * 'a) Seq.t ``` Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. + since 4.07 ``` val of_seq : 'a Seq.t -> 'a array ``` Create an array from the generator + since 4.07 + ## Arrays and concurrency safety + Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + ### Atomicity + Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. + For example, consider the following program: + ```ocaml let size = 100_000_000 let a = ArrayLabels.make size 1 @@ -273,15 +349,27 @@ let d2 = Domain.spawn (fun () -> let () = Domain.join d1; Domain.join d2 ``` After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ### Data races + If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. + Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). + + ### Float arrays + Float arrays have two supplementary caveats in the presence of data races. + First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. + For instance, at the end of + ```ocaml let zeros = Array.make size 0. let max_floats = Array.make size Float.max_float @@ -291,4 +379,5 @@ let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) let () = Domain.join d1; Domain.join d2 ``` the `res` array might contain values that are neither `0.` nor `max_float`. -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. \ No newline at end of file + +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/melange/Stdlib-Atomic.md b/docs/api/melange/Stdlib-Atomic.md index 22b9265cd..1fc036d20 100644 --- a/docs/api/melange/Stdlib-Atomic.md +++ b/docs/api/melange/Stdlib-Atomic.md @@ -1,50 +1,72 @@ + # Module `Stdlib.Atomic` + Atomic references. + See [the examples](./#examples) below. See 'Memory model: The hard bits' chapter in the manual. + since 4.12 ``` type !'a t ``` An atomic (mutable) reference to a value of type `'a`. + ``` val make : 'a -> 'a t ``` Create an atomic reference. + Create an atomic reference that is alone on a cache line. It occupies 4-16x the memory of one allocated with `make v`. + The primary purpose is to prevent false-sharing and the resulting performance degradation. When a CPU performs an atomic operation, it temporarily takes ownership of an entire cache line that contains the atomic reference. If multiple atomic references share the same cache line, modifying these disjoint memory regions simultaneously becomes impossible, which can create a bottleneck. Hence, as a general guideline, if an atomic reference is experiencing contention, assigning it its own cache line may enhance performance. + ``` val get : 'a t -> 'a ``` Get the current value of the atomic reference. + ``` val set : 'a t -> 'a -> unit ``` Set a new value for the atomic reference. + ``` val exchange : 'a t -> 'a -> 'a ``` Set a new value for the atomic reference, and return the current value. + ``` val compare_and_set : 'a t -> 'a -> 'a -> bool ``` `compare_and_set r seen v` sets the new value of `r` to `v` only if its current value is physically equal to `seen` \-- the comparison and the set occur atomically. Returns `true` if the comparison succeeded (so the set happened) and `false` otherwise. + ``` val fetch_and_add : int t -> int -> int ``` `fetch_and_add r n` atomically increments the value of `r` by `n`, and returns the current value (before the increment). + ``` val incr : int t -> unit ``` `incr r` atomically increments the value of `r` by `1`. + ``` val decr : int t -> unit ``` `decr r` atomically decrements the value of `r` by `1`. + + ## Examples + + ### Basic Thread Coordination + A basic use case is to have global counters that are updated in a thread-safe way, for example to keep some sorts of metrics over IOs performed by the program. Another basic use case is to coordinate the termination of threads in a given program, for example when one thread finds an answer, or when the program is shut down by the user. + Here, for example, we're going to try to find a number whose hash satisfies a basic property. To do that, we'll run multiple threads which will try random numbers until they find one that works. + Of course the output below is a sample run and will change every time the program is run. + ```ocaml (* use for termination *) let stop_all_threads = Atomic.make false @@ -83,9 +105,13 @@ let () = found 1651745641680046833 (hash=33) total number of attempts: 30230350 ``` + ### Treiber Stack + Another example is a basic [Treiber stack](https://en.wikipedia.org/wiki/Treiber_stack) (a thread-safe stack) that can be safely shared between threads. + Note how both `push` and `pop` are recursive, because they attempt to swap the new stack (with one more, or one fewer, element) with the old stack. This is optimistic concurrency: each iteration of, say, `push stack x` gets the old stack `l`, and hopes that by the time it tries to replace `l` with `x::l`, nobody else has had time to modify the list. If the `compare_and_set` fails it means we were too optimistic, and must try again. + ```ocaml type 'a stack = 'a list Atomic.t diff --git a/docs/api/melange/Stdlib-Bool.md b/docs/api/melange/Stdlib-Bool.md index 91ffeda60..d6f379425 100644 --- a/docs/api/melange/Stdlib-Bool.md +++ b/docs/api/melange/Stdlib-Bool.md @@ -1,7 +1,12 @@ + # Module `Stdlib.Bool` + Boolean values. + since 4.08 + ## Booleans + ``` type t = bool = ``` @@ -15,48 +20,64 @@ type t = bool = ``` The type of booleans (truth values). + The constructors `false` and `true` are included here so that they have paths, but they are not intended to be used in user-defined data types. + ``` val not : bool -> bool ``` `not b` is the boolean negation of `b`. + ``` val (&&) : bool -> bool -> bool ``` `e0 && e1` is the lazy boolean conjunction of expressions `e0` and `e1`. If `e0` evaluates to `false`, `e1` is not evaluated. Right-associative operator at precedence level 3/11. + ``` val (||) : bool -> bool -> bool ``` `e0 || e1` is the lazy boolean disjunction of expressions `e0` and `e1`. If `e0` evaluates to `true`, `e1` is not evaluated. Right-associative operator at precedence level 2/11. + + ## Predicates and comparisons + ``` val equal : bool -> bool -> bool ``` `equal b0 b1` is `true` if and only if `b0` and `b1` are both `true` or both `false`. + ``` val compare : bool -> bool -> int ``` `compare b0 b1` is a total order on boolean values. `false` is smaller than `true`. + + ## Converting + ``` val to_int : bool -> int ``` `to_int b` is `0` if `b` is `false` and `1` if `b` is `true`. + ``` val to_float : bool -> float ``` `to_float b` is `0.` if `b` is `false` and `1.` if `b` is `true`. + ``` val to_string : bool -> string ``` `to_string b` is `"true"` if `b` is `true` and `"false"` if `b` is `false`. + ``` val seeded_hash : int -> bool -> int ``` A seeded hash function for booleans, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.1 ``` val hash : bool -> int ``` An unseeded hash function for booleans, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Buffer.md b/docs/api/melange/Stdlib-Buffer.md index a4a8fe016..9af9a8328 100644 --- a/docs/api/melange/Stdlib-Buffer.md +++ b/docs/api/melange/Stdlib-Buffer.md @@ -1,6 +1,10 @@ + # Module `Stdlib.Buffer` + Extensible buffers. + This module implements buffers that automatically expand as necessary. It provides accumulative concatenation of strings in linear time (instead of quadratic time when strings are concatenated pairwise). For example: + ```ocaml let concat_strings ss = let b = Buffer.create 16 in @@ -9,214 +13,270 @@ This module implements buffers that automatically expand as necessary. It provid ``` **Unsynchronized accesses** + Unsynchronized accesses to a buffer may lead to an invalid buffer state. Thus, concurrent accesses to a buffer must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + ``` type t ``` The abstract type of buffers. + ``` val create : int -> t ``` `create n` returns a fresh buffer, initially empty. The `n` parameter is the initial size of the internal byte sequence that holds the buffer contents. That byte sequence is automatically reallocated when more than `n` characters are stored in the buffer, but shrinks back to `n` characters when `reset` is called. For best performance, `n` should be of the same order of magnitude as the number of characters that are expected to be stored in the buffer (for instance, 80 for a buffer that holds one output line). Nothing bad will happen if the buffer grows beyond that limit, however. In doubt, take `n = 16` for instance. If `n` is not between 1 and [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length), it will be clipped to that interval. + ``` val contents : t -> string ``` Return a copy of the current contents of the buffer. The buffer itself is unchanged. + ``` val to_bytes : t -> bytes ``` Return a copy of the current contents of the buffer. The buffer itself is unchanged. + since 4.02 ``` val sub : t -> int -> int -> string ``` `Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off and len do not designate a valid range of b. ``` val blit : t -> int -> bytes -> int -> int -> unit ``` `Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if srcoff and len do not designate a valid range of src, or if dstoff and len do not designate a valid range of dst. since 3.11.2 ``` val nth : t -> int -> char ``` Get the n-th character of the buffer. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if index out of bounds ``` val length : t -> int ``` Return the number of characters currently contained in the buffer. + ``` val clear : t -> unit ``` Empty the buffer. + ``` val reset : t -> unit ``` Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by [`Buffer.create`](./#val-create) `n`. For long-lived buffers that may have grown a lot, `reset` allows faster reclamation of the space used by the buffer. + ``` val output_buffer : out_channel -> t -> unit ``` `output_buffer oc b` writes the current contents of buffer `b` on the output channel `oc`. + ``` val truncate : t -> int -> unit ``` `truncate b len` truncates the length of `b` to `len` Note: the internal byte sequence is not shortened. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> length b. since 4.05 + ## Appending + Note: all `add_*` operations can raise `Failure` if the internal byte sequence of the buffer would need to grow beyond [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length). + ``` val add_char : t -> char -> unit ``` `add_char b c` appends the character `c` at the end of buffer `b`. + ``` val add_utf_8_uchar : t -> Uchar.t -> unit ``` `add_utf_8_uchar b u` appends the [UTF-8](https://tools.ietf.org/html/rfc3629) encoding of `u` at the end of buffer `b`. + since 4.06 ``` val add_utf_16le_uchar : t -> Uchar.t -> unit ``` `add_utf_16le_uchar b u` appends the [UTF-16LE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. + since 4.06 ``` val add_utf_16be_uchar : t -> Uchar.t -> unit ``` `add_utf_16be_uchar b u` appends the [UTF-16BE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. + since 4.06 ``` val add_string : t -> string -> unit ``` `add_string b s` appends the string `s` at the end of buffer `b`. + ``` val add_bytes : t -> bytes -> unit ``` `add_bytes b s` appends the byte sequence `s` at the end of buffer `b`. + since 4.02 ``` val add_substring : t -> string -> int -> int -> unit ``` `add_substring b s ofs len` takes `len` characters from offset `ofs` in string `s` and appends them at the end of buffer `b`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. ``` val add_subbytes : t -> bytes -> int -> int -> unit ``` `add_subbytes b s ofs len` takes `len` characters from offset `ofs` in byte sequence `s` and appends them at the end of buffer `b`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. since 4.02 ``` val add_substitute : t -> (string -> string) -> string -> unit ``` `add_substitute b f s` appends the string pattern `s` at the end of buffer `b` with substitution. The substitution process looks for variable references in the pattern and substitutes each variable reference with its value, as obtained by applying the mapping `f` to the variable name. Inside the string pattern, a variable reference is a non-escaped `$` immediately followed by a variable name, which is one of the following: + - a non empty sequence of alphanumeric or `_` characters, - an arbitrary sequence of characters enclosed by a pair of matching parentheses or curly brackets. An escaped `$` character is a `$` that immediately follows a backslash character; the two characters together stand for a plain `$`. ``` val add_buffer : t -> t -> unit ``` `add_buffer b1 b2` appends the current contents of buffer `b2` at the end of buffer `b1`. `b2` is not modified. + ``` val add_channel : t -> in_channel -> int -> unit ``` `add_channel b ic n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`. + raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if the channel contains fewer than n characters. In this case, the characters are still added to the buffer, so as to avoid loss of data. raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> Sys.max\_string\_length. + ## Buffers and Sequences + ``` val to_seq : t -> char Seq.t ``` Iterate on the buffer, in increasing order. + The behavior is not specified if the buffer is modified during iteration. + since 4.07 ``` val to_seqi : t -> (int * char) Seq.t ``` Iterate on the buffer, in increasing order, yielding indices along chars. + The behavior is not specified if the buffer is modified during iteration. + since 4.07 ``` val add_seq : t -> char Seq.t -> unit ``` Add chars to the buffer + since 4.07 ``` val of_seq : char Seq.t -> t ``` Create a buffer from the generator + since 4.07 + ## Binary encoding of integers + The functions in this section append binary encodings of integers to buffers. + Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + 32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + 8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. Functions that encode these values truncate their inputs to their least significant bytes. + ``` val add_uint8 : t -> int -> unit ``` `add_uint8 b i` appends a binary unsigned 8-bit integer `i` to `b`. + since 4.08 ``` val add_int8 : t -> int -> unit ``` `add_int8 b i` appends a binary signed 8-bit integer `i` to `b`. + since 4.08 ``` val add_uint16_ne : t -> int -> unit ``` `add_uint16_ne b i` appends a binary native-endian unsigned 16-bit integer `i` to `b`. + since 4.08 ``` val add_uint16_be : t -> int -> unit ``` `add_uint16_be b i` appends a binary big-endian unsigned 16-bit integer `i` to `b`. + since 4.08 ``` val add_uint16_le : t -> int -> unit ``` `add_uint16_le b i` appends a binary little-endian unsigned 16-bit integer `i` to `b`. + since 4.08 ``` val add_int16_ne : t -> int -> unit ``` `add_int16_ne b i` appends a binary native-endian signed 16-bit integer `i` to `b`. + since 4.08 ``` val add_int16_be : t -> int -> unit ``` `add_int16_be b i` appends a binary big-endian signed 16-bit integer `i` to `b`. + since 4.08 ``` val add_int16_le : t -> int -> unit ``` `add_int16_le b i` appends a binary little-endian signed 16-bit integer `i` to `b`. + since 4.08 ``` val add_int32_ne : t -> int32 -> unit ``` `add_int32_ne b i` appends a binary native-endian 32-bit integer `i` to `b`. + since 4.08 ``` val add_int32_be : t -> int32 -> unit ``` `add_int32_be b i` appends a binary big-endian 32-bit integer `i` to `b`. + since 4.08 ``` val add_int32_le : t -> int32 -> unit ``` `add_int32_le b i` appends a binary little-endian 32-bit integer `i` to `b`. + since 4.08 ``` val add_int64_ne : t -> int64 -> unit ``` `add_int64_ne b i` appends a binary native-endian 64-bit integer `i` to `b`. + since 4.08 ``` val add_int64_be : t -> int64 -> unit ``` `add_int64_be b i` appends a binary big-endian 64-bit integer `i` to `b`. + since 4.08 ``` val add_int64_le : t -> int64 -> unit ``` `add_int64_ne b i` appends a binary little-endian 64-bit integer `i` to `b`. + since 4.08 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Bytes.md b/docs/api/melange/Stdlib-Bytes.md index 2b305f8d7..28c026643 100644 --- a/docs/api/melange/Stdlib-Bytes.md +++ b/docs/api/melange/Stdlib-Bytes.md @@ -1,258 +1,324 @@ + # Module `Stdlib.Bytes` + Byte sequence operations. + A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. + Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. + Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. + Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. + Bytes are represented by the OCaml type `char`. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + since 4.02 ``` val length : bytes -> int ``` Return the length (number of bytes) of the argument. + ``` val get : bytes -> int -> char ``` `get s n` returns the byte at index `n` in argument `s`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. ``` val set : bytes -> int -> char -> unit ``` `set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. ``` val create : int -> bytes ``` `create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val make : int -> char -> bytes ``` `make n c` returns a new byte sequence of length `n`, filled with the byte `c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val init : int -> (int -> char) -> bytes ``` `init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val empty : bytes ``` A byte sequence of size 0. + ``` val copy : bytes -> bytes ``` Return a new byte sequence that contains the same bytes as the argument. + ``` val of_string : string -> bytes ``` Return a new byte sequence that contains the same bytes as the given string. + ``` val to_string : bytes -> string ``` Return a new string that contains the same bytes as the given byte sequence. + ``` val sub : bytes -> int -> int -> bytes ``` `sub s pos len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. ``` val sub_string : bytes -> int -> int -> string ``` Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. + ``` val extend : bytes -> int -> int -> bytes ``` `extend s left right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. since 4.05 in BytesLabels ``` val fill : bytes -> int -> int -> char -> unit ``` `fill s pos len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. ``` val blit : bytes -> int -> bytes -> int -> int -> unit ``` `blit src src_pos dst dst_pos len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. ``` val blit_string : string -> int -> bytes -> int -> int -> unit ``` `blit_string src src_pos dst dst_pos len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. since 4.05 in BytesLabels ``` val concat : bytes -> bytes list -> bytes ``` `concat sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val cat : bytes -> bytes -> bytes ``` `cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. since 4.05 in BytesLabels ``` val iter : (char -> unit) -> bytes -> unit ``` `iter f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. + ``` val iteri : (int -> char -> unit) -> bytes -> unit ``` Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. + ``` val map : (char -> char) -> bytes -> bytes ``` `map f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + ``` val mapi : (int -> char -> char) -> bytes -> bytes ``` `mapi f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + ``` val fold_left : ('acc -> char -> 'acc) -> 'acc -> bytes -> 'acc ``` `fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. + since 4.13 ``` val fold_right : (char -> 'acc -> 'acc) -> bytes -> 'acc -> 'acc ``` `fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. + since 4.13 ``` val for_all : (char -> bool) -> bytes -> bool ``` `for_all p s` checks if all characters in `s` satisfy the predicate `p`. + since 4.13 ``` val exists : (char -> bool) -> bytes -> bool ``` `exists p s` checks if at least one character of `s` satisfies the predicate `p`. + since 4.13 ``` val trim : bytes -> bytes ``` Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. + ``` val escaped : bytes -> bytes ``` Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val index : bytes -> char -> int ``` `index s c` returns the index of the first occurrence of byte `c` in `s`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. ``` val index_opt : bytes -> char -> int option ``` `index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + since 4.05 ``` val rindex : bytes -> char -> int ``` `rindex s c` returns the index of the last occurrence of byte `c` in `s`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. ``` val rindex_opt : bytes -> char -> int option ``` `rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + since 4.05 ``` val index_from : bytes -> int -> char -> int ``` `index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. ``` val index_from_opt : bytes -> int -> char -> int option ``` `index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. since 4.05 ``` val rindex_from : bytes -> int -> char -> int ``` `rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. ``` val rindex_from_opt : bytes -> int -> char -> int option ``` `rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. since 4.05 ``` val contains : bytes -> char -> bool ``` `contains s c` tests if byte `c` appears in `s`. + ``` val contains_from : bytes -> int -> char -> bool ``` `contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. ``` val rcontains_from : bytes -> int -> char -> bool ``` `rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. ``` val uppercase_ascii : bytes -> bytes ``` Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` val lowercase_ascii : bytes -> bytes ``` Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` val capitalize_ascii : bytes -> bytes ``` Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` val uncapitalize_ascii : bytes -> bytes ``` Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` type t = bytes ``` An alias for the type of byte sequences. + ``` val compare : t -> t -> int ``` The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + ``` val equal : t -> t -> bool ``` The equality function for byte sequences. + since 4.03 (4.05 in BytesLabels) ``` val starts_with : prefix:bytes -> bytes -> bool ``` `starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + since 4.13 ``` val ends_with : suffix:bytes -> bytes -> bool ``` `ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + since 4.13 + ## Unsafe conversions (for advanced users) + This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. + ``` val unsafe_to_string : bytes -> string ``` Unsafely convert a byte sequence into a string. + To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: + - Unique ownership: the data may be accessed and mutated - Shared ownership: the data has several owners, that may only access it, not mutate it. Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. + `unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. + There are two valid use-cases that respect this ownership discipline: + 1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. + ```ocaml let string_init len f : string = let s = Bytes.create len in @@ -260,248 +326,327 @@ let string_init len f : string = Bytes.unsafe_to_string s ``` This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. + Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. + We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. + 2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. + ```ocaml let bytes_length (s : bytes) = String.length (Bytes.unsafe_to_string s) ``` In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. + The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. + ``` val unsafe_of_string : string -> bytes ``` Unsafely convert a shared string to a byte sequence that should not be mutated. + The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. + In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. + For example, string literals are implicitly shared by the compiler, so you never uniquely own them. + ```ocaml let incorrect = Bytes.unsafe_of_string "hello" let s = Bytes.of_string "hello" ``` The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. + Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. + The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. + ``` val split_on_char : char -> bytes -> bytes list ``` `split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. + The function's output is specified by the following invariants: + - The list is not empty. - Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). - No byte sequence in the result contains the `sep` character. since 4.13 + ## Iterators + ``` val to_seq : t -> char Seq.t ``` Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. + since 4.07 ``` val to_seqi : t -> (int * char) Seq.t ``` Iterate on the string, in increasing order, yielding indices along chars + since 4.07 ``` val of_seq : char Seq.t -> t ``` Create a string from the generator + since 4.07 + ## UTF codecs and validations + since 4.14 + ### UTF-8 + ``` 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`. + ``` val set_utf_8_uchar : t -> int -> Uchar.t -> int ``` `set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + ``` val is_valid_utf_8 : t -> bool ``` `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + ### UTF-16BE + ``` 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`. + ``` val set_utf_16be_uchar : t -> int -> Uchar.t -> int ``` `set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + ``` val is_valid_utf_16be : t -> bool ``` `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + ### UTF-16LE + ``` 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`. + ``` val set_utf_16le_uchar : t -> int -> Uchar.t -> int ``` `set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + ``` val is_valid_utf_16le : t -> bool ``` `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + ## Binary encoding/decoding of integers + The functions in this section binary encode and decode integers to and from byte sequences. + All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. + Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + 32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + 8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: + - Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. - Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. ``` val get_uint8 : bytes -> int -> int ``` `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. + since 4.08 ``` val get_int8 : bytes -> int -> int ``` `get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. + since 4.08 ``` val get_uint16_ne : bytes -> int -> int ``` `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_uint16_be : bytes -> int -> int ``` `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_uint16_le : bytes -> int -> int ``` `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int16_ne : bytes -> int -> int ``` `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int16_be : bytes -> int -> int ``` `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int16_le : bytes -> int -> int ``` `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int32_ne : bytes -> int -> int32 ``` `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. + since 4.08 ``` val get_int32_be : bytes -> int -> int32 ``` `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. + since 4.08 ``` val get_int32_le : bytes -> int -> int32 ``` `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. + since 4.08 ``` val get_int64_ne : bytes -> int -> int64 ``` `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. + since 4.08 ``` val get_int64_be : bytes -> int -> int64 ``` `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. + since 4.08 ``` val get_int64_le : bytes -> int -> int64 ``` `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. + since 4.08 ``` val set_uint8 : bytes -> int -> int -> unit ``` `set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int8 : bytes -> int -> int -> unit ``` `set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_uint16_ne : bytes -> int -> int -> unit ``` `set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_uint16_be : bytes -> int -> int -> unit ``` `set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_uint16_le : bytes -> int -> int -> unit ``` `set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int16_ne : bytes -> int -> int -> unit ``` `set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int16_be : bytes -> int -> int -> unit ``` `set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int16_le : bytes -> int -> int -> unit ``` `set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int32_ne : bytes -> int -> int32 -> unit ``` `set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int32_be : bytes -> int -> int32 -> unit ``` `set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int32_le : bytes -> int -> int32 -> unit ``` `set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int64_ne : bytes -> int -> int64 -> unit ``` `set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int64_be : bytes -> int -> int64 -> unit ``` `set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int64_le : bytes -> int -> int64 -> unit ``` `set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. + since 4.08 + ## Byte sequences and concurrency safety + Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + ### Atomicity + Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. + For example, consider the following program: + ```ocaml let size = 100_000_000 let b = Bytes.make size ' ' @@ -512,16 +657,27 @@ let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) let () = Domain.join d1; Domain.join d2 ``` the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. + After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ### Data races + If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. + Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. + + ### Mixed-size accesses + Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index + ```ocaml let b = Bytes.make 10 '\000' let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) ``` -In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. \ No newline at end of file +In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/melange/Stdlib-BytesLabels.md b/docs/api/melange/Stdlib-BytesLabels.md index c7a53517d..ece55c1e0 100644 --- a/docs/api/melange/Stdlib-BytesLabels.md +++ b/docs/api/melange/Stdlib-BytesLabels.md @@ -1,76 +1,99 @@ + # Module `Stdlib.BytesLabels` + Byte sequence operations. + A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. + Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. + Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. + Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. + Bytes are represented by the OCaml type `char`. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + since 4.02 ``` val length : bytes -> int ``` Return the length (number of bytes) of the argument. + ``` val get : bytes -> int -> char ``` `get s n` returns the byte at index `n` in argument `s`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. ``` val set : bytes -> int -> char -> unit ``` `set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. ``` val create : int -> bytes ``` `create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val make : int -> char -> bytes ``` `make n c` returns a new byte sequence of length `n`, filled with the byte `c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val init : int -> f:(int -> char) -> bytes ``` `init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val empty : bytes ``` A byte sequence of size 0. + ``` val copy : bytes -> bytes ``` Return a new byte sequence that contains the same bytes as the argument. + ``` val of_string : string -> bytes ``` Return a new byte sequence that contains the same bytes as the given string. + ``` val to_string : bytes -> string ``` Return a new string that contains the same bytes as the given byte sequence. + ``` val sub : bytes -> pos:int -> len:int -> bytes ``` `sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. ``` val sub_string : bytes -> pos:int -> len:int -> string ``` Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. + ``` val extend : bytes -> left:int -> right:int -> bytes ``` `extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. since 4.05 in BytesLabels ``` val fill : bytes -> pos:int -> len:int -> char -> unit ``` `fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. ``` val blit : @@ -82,6 +105,7 @@ val blit : unit ``` `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. ``` val blit_string : @@ -93,178 +117,220 @@ val blit_string : unit ``` `blit_string ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. since 4.05 in BytesLabels ``` val concat : sep:bytes -> bytes list -> bytes ``` `concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val cat : bytes -> bytes -> bytes ``` `cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. since 4.05 in BytesLabels ``` val iter : f:(char -> unit) -> bytes -> unit ``` `iter ~f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. + ``` val iteri : f:(int -> char -> unit) -> bytes -> unit ``` Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. + ``` val map : f:(char -> char) -> bytes -> bytes ``` `map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + ``` val mapi : f:(int -> char -> char) -> bytes -> bytes ``` `mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + ``` val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> bytes -> 'acc ``` `fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. + since 4.13 ``` val fold_right : f:(char -> 'acc -> 'acc) -> bytes -> init:'acc -> 'acc ``` `fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. + since 4.13 ``` val for_all : f:(char -> bool) -> bytes -> bool ``` `for_all p s` checks if all characters in `s` satisfy the predicate `p`. + since 4.13 ``` val exists : f:(char -> bool) -> bytes -> bool ``` `exists p s` checks if at least one character of `s` satisfies the predicate `p`. + since 4.13 ``` val trim : bytes -> bytes ``` Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. + ``` val escaped : bytes -> bytes ``` Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val index : bytes -> char -> int ``` `index s c` returns the index of the first occurrence of byte `c` in `s`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. ``` val index_opt : bytes -> char -> int option ``` `index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + since 4.05 ``` val rindex : bytes -> char -> int ``` `rindex s c` returns the index of the last occurrence of byte `c` in `s`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. ``` val rindex_opt : bytes -> char -> int option ``` `rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + since 4.05 ``` val index_from : bytes -> int -> char -> int ``` `index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. ``` val index_from_opt : bytes -> int -> char -> int option ``` `index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. since 4.05 ``` val rindex_from : bytes -> int -> char -> int ``` `rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. ``` val rindex_from_opt : bytes -> int -> char -> int option ``` `rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. since 4.05 ``` val contains : bytes -> char -> bool ``` `contains s c` tests if byte `c` appears in `s`. + ``` val contains_from : bytes -> int -> char -> bool ``` `contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. ``` val rcontains_from : bytes -> int -> char -> bool ``` `rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. ``` val uppercase_ascii : bytes -> bytes ``` Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` val lowercase_ascii : bytes -> bytes ``` Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` val capitalize_ascii : bytes -> bytes ``` Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` val uncapitalize_ascii : bytes -> bytes ``` Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in BytesLabels) ``` type t = bytes ``` An alias for the type of byte sequences. + ``` val compare : t -> t -> int ``` The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + ``` val equal : t -> t -> bool ``` The equality function for byte sequences. + since 4.03 (4.05 in BytesLabels) ``` val starts_with : prefix:bytes -> bytes -> bool ``` `starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + since 4.13 ``` val ends_with : suffix:bytes -> bytes -> bool ``` `ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + since 4.13 + ## Unsafe conversions (for advanced users) + This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. + ``` val unsafe_to_string : bytes -> string ``` Unsafely convert a byte sequence into a string. + To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: + - Unique ownership: the data may be accessed and mutated - Shared ownership: the data has several owners, that may only access it, not mutate it. Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. + `unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. + There are two valid use-cases that respect this ownership discipline: + 1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. + ```ocaml let string_init len f : string = let s = Bytes.create len in @@ -272,248 +338,327 @@ let string_init len f : string = Bytes.unsafe_to_string s ``` This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. + Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. + We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. + 2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. + ```ocaml let bytes_length (s : bytes) = String.length (Bytes.unsafe_to_string s) ``` In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. + The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. + ``` val unsafe_of_string : string -> bytes ``` Unsafely convert a shared string to a byte sequence that should not be mutated. + The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. + In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. + For example, string literals are implicitly shared by the compiler, so you never uniquely own them. + ```ocaml let incorrect = Bytes.unsafe_of_string "hello" let s = Bytes.of_string "hello" ``` The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. + Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. + The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. + ``` val split_on_char : sep:char -> bytes -> bytes list ``` `split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. + The function's output is specified by the following invariants: + - The list is not empty. - Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). - No byte sequence in the result contains the `sep` character. since 4.13 + ## Iterators + ``` val to_seq : t -> char Seq.t ``` Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. + since 4.07 ``` val to_seqi : t -> (int * char) Seq.t ``` Iterate on the string, in increasing order, yielding indices along chars + since 4.07 ``` val of_seq : char Seq.t -> t ``` Create a string from the generator + since 4.07 + ## UTF codecs and validations + since 4.14 + ### UTF-8 + ``` 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`. + ``` val set_utf_8_uchar : t -> int -> Uchar.t -> int ``` `set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + ``` val is_valid_utf_8 : t -> bool ``` `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + ### UTF-16BE + ``` 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`. + ``` val set_utf_16be_uchar : t -> int -> Uchar.t -> int ``` `set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + ``` val is_valid_utf_16be : t -> bool ``` `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + ### UTF-16LE + ``` 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`. + ``` val set_utf_16le_uchar : t -> int -> Uchar.t -> int ``` `set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + ``` val is_valid_utf_16le : t -> bool ``` `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + ## Binary encoding/decoding of integers + The functions in this section binary encode and decode integers to and from byte sequences. + All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. + Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + 32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + 8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: + - Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. - Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. ``` val get_uint8 : bytes -> int -> int ``` `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. + since 4.08 ``` val get_int8 : bytes -> int -> int ``` `get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. + since 4.08 ``` val get_uint16_ne : bytes -> int -> int ``` `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_uint16_be : bytes -> int -> int ``` `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_uint16_le : bytes -> int -> int ``` `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int16_ne : bytes -> int -> int ``` `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int16_be : bytes -> int -> int ``` `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int16_le : bytes -> int -> int ``` `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. + since 4.08 ``` val get_int32_ne : bytes -> int -> int32 ``` `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. + since 4.08 ``` val get_int32_be : bytes -> int -> int32 ``` `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. + since 4.08 ``` val get_int32_le : bytes -> int -> int32 ``` `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. + since 4.08 ``` val get_int64_ne : bytes -> int -> int64 ``` `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. + since 4.08 ``` val get_int64_be : bytes -> int -> int64 ``` `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. + since 4.08 ``` val get_int64_le : bytes -> int -> int64 ``` `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. + since 4.08 ``` val set_uint8 : bytes -> int -> int -> unit ``` `set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int8 : bytes -> int -> int -> unit ``` `set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_uint16_ne : bytes -> int -> int -> unit ``` `set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_uint16_be : bytes -> int -> int -> unit ``` `set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_uint16_le : bytes -> int -> int -> unit ``` `set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int16_ne : bytes -> int -> int -> unit ``` `set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int16_be : bytes -> int -> int -> unit ``` `set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int16_le : bytes -> int -> int -> unit ``` `set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int32_ne : bytes -> int -> int32 -> unit ``` `set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int32_be : bytes -> int -> int32 -> unit ``` `set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int32_le : bytes -> int -> int32 -> unit ``` `set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int64_ne : bytes -> int -> int64 -> unit ``` `set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int64_be : bytes -> int -> int64 -> unit ``` `set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. + since 4.08 ``` val set_int64_le : bytes -> int -> int64 -> unit ``` `set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. + since 4.08 + ## Byte sequences and concurrency safety + Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + ### Atomicity + Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. + For example, consider the following program: + ```ocaml let size = 100_000_000 let b = Bytes.make size ' ' @@ -524,16 +669,27 @@ let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) let () = Domain.join d1; Domain.join d2 ``` the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. + After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ### Data races + If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. + Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. + + ### Mixed-size accesses + Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index + ```ocaml let b = Bytes.make 10 '\000' let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) ``` -In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. \ No newline at end of file +In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/melange/Stdlib-Char.md b/docs/api/melange/Stdlib-Char.md index 41595f5da..31c382bda 100644 --- a/docs/api/melange/Stdlib-Char.md +++ b/docs/api/melange/Stdlib-Char.md @@ -1,48 +1,61 @@ + # Module `Stdlib.Char` + Character operations. + ``` val code : char -> int ``` Return the ASCII code of the argument. + ``` val chr : int -> char ``` Return the character with the given ASCII code. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is outside the range 0--255. ``` val escaped : char -> string ``` Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote. + ``` val lowercase_ascii : char -> char ``` Convert the given character to its equivalent lowercase character, using the US-ASCII character set. + since 4.03 ``` val uppercase_ascii : char -> char ``` Convert the given character to its equivalent uppercase character, using the US-ASCII character set. + since 4.03 ``` type t = char ``` An alias for the type of characters. + ``` val compare : t -> t -> int ``` The comparison function for characters, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Char` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + ``` val equal : t -> t -> bool ``` The equal function for chars. + since 4.03 ``` val seeded_hash : int -> t -> int ``` A seeded hash function for characters, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.1 ``` val hash : t -> int ``` An unseeded hash function for characters, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Complex.md b/docs/api/melange/Stdlib-Complex.md index 7829fe11f..e751d99b7 100644 --- a/docs/api/melange/Stdlib-Complex.md +++ b/docs/api/melange/Stdlib-Complex.md @@ -1,6 +1,10 @@ + # Module `Stdlib.Complex` + Complex numbers. + This module provides arithmetic operations on complex numbers. Complex numbers are represented by their real and imaginary parts (cartesian representation). Each part is represented by a double-precision floating-point number (type `float`). + ``` type t = { ``` @@ -10,75 +14,93 @@ type t = { } ``` The type of complex numbers. `re` is the real part and `im` the imaginary part. + ``` val zero : t ``` The complex number `0`. + ``` val one : t ``` The complex number `1`. + ``` val i : t ``` The complex number `i`. + ``` val neg : t -> t ``` Unary negation. + ``` val conj : t -> t ``` Conjugate: given the complex `x + i.y`, returns `x - i.y`. + ``` val add : t -> t -> t ``` Addition + ``` val sub : t -> t -> t ``` Subtraction + ``` val mul : t -> t -> t ``` Multiplication + ``` val inv : t -> t ``` Multiplicative inverse (`1/z`). + ``` val div : t -> t -> t ``` Division + ``` val sqrt : t -> t ``` Square root. The result `x + i.y` is such that `x > 0` or `x = 0` and `y >= 0`. This function has a discontinuity along the negative real axis. + ``` val norm2 : t -> float ``` Norm squared: given `x + i.y`, returns `x^2 + y^2`. + ``` val norm : t -> float ``` Norm: given `x + i.y`, returns `sqrt(x^2 + y^2)`. + ``` val arg : t -> float ``` Argument. The argument of a complex number is the angle in the complex plane between the positive real axis and a line passing through zero and the number. This angle ranges from `-pi` to `pi`. This function has a discontinuity along the negative real axis. + ``` val polar : float -> float -> t ``` `polar norm arg` returns the complex having norm `norm` and argument `arg`. + ``` val exp : t -> t ``` Exponentiation. `exp z` returns `e` to the `z` power. + ``` val log : t -> t ``` Natural logarithm (in base `e`). + ``` val pow : t -> t -> t ``` -Power function. `pow z1 z2` returns `z1` to the `z2` power. \ No newline at end of file +Power function. `pow z1 z2` returns `z1` to the `z2` power. diff --git a/docs/api/melange/Stdlib-Digest-BLAKE128.md b/docs/api/melange/Stdlib-Digest-BLAKE128.md index 8ac901a28..d066e1e33 100644 --- a/docs/api/melange/Stdlib-Digest-BLAKE128.md +++ b/docs/api/melange/Stdlib-Digest-BLAKE128.md @@ -1,61 +1,78 @@ + # Module `Digest.BLAKE128` + `BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. + since 5.2 ``` type t = string ``` The type of digests. + ``` val hash_length : int ``` The length of digests, in bytes. + ``` val compare : t -> t -> int ``` Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + ``` val equal : t -> t -> bool ``` Test two digests for equality. + ``` val string : string -> t ``` Return the digest of the given string. + ``` val bytes : bytes -> t ``` Return the digest of the given byte sequence. + ``` val substring : string -> int -> int -> t ``` `substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + ``` val subbytes : bytes -> int -> int -> t ``` `subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + ``` val channel : in_channel -> int -> t ``` Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + ``` val file : string -> t ``` Return the digest of the file whose name is given. + ``` val output : out_channel -> t -> unit ``` Write a digest on the given output channel. + ``` val input : in_channel -> t ``` Read a digest from the given input channel. + ``` val to_hex : t -> string ``` Return the printable hexadecimal representation of the given digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, ``` val of_hex : string -> t ``` Convert a hexadecimal representation back into the corresponding digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-BLAKE256.md b/docs/api/melange/Stdlib-Digest-BLAKE256.md index a8666f993..ee9952c96 100644 --- a/docs/api/melange/Stdlib-Digest-BLAKE256.md +++ b/docs/api/melange/Stdlib-Digest-BLAKE256.md @@ -1,61 +1,78 @@ + # Module `Digest.BLAKE256` + `BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + since 5.2 ``` type t = string ``` The type of digests. + ``` val hash_length : int ``` The length of digests, in bytes. + ``` val compare : t -> t -> int ``` Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + ``` val equal : t -> t -> bool ``` Test two digests for equality. + ``` val string : string -> t ``` Return the digest of the given string. + ``` val bytes : bytes -> t ``` Return the digest of the given byte sequence. + ``` val substring : string -> int -> int -> t ``` `substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + ``` val subbytes : bytes -> int -> int -> t ``` `subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + ``` val channel : in_channel -> int -> t ``` Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + ``` val file : string -> t ``` Return the digest of the file whose name is given. + ``` val output : out_channel -> t -> unit ``` Write a digest on the given output channel. + ``` val input : in_channel -> t ``` Read a digest from the given input channel. + ``` val to_hex : t -> string ``` Return the printable hexadecimal representation of the given digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, ``` val of_hex : string -> t ``` Convert a hexadecimal representation back into the corresponding digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-BLAKE512.md b/docs/api/melange/Stdlib-Digest-BLAKE512.md index 613a76602..a22b0bc72 100644 --- a/docs/api/melange/Stdlib-Digest-BLAKE512.md +++ b/docs/api/melange/Stdlib-Digest-BLAKE512.md @@ -1,61 +1,78 @@ + # Module `Digest.BLAKE512` + `BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + since 5.2 ``` type t = string ``` The type of digests. + ``` val hash_length : int ``` The length of digests, in bytes. + ``` val compare : t -> t -> int ``` Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + ``` val equal : t -> t -> bool ``` Test two digests for equality. + ``` val string : string -> t ``` Return the digest of the given string. + ``` val bytes : bytes -> t ``` Return the digest of the given byte sequence. + ``` val substring : string -> int -> int -> t ``` `substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + ``` val subbytes : bytes -> int -> int -> t ``` `subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + ``` val channel : in_channel -> int -> t ``` Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + ``` val file : string -> t ``` Return the digest of the file whose name is given. + ``` val output : out_channel -> t -> unit ``` Write a digest on the given output channel. + ``` val input : in_channel -> t ``` Read a digest from the given input channel. + ``` val to_hex : t -> string ``` Return the printable hexadecimal representation of the given digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, ``` val of_hex : string -> t ``` Convert a hexadecimal representation back into the corresponding digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-MD5.md b/docs/api/melange/Stdlib-Digest-MD5.md index b881120cb..9909a727e 100644 --- a/docs/api/melange/Stdlib-Digest-MD5.md +++ b/docs/api/melange/Stdlib-Digest-MD5.md @@ -1,61 +1,78 @@ + # Module `Digest.MD5` + `MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. + since 5.2 ``` type t = string ``` The type of digests. + ``` val hash_length : int ``` The length of digests, in bytes. + ``` val compare : t -> t -> int ``` Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + ``` val equal : t -> t -> bool ``` Test two digests for equality. + ``` val string : string -> t ``` Return the digest of the given string. + ``` val bytes : bytes -> t ``` Return the digest of the given byte sequence. + ``` val substring : string -> int -> int -> t ``` `substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + ``` val subbytes : bytes -> int -> int -> t ``` `subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + ``` val channel : in_channel -> int -> t ``` Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + ``` val file : string -> t ``` Return the digest of the file whose name is given. + ``` val output : out_channel -> t -> unit ``` Write a digest on the given output channel. + ``` val input : in_channel -> t ``` Read a digest from the given input channel. + ``` val to_hex : t -> string ``` Return the printable hexadecimal representation of the given digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, ``` val of_hex : string -> t ``` Convert a hexadecimal representation back into the corresponding digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest-module-type-S.md b/docs/api/melange/Stdlib-Digest-module-type-S.md index e553f47ae..8e6095b8a 100644 --- a/docs/api/melange/Stdlib-Digest-module-type-S.md +++ b/docs/api/melange/Stdlib-Digest-module-type-S.md @@ -1,61 +1,78 @@ + # Module type `Digest.S` + The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. + since 5.2 ``` type t = string ``` The type of digests. + ``` val hash_length : int ``` The length of digests, in bytes. + ``` val compare : t -> t -> int ``` Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + ``` val equal : t -> t -> bool ``` Test two digests for equality. + ``` val string : string -> t ``` Return the digest of the given string. + ``` val bytes : bytes -> t ``` Return the digest of the given byte sequence. + ``` val substring : string -> int -> int -> t ``` `substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + ``` val subbytes : bytes -> int -> int -> t ``` `subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + ``` val channel : in_channel -> int -> t ``` Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + ``` val file : string -> t ``` Return the digest of the file whose name is given. + ``` val output : out_channel -> t -> unit ``` Write a digest on the given output channel. + ``` val input : in_channel -> t ``` Read a digest from the given input channel. + ``` val to_hex : t -> string ``` Return the printable hexadecimal representation of the given digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, ``` val of_hex : string -> t ``` Convert a hexadecimal representation back into the corresponding digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Digest.md b/docs/api/melange/Stdlib-Digest.md index b2e19fba1..6ef661f6d 100644 --- a/docs/api/melange/Stdlib-Digest.md +++ b/docs/api/melange/Stdlib-Digest.md @@ -1,91 +1,120 @@ + # Module `Stdlib.Digest` + Message digest. + This module provides functions to compute 'digests', also known as 'hashes', of arbitrary-length strings or files. The supported hashing algorithms are BLAKE2 and MD5. + + ## Basic functions + The functions in this section use the MD5 hash function to produce 128-bit digests (16 bytes). MD5 is not cryptographically secure. Hence, these functions should not be used for security-sensitive applications. The BLAKE2 functions below are cryptographically secure. + ``` type t = string ``` The type of digests: 16-byte strings. + ``` val compare : t -> t -> int ``` The comparison function for 16-byte digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare) and the implementation shared with [`String.compare`](./Stdlib-String.md#val-compare). Along with the type `t`, this function `compare` allows the module `Digest` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + since 4.00 ``` val equal : t -> t -> bool ``` The equal function for 16-byte digests. + since 4.03 ``` val string : string -> t ``` Return the digest of the given string. + ``` val bytes : bytes -> t ``` Return the digest of the given byte sequence. + since 4.02 ``` val substring : string -> int -> int -> t ``` `Digest.substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + ``` val subbytes : bytes -> int -> int -> t ``` `Digest.subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + since 4.02 ``` val channel : in_channel -> int -> t ``` If `len` is nonnegative, `Digest.channel ic len` reads `len` characters from channel `ic` and returns their digest, or raises `End_of_file` if end-of-file is reached before `len` characters are read. If `len` is negative, `Digest.channel ic len` reads all characters from `ic` until end-of-file is reached and return their digest. + ``` val file : string -> t ``` Return the digest of the file whose name is given. + ``` val output : out_channel -> t -> unit ``` Write a digest on the given output channel. + ``` val input : in_channel -> t ``` Read a digest from the given input channel. + ``` val to_hex : t -> string ``` Return the printable hexadecimal representation of the given digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 16 bytes. ``` val of_hex : string -> t ``` Convert a hexadecimal representation back into the corresponding digest. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 32 hexadecimal characters. since 5.2 ``` val from_hex : string -> t ``` Same function as [`Digest.of_hex`](./#val-of_hex). + since 4.00 + ## Generic interface + ``` module type S = sig ... end ``` The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. + + ## Specific hash functions + ``` module BLAKE128 : S ``` `BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. + ``` module BLAKE256 : S ``` `BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + ``` module BLAKE512 : S ``` `BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + ``` module MD5 : S ``` -`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. \ No newline at end of file +`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. diff --git a/docs/api/melange/Stdlib-Domain-DLS.md b/docs/api/melange/Stdlib-Domain-DLS.md index b67997fdd..5c29e70ee 100644 --- a/docs/api/melange/Stdlib-Domain-DLS.md +++ b/docs/api/melange/Stdlib-Domain-DLS.md @@ -1,16 +1,24 @@ + # Module `Domain.DLS` + Domain-local Storage + ``` type 'a key ``` Type of a DLS key + ``` val new_key : ?split_from_parent:('a -> 'a) -> (unit -> 'a) -> 'a key ``` `new_key f` returns a new key bound to initialiser `f` for accessing domain-local variables. + If `split_from_parent` is not provided, the value for a new domain will be computed on-demand by the new domain: the first `get` call will call the initializer `f` and store that value. + **Warning.** `f` may be called several times if another call to `get` occurs during initialization on the same domain. Only the 'first' value computed will be used, the other now-useless values will be discarded. Your initialization function should support this situation, or contain logic to detect this case and fail. + If `split_from_parent` is provided, spawning a domain will derive the child value (for this key) from the parent value. This computation happens in the parent domain and it always happens, regardless of whether the child domain will use it. If the splitting function is expensive or requires child-side computation, consider using `'a Lazy.t key`: + ```ocaml let init () = ... @@ -25,11 +33,13 @@ let key = Domain.DLS.new_key ~split_from_parent init let get () = Lazy.force (Domain.DLS.get key) ``` In this case a part of the computation happens on the child domain; in particular, it can access `parent_value` concurrently with the parent domain, which may require explicit synchronization to avoid data races. + ``` val get : 'a key -> 'a ``` `get k` returns `v` if a value `v` is associated to the key `k` on the calling domain's domain-local state. Sets `k`'s value with its initialiser and returns it otherwise. + ``` val set : 'a key -> 'a -> unit ``` -`set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. It overwrites any previous values associated to `k`, which cannot be restored later. \ No newline at end of file +`set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. It overwrites any previous values associated to `k`, which cannot be restored later. diff --git a/docs/api/melange/Stdlib-Domain.md b/docs/api/melange/Stdlib-Domain.md index 530280beb..5a038a823 100644 --- a/docs/api/melange/Stdlib-Domain.md +++ b/docs/api/melange/Stdlib-Domain.md @@ -1,43 +1,55 @@ + # Module `Stdlib.Domain` + alert unstable The Domain interface may change in incompatible ways in the future. Domains. + See 'Parallel programming' chapter in the manual. + since 5.0 alert unstable The Domain interface may change in incompatible ways in the future. ``` type !'a t ``` A domain of type `'a t` runs independently, eventually producing a result of type 'a, or an exception + ``` val spawn : (unit -> 'a) -> 'a t ``` `spawn f` creates a new domain that runs in parallel with the current domain. + raises [`Failure`](./Stdlib.md#exception-Failure) if the program has insufficient resources to create another domain. ``` val join : 'a t -> 'a Js.Promise.t ``` `join d` blocks until domain `d` runs to completion. If `d` results in a value, then that is returned by `join d`. If `d` raises an uncaught exception, then that is re-raised by `join d`. + ``` type id = private int ``` Domains have unique integer identifiers + ``` val get_id : 'a t -> id ``` `get_id d` returns the identifier of the domain `d` + ``` val self : unit -> id ``` `self ()` is the identifier of the currently running domain + ``` val before_first_spawn : (unit -> unit) -> unit ``` `before_first_spawn f` registers `f` to be called before the first domain is spawned by the program. The functions registered with `before_first_spawn` are called on the main (initial) domain. The functions registered with `before_first_spawn` are called in 'first in, first out' order: the oldest function added with `before_first_spawn` is called first. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the program has already spawned a domain. ``` val at_exit : (unit -> unit) -> unit ``` `at_exit f` registers `f` to be called when the current domain exits. Note that `at_exit` callbacks are domain-local and only apply to the calling domain. The registered functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. An example: + ```ocaml let temp_file_key = Domain.DLS.new_key (fun _ -> let tmp = snd (Filename.open_temp_file "" "") in @@ -45,26 +57,33 @@ let temp_file_key = Domain.DLS.new_key (fun _ -> tmp) ``` The snippet above creates a key that when retrieved for the first time will open a temporary file and register an `at_exit` callback to close it, thus guaranteeing the descriptor is not leaked in case the current domain exits. + ``` val cpu_relax : unit -> unit ``` If busy-waiting, calling cpu\_relax () between iterations will improve performance on some CPU architectures + ``` val is_main_domain : unit -> bool ``` `is_main_domain ()` returns true if called from the initial domain. + ``` val recommended_domain_count : unit -> int ``` The recommended maximum number of domains which should be running simultaneously (including domains already running). + The value returned is at least `1`. + ``` val self_index : unit -> int ``` The index of the current domain. It is an integer unique among currently-running domains, in the interval `0; N-1` where N is the peak number of domains running simultaneously so far. + The index of a terminated domain may be reused for a new domain. Use `(Domain.self () :> int)` instead for an identifier unique among all domains ever created by the program. + since 5.3 ``` module DLS : sig ... end ``` -Domain-local Storage \ No newline at end of file +Domain-local Storage diff --git a/docs/api/melange/Stdlib-Dynarray.md b/docs/api/melange/Stdlib-Dynarray.md index e2d14d0ee..c278e16be 100644 --- a/docs/api/melange/Stdlib-Dynarray.md +++ b/docs/api/melange/Stdlib-Dynarray.md @@ -1,7 +1,12 @@ + # Module `Stdlib.Dynarray` + Dynamic arrays. + The [`Array`](./Stdlib-Array.md) module provide arrays of fixed length. [`Dynarray`](#) provides arrays whose length can change over time, by adding or removing elements at the end of the array. + This is typically used to accumulate elements whose number is not known in advance or changes during computation, while also providing fast access to elements at arbitrary indices. + ```ocaml let dynarray_of_list li = let arr = Dynarray.create () in @@ -9,75 +14,102 @@ This is typically used to accumulate elements whose number is not known in advan arr ``` The [`Buffer`](./Stdlib-Buffer.md) module provides similar features, but it is specialized for accumulating characters into a dynamically-resized string. + The [`Stack`](./Stdlib-Stack.md) module provides a last-in first-out data structure that can be easily implemented on top of dynamic arrays. + since 5.2 **Unsynchronized accesses** + Concurrent accesses to dynamic arrays must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). Unsynchronized accesses to a dynamic array are a programming error that may lead to an invalid dynamic array state, on which some operations would fail with an `Invalid_argument` exception. + + ## Dynamic arrays + ``` type !'a t ``` A dynamic array containing values of type `'a`. + A dynamic array `a` provides constant-time `get` and `set` operations on indices between `0` and `Dynarray.length a - 1` included. Its [`length`](./#val-length) may change over time by adding or removing elements to the end of the array. + We say that an index into a dynarray `a` is valid if it is in `0 .. length a - 1` and invalid otherwise. + ``` val create : unit -> 'a t ``` `create ()` is a new, empty array. + ``` val make : int -> 'a -> 'a t ``` `make n x` is a new array of length `n`, filled with `x`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. ``` val init : int -> (int -> 'a) -> 'a t ``` `init n f` is a new array `a` of length `n`, such that `get a i` is `f i`. In other words, the elements of `a` are `f 0`, then `f 1`, then `f 2`... and `f (n - 1)` last, evaluated in that order. + This is similar to [`Array.init`](./Stdlib-Array.md#val-init). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. ``` val get : 'a t -> int -> 'a ``` `get a i` is the `i`\-th element of `a`, starting with index `0`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid ``` val set : 'a t -> int -> 'a -> unit ``` `set a i x` sets the `i`\-th element of `a` to be `x`. + `i` must be a valid index. `set` does not add new elements to the array \-- see [`add_last`](./#val-add_last) to add an element. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid. ``` val length : 'a t -> int ``` `length a` is the number of elements in the array. + ``` val is_empty : 'a t -> bool ``` `is_empty a` is `true` if `a` is empty, that is, if `length a = 0`. + ``` val get_last : 'a t -> 'a ``` `get_last a` is the element of `a` at index `length a - 1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if a is empty. ``` val find_last : 'a t -> 'a option ``` `find_last a` is `None` if `a` is empty and `Some (get_last a)` otherwise. + ``` val copy : 'a t -> 'a t ``` `copy a` is a shallow copy of `a`, a new array containing the same elements as `a`. + + ## Adding elements + Note: all operations adding elements raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). + ``` val add_last : 'a t -> 'a -> unit ``` `add_last a x` adds the element `x` at the end of the array `a`. + ``` val append_array : 'a t -> 'a array -> unit ``` `append_array a b` adds all elements of `b` at the end of `a`, in the order they appear in `b`. + For example: + ```ocaml let a = Dynarray.of_list [1;2] in Dynarray.append_array a [|3; 4|]; @@ -87,21 +119,28 @@ For example: val append_list : 'a t -> 'a list -> unit ``` Like [`append_array`](./#val-append_array) but with a list. + ``` val append : 'a t -> 'a t -> unit ``` `append a b` is like `append_array a b`, but `b` is itself a dynamic array instead of a fixed-size array. + Warning: `append a a` is a programming error because it iterates on `a` and adds elements to it at the same time \-- see the [Iteration](./#iteration) section below. It fails with `Invalid_argument`. If you really want to append a copy of `a` to itself, you can use `Dynarray.append_array a (Dynarray.to_array a)` which copies `a` into a temporary array. + ``` val append_seq : 'a t -> 'a Seq.t -> unit ``` Like [`append_array`](./#val-append_array) but with a sequence. + Warning: `append_seq a (to_seq_reentrant a)` simultaneously traverses `a` and adds element to it; the ordering of those operations is unspecified, and may result in an infinite loop \-- the new elements may in turn be produced by `to_seq_reentrant a` and get added again and again. + ``` val append_iter : 'a t -> (('a -> unit) -> 'x -> unit) -> 'x -> unit ``` `append_iter a iter x` adds each element of `x` to the end of `a`. This is `iter (add_last a) x`. + For example, `append_iter a List.iter [1;2;3]` would add elements `1`, `2`, and then `3` at the end of `a`. `append_iter a Queue.iter q` adds elements from the queue `q`. + ``` val blit : src:'a t -> @@ -112,28 +151,38 @@ val blit : unit ``` `blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from a source dynarray `src`, starting at index `src_pos`, to a destination dynarray `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. + Unlike [`Array.blit`](./Stdlib-Array.md#val-blit), [`Dynarray.blit`](./#val-blit) can extend the destination array with new elements: it is valid to call `blit` even when `dst_pos + len` is larger than `length dst`. The only requirement is that `dst_pos` must be at most `length dst` (included), so that there is no gap between the current elements and the blit region. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos is strictly below 0 or strictly above length dst. + ## Removing elements + ``` val pop_last_opt : 'a t -> 'a option ``` `pop_last_opt a` removes and returns the last element of `a`, or `None` if the array is empty. + ``` val pop_last : 'a t -> 'a ``` `pop_last a` removes and returns the last element of `a`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) on an empty array. ``` val remove_last : 'a t -> unit ``` `remove_last a` removes the last element of `a`, if any. It does nothing if `a` is empty. + ``` val truncate : 'a t -> int -> unit ``` `truncate a n` truncates `a` to have at most `n` elements. + It removes elements whose index is greater or equal to `n`. It does nothing if `n >= length a`. + `truncate a n` is equivalent to: + ```ocaml if n < 0 then invalid_argument "..."; while length a > n do @@ -145,32 +194,45 @@ raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. val clear : 'a t -> unit ``` `clear a` is `truncate a 0`, it removes all the elements of `a`. + + ## Iteration + The iteration functions traverse the elements of a dynamic array. Traversals of `a` are computed in increasing index order: from the element of index `0` to the element of index `length a - 1`. + It is a programming error to change the length of an array (by adding or removing elements) during an iteration on the array. Any iteration function will fail with `Invalid_argument` if it detects such a length change. + ``` val iter : ('a -> unit) -> 'a t -> unit ``` `iter f a` calls `f` on each element of `a`. + ``` val iteri : (int -> 'a -> unit) -> 'a t -> unit ``` `iteri f a` calls `f i x` for each `x` at index `i` in `a`. + ``` val map : ('a -> 'b) -> 'a t -> 'b t ``` `map f a` is a new array of elements of the form `f x` for each element `x` of `a`. + For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f x0`, `f x1`, `f x2`. + ``` val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t ``` `mapi f a` is a new array of elements of the form `f i x` for each element `x` of `a` at index `i`. + For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f 0 x0`, `f 1 x1`, `f 2 x2`. + ``` val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc ``` `fold_left f acc a` folds `f` over `a` in order, starting with accumulator `acc`. + For example, if the elements of `a` are `x0`, `x1`, then `fold f acc a` is + ```ocaml let acc = f acc x0 in let acc = f acc x1 in @@ -180,133 +242,184 @@ For example, if the elements of `a` are `x0`, `x1`, then `fold f acc a` is val fold_right : ('a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc ``` `fold_right f a acc` computes `f x0 (f x1 (... (f xn acc) ...))` where `x0`, `x1`, ..., `xn` are the elements of `a`. + ``` val filter : ('a -> bool) -> 'a t -> 'a t ``` `filter f a` is a new array of all the elements of `a` that satisfy `f`. In other words, it is an array `b` such that, for each element `x` in `a` in order, `x` is added to `b` if `f x` is `true`. + For example, `filter (fun x -> x >= 0) a` is a new array of all non-negative elements of `a`, in order. + ``` val filter_map : ('a -> 'b option) -> 'a t -> 'b t ``` `filter_map f a` is a new array of elements `y` such that `f x` is `Some y` for an element `x` of `a`. In others words, it is an array `b` such that, for each element `x` of `a` in order: + - if `f x = Some y`, then `y` is added to `b`, - if `f x = None`, then no element is added to `b`. For example, `filter_map int_of_string_opt inputs` returns a new array of integers read from the strings in `inputs`, ignoring strings that cannot be converted to integers. + + ## Dynarray scanning + ``` val exists : ('a -> bool) -> 'a t -> bool ``` `exists f a` is `true` if some element of `a` satisfies `f`. + For example, if the elements of `a` are `x0`, `x1`, `x2`, then `exists f a` is `f x0 || f x1 || f x2`. + ``` val for_all : ('a -> bool) -> 'a t -> bool ``` `for_all f a` is `true` if all elements of `a` satisfy `f`. This includes the case where `a` is empty. + For example, if the elements of `a` are `x0`, `x1`, then `exists f a` is `f x0 && f x1 && f x2`. + ``` val mem : 'a -> 'a t -> bool ``` `mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). + since 5.3 ``` val memq : 'a -> 'a t -> bool ``` Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. + since 5.3 ``` val find_opt : ('a -> bool) -> 'a t -> 'a option ``` `find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. + since 5.3 ``` val find_index : ('a -> bool) -> 'a t -> int option ``` `find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + It returns `None` if there is no such element. + since 5.3 ``` val find_map : ('a -> 'b option) -> 'a t -> 'b option ``` `find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. + since 5.3 ``` val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option ``` Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 5.3 + ## Comparison functions + Comparison functions iterate over their arguments; it is a programming error to change their length during the iteration, see the [Iteration](./#iteration) section above. + ``` val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool ``` `equal eq a b` holds when `a` and `b` have the same length, and for all indices `i` we have `eq (get a i) (get b i)`. + since 5.3 ``` val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int ``` Provided the function `cmp` defines a preorder on elements, `compare cmp a b` compares first `a` and `b` by their length, and then, if equal, by their elements according to the lexicographic preorder. + For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). + since 5.3 + ## Conversions to other data structures + Note: the `of_*` functions raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). + The `to_*` functions, except those specifically marked "reentrant", iterate on their dynarray argument. In particular it is a programming error if the length of the dynarray changes during their execution, and the conversion functions raise `Invalid_argument` if they observe such a change. + ``` val of_array : 'a array -> 'a t ``` `of_array arr` returns a dynamic array corresponding to the fixed-sized array `a`. Operates in `O(n)` time by making a copy. + ``` val to_array : 'a t -> 'a array ``` `to_array a` returns a fixed-sized array corresponding to the dynamic array `a`. This always allocate a new array and copies elements into it. + ``` val of_list : 'a list -> 'a t ``` `of_list l` is the array containing the elements of `l` in the same order. + ``` val to_list : 'a t -> 'a list ``` `to_list a` is a list with the elements contained in the array `a`. + ``` val of_seq : 'a Seq.t -> 'a t ``` `of_seq seq` is an array containing the same elements as `seq`. + It traverses `seq` once and will terminate only if `seq` is finite. + ``` val to_seq : 'a t -> 'a Seq.t ``` `to_seq a` is the sequence of elements `get a 0`, `get a 1`... `get a (length a - 1)`. + ``` val to_seq_reentrant : 'a t -> 'a Seq.t ``` `to_seq_reentrant a` is a reentrant variant of [`to_seq`](./#val-to_seq), in the sense that one may still access its elements after the length of `a` has changed. + Demanding the `i`\-th element of the resulting sequence (which can happen zero, one or several times) will access the `i`\-th element of `a` at the time of the demand. The sequence stops if `a` has less than `i` elements at this point. + ``` val to_seq_rev : 'a t -> 'a Seq.t ``` `to_seq_rev a` is the sequence of elements `get a (l - 1)`, `get a (l - 2)`... `get a 0`, where `l` is `length a` at the time `to_seq_rev` is invoked. + ``` val to_seq_rev_reentrant : 'a t -> 'a Seq.t ``` `to_seq_rev_reentrant a` is a reentrant variant of [`to_seq_rev`](./#val-to_seq_rev), in the sense that one may still access its elements after the length of `a` has changed. + Elements that have been removed from the array by the time they are demanded in the sequence are skipped. + + ## Advanced topics for performance + + ### Backing array, capacity + Internally, a dynamic array uses a **backing array** (a fixed-size array as provided by the [`Array`](./Stdlib-Array.md) module) whose length is greater or equal to the length of the dynamic array. We define the **capacity** of a dynamic array as the length of its backing array. + The capacity of a dynamic array is relevant in advanced scenarios, when reasoning about the performance of dynamic array programs: + - The memory usage of a dynamic array is proportional to its capacity, rather than its length. - When there is no empty space left at the end of the backing array, adding elements requires allocating a new, larger backing array. The implementation uses a standard exponential reallocation strategy which guarantees amortized constant-time operation; in particular, the total capacity of all backing arrays allocated over the lifetime of a dynamic array is at worst proportional to the total number of elements added. + In other words, users need not care about capacity and reallocations, and they will get reasonable behavior by default. However, in some performance-sensitive scenarios the functions below can help control memory usage or guarantee an optimal number of reallocations. + ``` val capacity : 'a t -> int ``` `capacity a` is the length of `a`'s backing array. + ``` val ensure_capacity : 'a t -> int -> unit ``` `ensure_capacity a n` makes sure that the capacity of `a` is at least `n`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the requested capacity is outside the range 0 .. Sys.max\_array\_length. An example would be to reimplement [`of_array`](./#val-of_array) without using [`init`](./#val-init): + ```ocaml let of_array arr = let a = Dynarray.create () in @@ -314,13 +427,17 @@ let of_array arr = Array.iter (fun v -> add_last a v) arr ``` Using `ensure_capacity` guarantees that at most one reallocation will take place, instead of possibly several. + Without this `ensure_capacity` hint, the number of resizes would be logarithmic in the length of `arr`, creating a constant-factor slowdown noticeable when `arr` is large. + ``` val ensure_extra_capacity : 'a t -> int -> unit ``` `ensure_extra_capacity a n` is `ensure_capacity a (length a + n)`, it makes sure that `a` has room for `n` extra items. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the total requested capacity is outside the range 0 .. Sys.max\_array\_length. A use case would be to implement [`append_array`](./#val-append_array): + ```ocaml let append_array a arr = ensure_extra_capacity a (Array.length arr); @@ -330,25 +447,41 @@ let append_array a arr = val fit_capacity : 'a t -> unit ``` `fit_capacity a` reallocates a backing array if necessary, so that the resulting capacity is exactly `length a`, with no additional empty space at the end. This can be useful to make sure there is no memory wasted on a long-lived array. + Note that calling `fit_capacity` breaks the amortized complexity guarantees provided by the default reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. + If you know that a dynamic array has reached its final length, which will remain fixed in the future, it is sufficient to call `to_array` and only keep the resulting fixed-size array. `fit_capacity` is useful when you need to keep a dynamic array for eventual future resizes. + ``` val set_capacity : 'a t -> int -> unit ``` `set_capacity a n` reallocates a backing array if necessary, so that the resulting capacity is exactly `n`. In particular, all elements of index `n` or greater are removed. + Like [`fit_capacity`](./#val-fit_capacity), this function breaks the amortized complexity guarantees provided by the reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. + This is an advanced function; in particular, [`ensure_capacity`](./#val-ensure_capacity) should be preferred to increase the capacity, as it preserves those amortized guarantees. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. ``` val reset : 'a t -> unit ``` `reset a` clears `a` and replaces its backing array by an empty array. + It is equivalent to `set_capacity a 0` or `clear a; fit_capacity a`. + + ### No leaks: preservation of memory liveness + The user-provided values reachable from a dynamic array `a` are exactly the elements in the indices `0` to `length a - 1`. In particular, no user-provided values are "leaked" by being present in the backing array at index `length a` or later. + + ## Code examples + + ### Min-heaps for mutable priority queues + We can use dynamic arrays to implement a mutable priority queue. A priority queue provides a function to add elements, and a function to extract the minimum element \-- according to some comparison function. + ```ocaml (* We present our priority queues as a functor parametrized on the comparison function. *) @@ -432,12 +565,14 @@ end = struct end ``` The production code from which this example was inspired includes logic to free the backing array when the heap becomes empty, only in the case where the capacity is above a certain threshold. This can be done by calling the following function from `pop`: + ```ocaml let shrink h = if Dynarray.length h = 0 && Dynarray.capacity h > 1 lsl 18 then Dynarray.reset h ``` The `Heap` functor can be used to implement a sorting function, by adding all elements into a priority queue and then extracting them in order. + ```ocaml let heap_sort (type a) cmp li = let module Heap = Heap(struct type t = a let compare = cmp end) in diff --git a/docs/api/melange/Stdlib-Either.md b/docs/api/melange/Stdlib-Either.md index 4f31dbbec..444260295 100644 --- a/docs/api/melange/Stdlib-Either.md +++ b/docs/api/melange/Stdlib-Either.md @@ -1,13 +1,20 @@ + # Module `Stdlib.Either` + Either type. + Either is the simplest and most generic sum/variant type: a value of `('a, 'b) Either.t` is either a `Left (v : 'a)` or a `Right (v : 'b)`. + It is a natural choice in the API of generic functions where values could fall in two different cases, possibly at different types, without assigning a specific meaning to what each case should be. + For example: + ```ocaml List.partition_map: ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list ``` If you are looking for a parametrized type where one alternative means success and the other means failure, you should use the more specific type [`Result.t`](./Stdlib-Result.md#type-t). + since 4.12 ``` type ('a, 'b) t = @@ -22,38 +29,47 @@ type ('a, 'b) t = ``` A value of `('a, 'b) Either.t` contains either a value of `'a` or a value of `'b` + ``` val left : 'a -> ('a, 'b) t ``` `left v` is `Left v`. + ``` val right : 'b -> ('a, 'b) t ``` `right v` is `Right v`. + ``` val is_left : ('a, 'b) t -> bool ``` `is_left (Left v)` is `true`, `is_left (Right v)` is `false`. + ``` val is_right : ('a, 'b) t -> bool ``` `is_right (Left v)` is `false`, `is_right (Right v)` is `true`. + ``` val find_left : ('a, 'b) t -> 'a option ``` `find_left (Left v)` is `Some v`, `find_left (Right _)` is `None` + ``` val find_right : ('a, 'b) t -> 'b option ``` `find_right (Right v)` is `Some v`, `find_right (Left _)` is `None` + ``` val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t ``` `map_left f e` is `Left (f v)` if `e` is `Left v` and `e` if `e` is `Right _`. + ``` val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t ``` `map_right f e` is `Right (f v)` if `e` is `Right v` and `e` if `e` is `Left _`. + ``` val map : left:('a1 -> 'a2) -> @@ -62,18 +78,22 @@ val map : ('a2, 'b2) t ``` `map ~left ~right (Left v)` is `Left (left v)`, `map ~left ~right (Right v)` is `Right (right v)`. + ``` val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c ``` `fold ~left ~right (Left v)` is `left v`, and `fold ~left ~right (Right v)` is `right v`. + ``` val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit ``` `iter ~left ~right (Left v)` is `left v`, and `iter ~left ~right (Right v)` is `right v`. + ``` val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool ``` `for_all ~left ~right (Left v)` is `left v`, and `for_all ~left ~right (Right v)` is `right v`. + ``` val equal : left:('a -> 'a -> bool) -> @@ -83,6 +103,7 @@ val equal : bool ``` `equal ~left ~right e0 e1` tests equality of `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. + ``` val compare : left:('a -> 'a -> int) -> @@ -91,4 +112,4 @@ val compare : ('a, 'b) t -> int ``` -`compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _ ` and `Right _`. `Left _` values are smaller than `Right _` values. \ No newline at end of file +`compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _ ` and `Right _`. `Left _` values are smaller than `Right _` values. diff --git a/docs/api/melange/Stdlib-Filename.md b/docs/api/melange/Stdlib-Filename.md index 78815ae75..f56fdfaec 100644 --- a/docs/api/melange/Stdlib-Filename.md +++ b/docs/api/melange/Stdlib-Filename.md @@ -1,84 +1,109 @@ + # Module `Stdlib.Filename` + Operations on file names. + ``` val current_dir_name : string ``` The conventional name for the current directory (e.g. `.` in Unix). + ``` val parent_dir_name : string ``` The conventional name for the parent of the current directory (e.g. `..` in Unix). + ``` val dir_sep : string ``` The directory separator (e.g. `/` in Unix). + since 3.11.2 ``` val concat : string -> string -> string ``` `concat dir file` returns a file name that designates file `file` in directory `dir`. + ``` val is_relative : string -> bool ``` Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. in Unix, starts with `/`). + ``` val is_implicit : string -> bool ``` Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory. + ``` val check_suffix : string -> string -> bool ``` `check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`. + Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. + ``` val chop_suffix : string -> string -> string ``` `chop_suffix name suff` removes the suffix `suff` from the filename `name`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if name does not end with the suffix suff. ``` val chop_suffix_opt : suffix:string -> string -> string option ``` `chop_suffix_opt ~suffix filename` removes the suffix from the `filename` if possible, or returns `None` if the filename does not end with the suffix. + Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. + since 4.08 ``` val extension : string -> string ``` `extension name` is the shortest suffix `ext` of `name0` where: + - `name0` is the longest suffix of `name` that does not contain a directory separator; - `ext` starts with a period; - `ext` is preceded by at least one non-period character in `name0`. If such a suffix does not exist, `extension name` is the empty string. + since 4.04 ``` val remove_extension : string -> string ``` Return the given file name without its extension, as defined in [`Filename.extension`](./#val-extension). If the extension is empty, the function returns the given file name. + The following invariant holds for any file name `s`: + `remove_extension s ^ extension s = s` + since 4.04 ``` val chop_extension : string -> string ``` Same as [`Filename.remove_extension`](./#val-remove_extension), but raise `Invalid_argument` if the given name has an empty extension. + ``` val basename : string -> string ``` Split a file name into directory name / base file name. If `name` is a valid file name, then `concat (dirname name) (basename name)` returns a file name which is equivalent to `name`. Moreover, after setting the current directory to `dirname name` (with [`Sys.chdir`](./Stdlib-Sys.md#val-chdir)), references to `basename name` (which is a relative file name) designate the same file as `name` before the call to [`Sys.chdir`](./Stdlib-Sys.md#val-chdir). + This function conforms to the specification of POSIX.1-2008 for the `basename` utility. + ``` val dirname : string -> string ``` See [`Filename.basename`](./#val-basename). This function conforms to the specification of POSIX.1-2008 for the `dirname` utility. + ``` val null : string ``` `null` is `"/dev/null"` on POSIX and `"NUL"` on Windows. It represents a file on the OS that discards all writes and returns end of file on reads. + since 4.10 ``` val temp_file : ?temp_dir:string -> string -> string -> string ``` `temp_file prefix suffix` returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary file is created empty, with permissions `0o600` (readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when `temp_file` was called. + raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be created. before 3.11.2 no ?temp\_dir optional argument ``` @@ -91,6 +116,7 @@ val open_temp_file : string * out_channel ``` Same as [`Filename.temp_file`](./#val-temp_file), but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than `temp_file`: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument `mode` is a list of additional flags to control the opening of the file. It can contain one or several of `Open_append`, `Open_binary`, and `Open_text`. The default is `[Open_text]` (open in text mode). The file is created with permissions `perms` (defaults to readable and writable only by the file owner, `0o600`). + raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be opened. before 4.03 no ?perms optional argument before 3.11.2 no ?temp\_dir optional argument @@ -98,23 +124,28 @@ before 3.11.2 no ?temp\_dir optional argument val temp_dir : ?temp_dir:string -> ?perms:int -> string -> string -> string ``` `temp_dir prefix suffix` creates and returns the name of a fresh temporary directory with permissions `perms` (defaults to 0o700) inside `temp_dir`. The base name of the temporary directory is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary directory is created empty, with permissions `0o700` (readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when `temp_dir` was called. + If temp\_dir does not exist, this function does not create it. Instead, it raises Sys\_error. + raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the directory could not be created. since 5.1 ``` val get_temp_dir_name : unit -> string ``` The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the `TEMP` environment variable, or "." if the variable is not set. The temporary directory can be changed with [`Filename.set_temp_dir_name`](./#val-set_temp_dir_name). + since 4.00 ``` val set_temp_dir_name : string -> unit ``` Change the temporary directory returned by [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name) and used by [`Filename.temp_file`](./#val-temp_file) and [`Filename.open_temp_file`](./#val-open_temp_file). The temporary directory is a domain-local value which is inherited by child domains. + since 4.00 ``` val quote : string -> string ``` Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions. + ``` val quote_command : string -> @@ -125,8 +156,12 @@ val quote_command : string ``` `quote_command cmd args` returns a quoted command line, suitable for use as an argument to [`Sys.command`](./Stdlib-Sys.md#val-command), `Unix.system`, and the `Unix.open_process` functions. + The string `cmd` is the command to call. The list `args` is the list of arguments to pass to this command. It can be empty. + The optional arguments `?stdin` and `?stdout` and `?stderr` are file names used to redirect the standard input, the standard output, or the standard error of the command. If `~stdin:f` is given, a redirection `< f` is performed and the standard input of the command reads from file `f`. If `~stdout:f` is given, a redirection `> f` is performed and the standard output of the command is written to file `f`. If `~stderr:f` is given, a redirection `2> f` is performed and the standard error of the command is written to file `f`. If both `~stdout:f` and `~stderr:f` are given, with the exact same file name `f`, a `2>&1` redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file `f`. + Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using [`Filename.quote`](./#val-quote), then concatenated. Under Win32, additional quoting is performed as required by the `cmd.exe` shell that is called by [`Sys.command`](./Stdlib-Sys.md#val-command). + raises [`Failure`](./Stdlib.md#exception-Failure) if the command cannot be escaped on the current platform. since 4.10 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Float-Array.md b/docs/api/melange/Stdlib-Float-Array.md index 4fad7c009..99c3234de 100644 --- a/docs/api/melange/Stdlib-Float-Array.md +++ b/docs/api/melange/Stdlib-Float-Array.md @@ -1,152 +1,194 @@ + # Module `Float.Array` + Float arrays with packed representation. + ``` type t = floatarray ``` The type of float arrays with packed representation. + since 4.08 ``` val length : t -> int ``` Return the length (number of elements) of the given floatarray. + ``` val get : t -> int -> float ``` `get a n` returns the element number `n` of floatarray `a`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). ``` val set : t -> int -> float -> unit ``` `set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). ``` val make : int -> float -> t ``` `make n x` returns a fresh floatarray of length `n`, initialized with `x`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. ``` val create : int -> t ``` `create n` returns a fresh floatarray of length `n`, with uninitialized data. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. ``` val init : int -> (int -> float) -> t ``` `init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers `0` to `n-1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. ``` val make_matrix : int -> int -> float -> t array ``` `make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where all elements are initialized with `e`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. since 5.2 ``` val init_matrix : int -> int -> (int -> int -> float) -> t array ``` `init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. since 5.2 ``` val append : t -> t -> t ``` `append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_floatarray\_length. ``` val concat : t list -> t ``` Same as [`append`](./#val-append), but concatenates a list of floatarrays. + ``` val sub : t -> int -> int -> t ``` `sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. ``` val copy : t -> t ``` `copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`. + ``` val fill : t -> int -> int -> float -> unit ``` `fill a pos len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. ``` val blit : t -> int -> t -> int -> int -> unit ``` `blit src src_pos dst dst_pos len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. ``` val to_list : t -> float list ``` `to_list a` returns the list of all the elements of `a`. + ``` val of_list : float list -> t ``` `of_list l` returns a fresh floatarray containing the elements of `l`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_floatarray\_length. + ## Iterators + ``` val iter : (float -> unit) -> t -> unit ``` `iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. + ``` val iteri : (int -> float -> unit) -> t -> unit ``` Same as [`iter`](./#val-iter), but the function is applied with the index of the element as first argument, and the element itself as second argument. + ``` val map : (float -> float) -> t -> t ``` `map f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. + ``` val map_inplace : (float -> float) -> t -> unit ``` `map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. + since 5.1 ``` val mapi : (int -> float -> float) -> t -> t ``` Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. + ``` val mapi_inplace : (int -> float -> float) -> t -> unit ``` Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. + since 5.1 ``` val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc ``` `fold_left f x init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`. + ``` val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc ``` `fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`. + + ## Iterators on two arrays + ``` val iter2 : (float -> float -> unit) -> t -> t -> unit ``` `Array.iter2 f a b` applies function `f` to all the elements of `a` and `b`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. ``` val map2 : (float -> float -> float) -> t -> t -> t ``` `map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. + ## Array scanning + ``` val for_all : (float -> bool) -> t -> bool ``` `for_all f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. + ``` val exists : (float -> bool) -> t -> bool ``` `exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. + ``` val mem : float -> t -> bool ``` `mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`. + ``` val mem_ieee : float -> t -> bool ``` Same as [`mem`](./#val-mem), but uses IEEE equality instead of structural equality. + + ## Array searching + ``` val find_opt : (float -> bool) -> t -> float option ``` @@ -154,7 +196,9 @@ val find_opt : (float -> bool) -> t -> float option val find_index : (float -> bool) -> t -> int option ``` `find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + It returns `None` if there is no such element. + since 5.1 ``` val find_map : (float -> 'a option) -> t -> 'a option @@ -163,59 +207,85 @@ val find_map : (float -> 'a option) -> t -> 'a option val find_mapi : (int -> float -> 'a option) -> t -> 'a option ``` Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 5.1 + ## Sorting and shuffling + ``` val sort : (float -> float -> int) -> t -> unit ``` Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. + The current implementation uses Heap Sort. It runs in constant stack space. + Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : + - `cmp x y` \> 0 if and only if `cmp y x` \< 0 - if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : + - `cmp a.(i) a.(j)` \>= 0 if i \>= j ``` val stable_sort : (float -> float -> int) -> t -> unit ``` Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. + The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of [`sort`](./#val-sort). + ``` val fast_sort : (float -> float -> int) -> t -> unit ``` Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + ``` val shuffle : rand:(int -> int) -> t -> unit ``` `shuffle rand a` randomly permutes `a`'s elements using `rand` for randomness. The distribution of permutations is uniform. + `rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). + since 5.2 + ## Float arrays and Sequences + ``` val to_seq : t -> float Seq.t ``` Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence. + ``` val to_seqi : t -> (int * float) Seq.t ``` Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence. + ``` val of_seq : float Seq.t -> t ``` Create an array from the generator. + ``` val map_to_array : (float -> 'a) -> t -> 'a array ``` `map_to_array f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. + ``` val map_from_array : ('a -> float) -> 'a array -> t ``` `map_from_array f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. + + ## Arrays and concurrency safety + Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + ### Atomicity + Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. + For example, consider the following program: + ```ocaml let size = 100_000_000 let a = Float.Array.make size 1. @@ -226,15 +296,27 @@ let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.)) let () = Domain.join d1; Domain.join d2 ``` After executing this code, each field of the float array `a` is either `2.`, `3.`, `4.` or `5.`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ### Data races + If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. + Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions. + + ### Tearing + Float arrays have two supplementary caveats in the presence of data races. + First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. + For instance, at the end of + ```ocaml let zeros = Float.Array.make size 0. let max_floats = Float.Array.make size Float.max_float @@ -244,4 +326,5 @@ let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size) let () = Domain.join d1; Domain.join d2 ``` the `res` float array might contain values that are neither `0.` nor `max_float`. -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. \ No newline at end of file + +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/melange/Stdlib-Float.md b/docs/api/melange/Stdlib-Float.md index 26062df73..29ecfd718 100644 --- a/docs/api/melange/Stdlib-Float.md +++ b/docs/api/melange/Stdlib-Float.md @@ -1,148 +1,187 @@ + # Module `Stdlib.Float` + Floating-point arithmetic. + OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... + since 4.07 ``` val zero : float ``` The floating point 0. + since 4.08 ``` val one : float ``` The floating-point 1\. + since 4.08 ``` val minus_one : float ``` The floating-point \-1. + since 4.08 ``` val neg : float -> float ``` Unary negation. + ``` val add : float -> float -> float ``` Floating-point addition. + ``` val sub : float -> float -> float ``` Floating-point subtraction. + ``` val mul : float -> float -> float ``` Floating-point multiplication. + ``` val div : float -> float -> float ``` Floating-point division. + ``` val fma : float -> float -> float -> float ``` `fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation. + On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters. + since 4.08 ``` val rem : float -> float -> float ``` `rem a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. + ``` val succ : float -> float ``` `succ x` returns the floating point number right after `x` i.e., the smallest floating-point number greater than `x`. See also [`next_after`](./#val-next_after). + since 4.08 ``` val pred : float -> float ``` `pred x` returns the floating-point number right before `x` i.e., the greatest floating-point number smaller than `x`. See also [`next_after`](./#val-next_after). + since 4.08 ``` val abs : float -> float ``` `abs f` returns the absolute value of `f`. + ``` val infinity : float ``` Positive infinity. + ``` val neg_infinity : float ``` Negative infinity. + ``` val nan : float ``` A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. Stands for 'not a number'. Any floating-point operation with `nan` as argument returns `nan` as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, `=`, `<`, `<=`, `>` and `>=` return `false` and `<>` returns `true` if one or both of their arguments is `nan`. + `nan` is `quiet_nan` since 5.1; it was a signaling NaN before. + ``` val signaling_nan : float ``` Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries. + since 5.1 ``` val quiet_nan : float ``` Quiet NaN. + since 5.1 ``` val pi : float ``` The constant pi. + ``` val max_float : float ``` The largest positive finite value of type `float`. + ``` val min_float : float ``` The smallest positive, non-zero, non-denormalized value of type `float`. + ``` val epsilon : float ``` The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. + ``` val is_finite : float -> bool ``` `is_finite x` is `true` if and only if `x` is finite i.e., not infinite and not [`nan`](./#val-nan). + since 4.08 ``` val is_infinite : float -> bool ``` `is_infinite x` is `true` if and only if `x` is [`infinity`](./#val-infinity) or [`neg_infinity`](./#val-neg_infinity). + since 4.08 ``` val is_nan : float -> bool ``` `is_nan x` is `true` if and only if `x` is not a number (see [`nan`](./#val-nan)). + since 4.08 ``` val is_integer : float -> bool ``` `is_integer x` is `true` if and only if `x` is an integer. + since 4.08 ``` val of_int : int -> float ``` Convert an integer to floating-point. + ``` val to_int : float -> int ``` Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. + ``` val of_string : string -> float ``` Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The `_` (underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. + raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of a float. ``` val of_string_opt : string -> float option ``` Same as `of_string`, but returns `None` instead of raising. + ``` val to_string : float -> string ``` Return a string representation of a floating-point number. + This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). + This function is an alias for [`Stdlib.string_of_float`](./Stdlib.md#val-string_of_float). + ``` type fpclass = fpclass = ``` @@ -150,239 +189,294 @@ type fpclass = fpclass = | FP_normal ``` Normal number, none of the below + ``` | FP_subnormal ``` Number very close to 0.0, has reduced precision + ``` | FP_zero ``` Number is 0.0 or \-0.0 + ``` | FP_infinite ``` Number is positive or negative infinity + ``` | FP_nan ``` Not a number: result of an undefined operation + ``` ``` The five classes of floating-point numbers, as determined by the [`classify_float`](./#val-classify_float) function. + ``` val classify_float : float -> fpclass ``` Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number. + ``` val pow : float -> float -> float ``` Exponentiation. + ``` val sqrt : float -> float ``` Square root. + ``` val cbrt : float -> float ``` Cube root. + since 4.13 ``` val exp : float -> float ``` Exponential. + ``` val exp2 : float -> float ``` Base 2 exponential function. + since 4.13 ``` val log : float -> float ``` Natural logarithm. + ``` val log10 : float -> float ``` Base 10 logarithm. + ``` val log2 : float -> float ``` Base 2 logarithm. + since 4.13 ``` val expm1 : float -> float ``` `expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. + ``` val log1p : float -> float ``` `log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. + ``` val cos : float -> float ``` Cosine. Argument is in radians. + ``` val sin : float -> float ``` Sine. Argument is in radians. + ``` val tan : float -> float ``` Tangent. Argument is in radians. + ``` val acos : float -> float ``` Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. + ``` val asin : float -> float ``` Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. + ``` val atan : float -> float ``` Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. + ``` val atan2 : float -> float -> float ``` `atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. + ``` val hypot : float -> float -> float ``` `hypot x y` returns `sqrt(x *. x +. y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. If one of `x` or `y` is infinite, returns `infinity` even if the other is `nan`. + ``` val cosh : float -> float ``` Hyperbolic cosine. Argument is in radians. + ``` val sinh : float -> float ``` Hyperbolic sine. Argument is in radians. + ``` val tanh : float -> float ``` Hyperbolic tangent. Argument is in radians. + ``` val acosh : float -> float ``` Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. + since 4.13 ``` val asinh : float -> float ``` Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. + since 4.13 ``` val atanh : float -> float ``` Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. + since 4.13 ``` val erf : float -> float ``` Error function. The argument ranges over the entire real line. The result is always within `[-1.0, 1.0]`. + since 4.13 ``` val erfc : float -> float ``` Complementary error function (`erfc x = 1 - erf x`). The argument ranges over the entire real line. The result is always within `[0.0, 2.0]`. + since 4.13 ``` val trunc : float -> float ``` `trunc x` rounds `x` to the nearest integer whose absolute value is less than or equal to `x`. + since 4.08 ``` val round : float -> float ``` `round x` rounds `x` to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If `x` is an integer, `+0.`, `-0.`, `nan`, or infinite, `x` itself is returned. + On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform. + since 4.08 ``` val ceil : float -> float ``` Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. + ``` val floor : float -> float ``` Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. + ``` val next_after : float -> float -> float ``` `next_after x y` returns the next representable floating-point value following `x` in the direction of `y`. More precisely, if `y` is greater (resp. less) than `x`, it returns the smallest (resp. largest) representable number greater (resp. less) than `x`. If `x` equals `y`, the function returns `y`. If `x` or `y` is `nan`, a `nan` is returned. Note that `next_after max_float infinity = infinity` and that `next_after 0. infinity` is the smallest denormalized positive number. If `x` is the smallest denormalized positive number, `next_after x 0. = 0.` + since 4.08 ``` val copy_sign : float -> float -> float ``` `copy_sign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. + ``` val sign_bit : float -> bool ``` `sign_bit x` is `true` if and only if the sign bit of `x` is set. For example `sign_bit 1.` and `signbit 0.` are `false` while `sign_bit (-1.)` and `sign_bit (-0.)` are `true`. + since 4.08 ``` val frexp : float -> float * int ``` `frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. + ``` val ldexp : float -> int -> float ``` `ldexp x n` returns `x *. 2 ** n`. + ``` val modf : float -> float * float ``` `modf f` returns the pair of the fractional and integral part of `f`. + ``` type t = float ``` An alias for the type of floating-point numbers. + ``` val compare : t -> t -> int ``` `compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. + ``` val equal : t -> t -> bool ``` The equal function for floating-point numbers, compared using [`compare`](./#val-compare). + ``` val min : t -> t -> t ``` `min x y` returns the minimum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `min (-0.) (+0.) = -0.` + since 4.08 ``` val max : float -> float -> float ``` `max x y` returns the maximum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `max (-0.) (+0.) = +0.` + since 4.08 ``` val min_max : float -> float -> float * float ``` `min_max x y` is `(min x y, max x y)`, just more efficient. + since 4.08 ``` val min_num : t -> t -> t ``` `min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `min_num (-0.) (+0.) = -0.` + since 4.08 ``` val max_num : t -> t -> t ``` `max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan` `nan` is returned. Moreover `max_num (-0.) (+0.) = +0.` + since 4.08 ``` val min_max_num : float -> float -> float * float ``` `min_max_num x y` is `(min_num x y, max_num x y)`, just more efficient. Note that in particular `min_max_num x nan = (x, x)` and `min_max_num nan y = (y, y)`. + since 4.08 ``` val seeded_hash : int -> t -> int ``` A seeded hash function for floats, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.1 ``` val hash : t -> int ``` An unseeded hash function for floats, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + ``` module Array : sig ... end ``` -Float arrays with packed representation. \ No newline at end of file +Float arrays with packed representation. diff --git a/docs/api/melange/Stdlib-Format.md b/docs/api/melange/Stdlib-Format.md index e8596f2ab..92440e239 100644 --- a/docs/api/melange/Stdlib-Format.md +++ b/docs/api/melange/Stdlib-Format.md @@ -1,42 +1,71 @@ + # Module `Stdlib.Format` + Pretty-printing. + If you are new to this module, see the [examples](./#examples) below. + This module implements a pretty-printing facility to format values within ['pretty-printing boxes'](./#boxes) and ['semantic tags'](./#tags) combined with a set of [printf-like functions](./#fpp). The pretty-printer splits lines at specified [break hints](./#breaks), and indents lines according to the box structure. Similarly, [semantic tags](./#tags) can be used to decouple text presentation from its contents. + This pretty-printing facility is implemented as an overlay on top of abstract [formatters](./#formatter) which provide basic output functions. Some formatters are predefined, notably: + - [`std_formatter`](./#val-std_formatter) outputs to [stdout](./Stdlib.md#val-stdout) - [`err_formatter`](./#val-err_formatter) outputs to [stderr](./Stdlib.md#val-stderr) Most functions in the [`Format`](#) module come in two variants: a short version that operates on the current domain's standard formatter as obtained using [`get_std_formatter`](./#val-get_std_formatter) and the generic version prefixed by `pp_` that takes a formatter as its first argument. For the version that operates on the current domain's standard formatter, the call to [`get_std_formatter`](./#val-get_std_formatter) is delayed until the last argument is received. + More formatters can be created with [`formatter_of_out_channel`](./#val-formatter_of_out_channel), [`formatter_of_buffer`](./#val-formatter_of_buffer), [`formatter_of_symbolic_output_buffer`](./#val-formatter_of_symbolic_output_buffer) or using [custom formatters](./#formatter). + **Warning**: Since [formatters](./#formatter) contain mutable state, it is not thread-safe to use the same formatter on multiple domains in parallel without synchronization. + If multiple domains write to the same output channel using the predefined formatters (as obtained by [`get_std_formatter`](./#val-get_std_formatter) or [`get_err_formatter`](./#val-get_err_formatter)), the output from the domains will be interleaved with each other at points where the formatters are flushed, such as with [`print_flush`](./#val-print_flush). This synchronization is not performed by formatters obtained from [`formatter_of_out_channel`](./#val-formatter_of_out_channel) (on the standard out channels or others). + + ## Introduction + You may consider this module as providing an extension to the `printf` facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular `printf` format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function [`Format.fprintf`](./#val-fprintf). + You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise `fprintf` format strings. + For instance, the sequence `open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()` that prints `x = 1` within a pretty-printing box, can be abbreviated as `printf "@[%s@ %i@]@." "x =" 1`, or even shorter `printf "@[x =@ %i@]@." 1`. + Rule of thumb for casual users of this library: + - use simple pretty-printing boxes (as obtained by `open_box 0`); - use simple break hints as obtained by `print_cut ()` that outputs a simple break hint, or by `print_space ()` that outputs a space indicating a break hint; - once a pretty-printing box is open, display its material with basic printing functions (e. g. `print_int` and `print_string`); - when the material for a pretty-printing box has been printed, call `close_box ()` to close the box; - at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate `print_newline ()`. The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the `open_` functions below must be closed using `close_box` for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. + In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer. + Warning: mixing calls to pretty-printing functions of this module with calls to [`Stdlib`](./Stdlib.md) low level output functions is error prone. + The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, ` Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT"; ` leads to output `<>PRETTYTEXT`. + + ## Formatters + ``` type formatter ``` Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also [Defining formatters](./#formatter). + + ## Pretty-printing boxes + The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer. + Each different pretty-printing box kind introduces a specific line splitting policy: + - within an *horizontal* box, break hints never split the line (but the line may be split in a box nested deeper), - within a *vertical* box, break hints always split the line, - within an *horizontal/vertical* box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line, - within a *compacting* box, a break hint never splits the line, unless there is no more room on the current line. Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line. + Moreover, opening a box after the [maximum indentation limit](./#maxindent) splits the line whether or not the box would end up fitting on the line. + ``` val pp_open_box : formatter -> int -> unit ``` @@ -44,11 +73,17 @@ val pp_open_box : formatter -> int -> unit val open_box : int -> unit ``` `pp_open_box ppf d` opens a new compacting pretty-printing box with offset `d` in the formatter `ppf`. + Within this box, the pretty-printer prints as much as possible material on every line. + A break hint splits the line if there is no more room on the line to print the remainder of the box. + Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting \``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line). + This box is the general purpose pretty-printing box. + If the pretty-printer splits the line in the box, offset `d` is added to the current indentation. + ``` val pp_close_box : formatter -> unit -> unit ``` @@ -56,6 +91,7 @@ val pp_close_box : formatter -> unit -> unit val close_box : unit -> unit ``` Closes the most recently open pretty-printing box. + ``` val pp_open_hbox : formatter -> unit -> unit ``` @@ -63,8 +99,11 @@ val pp_open_hbox : formatter -> unit -> unit val open_hbox : unit -> unit ``` `pp_open_hbox ppf ()` opens a new 'horizontal' pretty-printing box. + This box prints material on a single line. + Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper). + ``` val pp_open_vbox : formatter -> int -> unit ``` @@ -72,9 +111,13 @@ val pp_open_vbox : formatter -> int -> unit val open_vbox : int -> unit ``` `pp_open_vbox ppf d` opens a new 'vertical' pretty-printing box with offset `d`. + This box prints material on as many lines as break hints in the box. + Every break hint in a vertical box splits the line. + If the pretty-printer splits the line in the box, `d` is added to the current indentation. + ``` val pp_open_hvbox : formatter -> int -> unit ``` @@ -82,8 +125,11 @@ val pp_open_hvbox : formatter -> int -> unit val open_hvbox : int -> unit ``` `pp_open_hvbox ppf d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`. + This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box. + If the pretty-printer splits the line in the box, `d` is added to the current indentation. + ``` val pp_open_hovbox : formatter -> int -> unit ``` @@ -91,10 +137,16 @@ val pp_open_hovbox : formatter -> int -> unit val open_hovbox : int -> unit ``` `pp_open_hovbox ppf d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`. + This box prints material as much as possible on every line. + A break hint splits the line if there is no more room on the line to print the remainder of the box. + If the pretty-printer splits the line in the box, `d` is added to the current indentation. + + ## Formatting functions + ``` val pp_print_string : formatter -> string -> unit ``` @@ -102,6 +154,7 @@ val pp_print_string : formatter -> string -> unit val print_string : string -> unit ``` `pp_print_string ppf s` prints `s` in the current pretty-printing box. + ``` val pp_print_substring : pos:int -> len:int -> formatter -> string -> unit ``` @@ -109,6 +162,7 @@ val pp_print_substring : pos:int -> len:int -> formatter -> string -> unit val print_substring : pos:int -> len:int -> string -> unit ``` `pp_print_substring ~pos ~len ppf s` prints the substring of `s` that starts at position `pos` and stops at position `pos+len` in the current pretty-printing box. + since 5.3 ``` val pp_print_bytes : formatter -> bytes -> unit @@ -117,6 +171,7 @@ val pp_print_bytes : formatter -> bytes -> unit val print_bytes : bytes -> unit ``` `pp_print_bytes ppf b` prints `b` in the current pretty-printing box. + since 4.13 ``` val pp_print_as : formatter -> int -> string -> unit @@ -125,6 +180,7 @@ val pp_print_as : formatter -> int -> string -> unit val print_as : int -> string -> unit ``` `pp_print_as ppf len s` prints `s` in the current pretty-printing box. The pretty-printer formats `s` as if it were of length `len`. + ``` val pp_print_substring_as : pos:int -> @@ -138,6 +194,7 @@ val pp_print_substring_as : val print_substring_as : pos:int -> len:int -> int -> string -> unit ``` `pp_print_substring_as ~first ~len ppf len_as s` prints the substring of `s` that starts at position `pos` and stop at position `pos+len` in the current pretty-printing box as if it were of length `len_as`. + since 5.1 ``` val pp_print_int : formatter -> int -> unit @@ -146,6 +203,7 @@ val pp_print_int : formatter -> int -> unit val print_int : int -> unit ``` Print an integer in the current pretty-printing box. + ``` val pp_print_float : formatter -> float -> unit ``` @@ -153,6 +211,7 @@ val pp_print_float : formatter -> float -> unit val print_float : float -> unit ``` Print a floating point number in the current pretty-printing box. + ``` val pp_print_char : formatter -> char -> unit ``` @@ -160,6 +219,7 @@ val pp_print_char : formatter -> char -> unit val print_char : char -> unit ``` Print a character in the current pretty-printing box. + ``` val pp_print_bool : formatter -> bool -> unit ``` @@ -167,18 +227,26 @@ val pp_print_bool : formatter -> bool -> unit val print_bool : bool -> unit ``` Print a boolean in the current pretty-printing box. + ``` val pp_print_nothing : formatter -> unit -> unit ``` Print nothing. + since 5.2 + ## Break hints + A 'break hint' tells the pretty-printer to output some space or split the line whichever way is more appropriate to the current pretty-printing box splitting rules. + Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items. + Simple break hints are: + - the 'space': output a space or split the line if appropriate, - the 'cut': split the line if appropriate. Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, \``output a space'' simply means printing a space character (ASCII code 32) and \``split the line'' means printing a newline character (ASCII code 10). + ``` val pp_print_space : formatter -> unit -> unit ``` @@ -186,7 +254,9 @@ val pp_print_space : formatter -> unit -> unit val print_space : unit -> unit ``` `pp_print_space ppf ()` emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space. + `pp_print_space ppf ()` is equivalent to `pp_print_break ppf 1 0`. + ``` val pp_print_cut : formatter -> unit -> unit ``` @@ -194,7 +264,9 @@ val pp_print_cut : formatter -> unit -> unit val print_cut : unit -> unit ``` `pp_print_cut ppf ()` emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing. + `pp_print_cut ppf ()` is equivalent to `pp_print_break ppf 0 0`. + ``` val pp_print_break : formatter -> int -> int -> unit ``` @@ -202,7 +274,9 @@ val pp_print_break : formatter -> int -> int -> unit val print_break : int -> int -> unit ``` `pp_print_break ppf nspaces offset` emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints `nspaces` spaces. + If the pretty-printer splits the line, `offset` is added to the current indentation. + ``` val pp_print_custom_break : formatter -> @@ -211,10 +285,15 @@ val pp_print_custom_break : unit ``` `pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4)` emits a custom break hint: the pretty-printer may split the line at this point. + If it does not split the line, then the `s1` is emitted, then `n` spaces, then `s2`. + If it splits the line, then it emits the `s3` string, then an indent (according to the box rules), then an offset of `m` spaces, then the `s4` string. + While `n` and `m` are handled by `formatter_out_functions.out_indent`, the strings will be handled by `formatter_out_functions.out_string`. This allows for a custom formatter that handles indentation distinctly, for example, outputs `
` tags or ` ` entities. + The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list ` [a; b; c] `, you might want to add a trailing semicolon when it is printed vertically: + ```ocaml [ a; @@ -223,6 +302,7 @@ The custom break is useful if you want to change which visible (non-whitespace) ] ``` You can do this as follows: + ```ocaml printf "@[[@;<0 2>@[a;@,b;@,c@]%t]@]@\n" (pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, "")) @@ -235,8 +315,11 @@ val pp_force_newline : formatter -> unit -> unit val force_newline : unit -> unit ``` Force a new line in the current pretty-printing box. + The pretty-printer must split the line at this point, + Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative. + ``` val pp_print_if_newline : formatter -> unit -> unit ``` @@ -244,7 +327,10 @@ val pp_print_if_newline : formatter -> unit -> unit val print_if_newline : unit -> unit ``` Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. + + ## Pretty-printing termination + ``` val pp_print_flush : formatter -> unit -> unit ``` @@ -252,10 +338,15 @@ val pp_print_flush : formatter -> unit -> unit val print_flush : unit -> unit ``` End of pretty-printing: resets the pretty-printer to initial state. + All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed. + Note: never use `print_flush` in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering. + Only consider using `print_flush` when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing. + Warning: If the output device of the pretty-printer is an output channel, repeated calls to `print_flush` means repeated calls to [`Stdlib.flush`](./Stdlib.md#val-flush) to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency. + ``` val pp_print_newline : formatter -> unit -> unit ``` @@ -263,14 +354,21 @@ val pp_print_newline : formatter -> unit -> unit val print_newline : unit -> unit ``` End of pretty-printing: resets the pretty-printer to initial state. + All open pretty-printing boxes are closed, all pending text is printed. + Equivalent to [`print_flush`](./#val-print_flush) with a new line emitted on the pretty-printer low-level output device immediately before the device is flushed. See corresponding words of caution for [`print_flush`](./#val-print_flush). + Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box. + + ## Margin + ``` val pp_infinity : int ``` `pp_infinity` is the maximal size of the margin. Its exact value is implementation dependent but is guaranteed to be greater than 109. + since 5.2 ``` val pp_set_margin : formatter -> int -> unit @@ -279,7 +377,9 @@ val pp_set_margin : formatter -> int -> unit val set_margin : int -> unit ``` `pp_set_margin ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to `d` means that the formatting engine aims at printing at most `d-1` characters per line. Nothing happens if `d` is smaller than 2. If `d >= `[`pp_infinity`](./#val-pp_infinity), the right margin is set to [`pp_infinity`](./#val-pp_infinity)` - 1`. If `d` is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio `max_indent/margin>=50%` and if possible the current difference `margin - max_indent`. + See also [`pp_set_geometry`](./#val-pp_set_geometry). + ``` val pp_get_margin : formatter -> unit -> int ``` @@ -287,7 +387,10 @@ val pp_get_margin : formatter -> unit -> int val get_margin : unit -> int ``` Returns the position of the right margin. + + ## Maximum indentation limit + ``` val pp_set_max_indent : formatter -> int -> unit ``` @@ -295,26 +398,34 @@ val pp_set_max_indent : formatter -> int -> unit val set_max_indent : int -> unit ``` `pp_set_max_indent ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration, + ```ocaml set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." ``` yields + ```ocaml 123456 789A ``` because the nested box `"@[7@]"` is opened after the maximum indentation limit (`7>5`) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line: + ```ocaml printf "@[123456@[7@]89@]@." ``` or opening an intermediary box before the maximum indentation limit which fits on the current line + ```ocaml printf "@[123@[456@[7@]89@]A@]@." ``` avoids the rejection to the left of the inner boxes and print respectively `"123456789"` and `"123456789A"` . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to `margin - 1`. Note that setting the maximum indentation limit to `margin` is invalid. + Nothing happens if `d` is smaller than 2. + If `d` is greater than the current margin, it is ignored, and the current maximum indentation limit is kept. + See also [`pp_set_geometry`](./#val-pp_set_geometry). + ``` val pp_get_max_indent : formatter -> unit -> int ``` @@ -322,8 +433,12 @@ val pp_get_max_indent : formatter -> unit -> int val get_max_indent : unit -> int ``` Return the maximum indentation limit (in characters). + + ## Geometry + Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maximum indentation limit. + ``` type geometry = { ``` @@ -337,6 +452,7 @@ since 4.08 val check_geometry : geometry -> bool ``` Check if the formatter geometry is valid: `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity) + since 4.08 ``` val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit @@ -351,14 +467,19 @@ val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit val safe_set_geometry : max_indent:int -> margin:int -> unit ``` `pp_set_geometry ppf ~max_indent ~margin` sets both the margin and maximum indentation limit for `ppf`. + When `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity), `pp_set_geometry ppf ~max_indent ~margin` is equivalent to `pp_set_margin ppf margin; pp_set_max_indent ppf max_indent`; and avoids the subtly incorrect `pp_set_max_indent ppf max_indent; pp_set_margin ppf margin`; + Outside of this domain, `pp_set_geometry` raises an invalid argument exception whereas `pp_safe_set_geometry` does nothing. + since 4.08 ``` val pp_update_geometry : formatter -> (geometry -> geometry) -> unit ``` `pp_update_geometry ppf (fun geo -> { geo with ... })` lets you update a formatter's geometry in a way that is robust to extension of the `geometry` record with new fields. + Raises an invalid argument exception if the returned geometry does not satisfy [`check_geometry`](./#val-check_geometry). + since 4.11 ``` val update_geometry : (geometry -> geometry) -> unit @@ -370,10 +491,15 @@ val pp_get_geometry : formatter -> unit -> geometry val get_geometry : unit -> geometry ``` Return the current geometry of the formatter + since 4.08 + ## Maximum formatting depth + The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open. + Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). + ``` val pp_set_max_boxes : formatter -> int -> unit ``` @@ -381,8 +507,11 @@ val pp_set_max_boxes : formatter -> int -> unit val set_max_boxes : int -> unit ``` `pp_set_max_boxes ppf max` sets the maximum number of pretty-printing boxes simultaneously open. + Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). + Nothing happens if `max` is smaller than 2. + ``` val pp_get_max_boxes : formatter -> unit -> int ``` @@ -390,6 +519,7 @@ val pp_get_max_boxes : formatter -> unit -> int val get_max_boxes : unit -> int ``` Returns the maximum number of pretty-printing boxes allowed before ellipsis. + ``` val pp_over_max_boxes : formatter -> unit -> bool ``` @@ -397,10 +527,16 @@ val pp_over_max_boxes : formatter -> unit -> bool val over_max_boxes : unit -> bool ``` Tests if the maximum number of pretty-printing boxes allowed have already been opened. + + ## Tabulation boxes + A *tabulation box* prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text. + This box features command `set_tab` to define cell boundaries, and command `print_tab` to move from cell to cell and split the line when there is no more cells to print on the line. + Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module [`Format`](#). + ``` val pp_open_tbox : formatter -> unit -> unit ``` @@ -408,9 +544,13 @@ val pp_open_tbox : formatter -> unit -> unit val open_tbox : unit -> unit ``` `open_tbox ()` opens a new tabulation box. + This box prints lines separated into cells of fixed width. + Inside a tabulation box, special *tabulation markers* defines points of interest on the line (for instance to delimit cell boundaries). Function [`Format.set_tab`](./#val-set_tab) sets a tabulation marker at insertion point. + A tabulation box features specific *tabulation breaks* to move to next tabulation marker or split the line. Function [`Format.print_tbreak`](./#val-print_tbreak) prints a tabulation break. + ``` val pp_close_tbox : formatter -> unit -> unit ``` @@ -418,6 +558,7 @@ val pp_close_tbox : formatter -> unit -> unit val close_tbox : unit -> unit ``` Closes the most recently opened tabulation box. + ``` val pp_set_tab : formatter -> unit -> unit ``` @@ -425,6 +566,7 @@ val pp_set_tab : formatter -> unit -> unit val set_tab : unit -> unit ``` Sets a tabulation marker at current insertion point. + ``` val pp_print_tab : formatter -> unit -> unit ``` @@ -432,7 +574,9 @@ val pp_print_tab : formatter -> unit -> unit val print_tab : unit -> unit ``` `print_tab ()` emits a 'next' tabulation break hint: if not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. + It is equivalent to `print_tbreak 0 0`. + ``` val pp_print_tbreak : formatter -> int -> int -> unit ``` @@ -440,10 +584,16 @@ val pp_print_tbreak : formatter -> int -> int -> unit val print_tbreak : int -> int -> unit ``` `print_tbreak nspaces offset` emits a 'full' tabulation break hint. + If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints `nspaces` spaces. + If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box. + If the pretty-printer splits the line, `offset` is added to the current indentation. + + ## Ellipsis + ``` val pp_set_ellipsis_text : formatter -> string -> unit ``` @@ -451,6 +601,7 @@ val pp_set_ellipsis_text : formatter -> string -> unit val set_ellipsis_text : string -> unit ``` Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, `.`, by default). + ``` val pp_get_ellipsis_text : formatter -> unit -> string ``` @@ -458,29 +609,44 @@ val pp_get_ellipsis_text : formatter -> unit -> string val get_ellipsis_text : unit -> string ``` Return the text of the ellipsis. + + ## Semantic tags + ``` type stag = .. ``` *Semantic tags* (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities. + Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so: + ```ocaml type stag += RGB of {r:int;g:int;b:int} ``` In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using [`pp_open_stag`](./#val-pp_open_stag) and [`pp_close_stag`](./#val-pp_close_stag). + Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed *tag-marking* and *tag-printing*: + - The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation. - The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations. Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output). + More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur: + - Tag-printing a semantic tag means calling the formatter specific function `print_open_stag` (resp. `print_close_stag`) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation). - Tag-marking a semantic tag means calling the formatter specific function `mark_open_stag` (resp. `mark_close_stag`) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. \`tag-closing marker') for direct output into the output device of the formatter. Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting). + Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once `set_tags` is set to `true`, the pretty-printer engine honors tags and decorates the output accordingly. + Default tag-marking functions behave the HTML way: [string tags](./#type-tag) are enclosed in "\<" and "\>" while other tags are ignored; hence, opening marker for tag string `"t"` is `""` and closing marker is `""`. + Default tag-printing functions just do nothing. + Tag-marking and tag-printing functions are user definable and can be set by calling [`set_formatter_stag_functions`](./#val-set_formatter_stag_functions). + Semantic tag operations may be set on or off with [`set_tags`](./#val-set_tags). Tag-marking operations may be set on or off with [`set_mark_tags`](./#val-set_mark_tags). Tag-printing operations may be set on or off with [`set_print_tags`](./#val-set_print_tags). + since 4.08 ``` type tag = string @@ -492,6 +658,7 @@ type stag += | String_tag of tag ``` `String_tag s` is a string tag `s`. String tags can be inserted either by explicitly using the constructor `String_tag` or by using the dedicated format syntax `"@{ ... @}"`. + since 4.08 ``` @@ -503,7 +670,9 @@ val pp_open_stag : formatter -> stag -> unit val open_stag : stag -> unit ``` `pp_open_stag ppf t` opens the semantic tag named `t`. + The `print_open_stag` tag-printing function of the formatter is called with `t` as argument; then the opening tag marker for `t`, as given by `mark_open_stag t`, is written into the output device of the formatter. + since 4.08 ``` val pp_close_stag : formatter -> unit -> unit @@ -512,7 +681,9 @@ val pp_close_stag : formatter -> unit -> unit val close_stag : unit -> unit ``` `pp_close_stag ppf ()` closes the most recently opened semantic tag `t`. + The closing tag marker, as given by `mark_close_stag t`, is written into the output device of the formatter; then the `print_close_stag` tag-printing function of the formatter is called with `t` as argument. + since 4.08 ``` val pp_set_tags : formatter -> bool -> unit @@ -521,6 +692,7 @@ val pp_set_tags : formatter -> bool -> unit val set_tags : bool -> unit ``` `pp_set_tags ppf b` turns on or off the treatment of semantic tags (default is off). + ``` val pp_set_print_tags : formatter -> bool -> unit ``` @@ -528,6 +700,7 @@ val pp_set_print_tags : formatter -> bool -> unit val set_print_tags : bool -> unit ``` `pp_set_print_tags ppf b` turns on or off the tag-printing operations. + ``` val pp_set_mark_tags : formatter -> bool -> unit ``` @@ -535,6 +708,7 @@ val pp_set_mark_tags : formatter -> bool -> unit val set_mark_tags : bool -> unit ``` `pp_set_mark_tags ppf b` turns on or off the tag-marking operations. + ``` val pp_get_print_tags : formatter -> unit -> bool ``` @@ -542,6 +716,7 @@ val pp_get_print_tags : formatter -> unit -> bool val get_print_tags : unit -> bool ``` Return the current status of tag-printing operations. + ``` val pp_get_mark_tags : formatter -> unit -> bool ``` @@ -549,15 +724,19 @@ val pp_get_mark_tags : formatter -> unit -> bool val get_mark_tags : unit -> bool ``` Return the current status of tag-marking operations. + ``` val pp_set_formatter_out_channel : formatter -> out_channel -> unit ``` Redirecting the standard formatter output + ``` val set_formatter_out_channel : out_channel -> unit ``` Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.) + `set_formatter_out_channel` is equivalent to [`pp_set_formatter_out_channel`](./#val-pp_set_formatter_out_channel) `std_formatter`. + ``` val pp_set_formatter_output_functions : formatter -> @@ -572,8 +751,11 @@ val set_formatter_output_functions : unit ``` `pp_set_formatter_output_functions ppf out flush` redirects the standard pretty-printer output functions to the functions `out` and `flush`. + The `out` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. + The `flush` function is called whenever the pretty-printer is flushed (via conversion `%!`, or pretty-printing indications `@?` or `@.`, or using low level functions `print_flush` or `print_newline`). + ``` val pp_get_formatter_output_functions : formatter -> @@ -586,9 +768,15 @@ val get_formatter_output_functions : (string -> int -> int -> unit) * (unit -> unit) ``` Return the current output functions of the standard pretty-printer. + + ## Redefining formatter output + The `Format` module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed\! + + ### Redefining output functions + ``` type formatter_out_functions = { ``` @@ -602,12 +790,14 @@ since 4.06 } ``` The set of output functions specific to a formatter: + - the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. - the `out_flush` function flushes the pretty-printer output device. - `out_newline` is called to open a new line when the pretty-printer splits the line. - the `out_spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output. - the `out_indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. By default: + - fields `out_string` and `out_flush` are output device specific; (e.g. [`Stdlib.output_string`](./Stdlib.md#val-output_string) and [`Stdlib.flush`](./Stdlib.md#val-flush) for a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) device, or `Buffer.add_substring` and [`Stdlib.ignore`](./Stdlib.md#val-ignore) for a `Buffer.t` output device), - field `out_newline` is equivalent to `out_string "\n" 0 1`; - fields `out_spaces` and `out_indent` are equivalent to `out_string (String.make n ' ') 0 n`. @@ -622,8 +812,11 @@ val pp_set_formatter_out_functions : val set_formatter_out_functions : formatter_out_functions -> unit ``` `pp_set_formatter_out_functions ppf out_funs` Set all the pretty-printer output functions of `ppf` to those of argument `out_funs`, + This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand). + Reasonable defaults for functions `out_spaces` and `out_newline` are respectively `out_funs.out_string (String.make n ' ') 0 n` and `out_funs.out_string "\n" 0 1`. + since 4.01 ``` val pp_get_formatter_out_functions : @@ -635,8 +828,11 @@ val pp_get_formatter_out_functions : val get_formatter_out_functions : unit -> formatter_out_functions ``` Return the current output functions of the pretty-printer, including line splitting and indentation functions. Useful to record the current setting and restore it afterwards. + since 4.01 + ## Redefining semantic tag operations + ``` type formatter_stag_functions = { ``` @@ -648,6 +844,7 @@ type formatter_stag_functions = { } ``` The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. `print` versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened. + since 4.08 ``` val pp_set_formatter_stag_functions : @@ -659,8 +856,11 @@ val pp_set_formatter_stag_functions : val set_formatter_stag_functions : formatter_stag_functions -> unit ``` `pp_set_formatter_stag_functions ppf tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`. + When opening a semantic tag with name `t`, the string `t` is passed to the opening tag-marking function (the `mark_open_stag` field of the record `tag_funs`), that must return the opening tag marker for that name. When the next call to `close_stag ()` happens, the semantic tag name `t` is sent back to the closing tag-marking function (the `mark_close_stag` field of record `tag_funs`), that must return a closing tag marker for that name. + The `print_` field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue. + since 4.08 ``` val pp_get_formatter_stag_functions : @@ -672,70 +872,92 @@ val pp_get_formatter_stag_functions : val get_formatter_stag_functions : unit -> formatter_stag_functions ``` Return the current semantic tag operation functions of the standard pretty-printer. + since 4.08 + ## Defining formatters + Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently. + For instance, given a [`Buffer.t`](./Stdlib-Buffer.md#type-t) buffer `b`, [`formatter_of_buffer`](./#val-formatter_of_buffer) `b` returns a new formatter using buffer `b` as its output device. Similarly, given a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) output channel `oc`, [`formatter_of_out_channel`](./#val-formatter_of_out_channel) `oc` returns a new formatter using channel `oc` as its output device. + Alternatively, given `out_funs`, a complete set of output functions for a formatter, then [`formatter_of_out_functions`](./#val-formatter_of_out_functions) `out_funs` computes a new formatter using those functions for output. + ``` val formatter_of_out_channel : out_channel -> formatter ``` `formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`. + ``` val synchronized_formatter_of_out_channel : out_channel -> formatter Domain.DLS.key ``` `synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`. + When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + alert unstable ``` val std_formatter : formatter ``` The initial domain's standard formatter to write to standard output. + It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stdout`](./Stdlib.md#val-stdout). + ``` val get_std_formatter : unit -> formatter ``` `get_std_formatter ()` returns the current domain's standard formatter used to write to standard output. + since 5.0 ``` val err_formatter : formatter ``` The initial domain's formatter to write to standard error. + It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stderr`](./Stdlib.md#val-stderr). + ``` val get_err_formatter : unit -> formatter ``` `get_err_formatter ()` returns the current domain's formatter used to write to standard error. + since 5.0 ``` val formatter_of_buffer : Buffer.t -> formatter ``` `formatter_of_buffer b` returns a new formatter writing to buffer `b`. At the end of pretty-printing, the formatter must be flushed using [`pp_print_flush`](./#val-pp_print_flush) or [`pp_print_newline`](./#val-pp_print_newline), to print all the pending material into the buffer. + ``` val stdbuf : Buffer.t ``` The initial domain's string buffer in which `str_formatter` writes. + ``` val get_stdbuf : unit -> Buffer.t ``` `get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes. + since 5.0 ``` val str_formatter : formatter ``` The initial domain's formatter to output to the [`stdbuf`](./#val-stdbuf) string buffer. + `str_formatter` is defined as [`formatter_of_buffer`](./#val-formatter_of_buffer) [`stdbuf`](./#val-stdbuf). + ``` val get_str_formatter : unit -> formatter ``` The current domain's formatter to output to the current domains string buffer. + since 5.0 ``` val flush_str_formatter : unit -> string ``` Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer. + ``` val make_formatter : (string -> int -> int -> unit) -> @@ -743,13 +965,16 @@ val make_formatter : formatter ``` `make_formatter out flush` returns a new formatter that outputs with function `out`, and flushes with function `flush`. + For instance, + ```ocaml make_formatter (Stdlib.output_substring oc) (fun () -> Stdlib.flush oc) ``` returns a formatter to the [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) `oc`. + ``` val make_synchronized_formatter : (string -> int -> int -> unit) -> @@ -757,22 +982,32 @@ val make_synchronized_formatter : formatter Domain.DLS.key ``` `make_synchronized_formatter out flush` returns the key to the domain-local state that holds the domain-local formatter that outputs with function `out`, and flushes with function `flush`. + When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + since 5.0 alert unstable ``` val formatter_of_out_functions : formatter_out_functions -> formatter ``` `formatter_of_out_functions out_funs` returns a new formatter that writes with the set of output functions `out_funs`. + See definition of type [`formatter_out_functions`](./#type-formatter_out_functions) for the meaning of argument `out_funs`. + since 4.06 + ### Symbolic pretty-printing + Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items. + When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations. + In practice, first define a symbolic output buffer `b` using: + - `let sob = make_symbolic_output_buffer ()`. Then define a symbolic formatter with: - `let ppf = formatter_of_symbolic_output_buffer sob` Use symbolic formatter `ppf` as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer `sob` with: + - `flush_symbolic_output_buffer sob`. ``` type symbolic_output_item = @@ -781,41 +1016,50 @@ type symbolic_output_item = | Output_flush ``` symbolic flush command + ``` | Output_newline ``` symbolic newline command + ``` | Output_string of string ``` `Output_string s`: symbolic output for string `s` + ``` | Output_spaces of int ``` `Output_spaces n`: symbolic command to output `n` spaces + ``` | Output_indent of int ``` `Output_indent i`: symbolic indentation of size `i` + ``` ``` Items produced by symbolic pretty-printers + since 4.06 ``` type symbolic_output_buffer ``` The output buffer of a symbolic pretty-printer. + since 4.06 ``` val make_symbolic_output_buffer : unit -> symbolic_output_buffer ``` `make_symbolic_output_buffer ()` returns a fresh buffer for symbolic output. + since 4.06 ``` val clear_symbolic_output_buffer : symbolic_output_buffer -> unit ``` `clear_symbolic_output_buffer sob` resets buffer `sob`. + since 4.06 ``` val get_symbolic_output_buffer : @@ -823,6 +1067,7 @@ val get_symbolic_output_buffer : symbolic_output_item list ``` `get_symbolic_output_buffer sob` returns the contents of buffer `sob`. + since 4.06 ``` val flush_symbolic_output_buffer : @@ -830,6 +1075,7 @@ val flush_symbolic_output_buffer : symbolic_output_item list ``` `flush_symbolic_output_buffer sob` returns the contents of buffer `sob` and resets buffer `sob`. `flush_symbolic_output_buffer sob` is equivalent to `let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items` + since 4.06 ``` val add_symbolic_output_item : @@ -838,13 +1084,17 @@ val add_symbolic_output_item : unit ``` `add_symbolic_output_item sob itm` adds item `itm` to buffer `sob`. + since 4.06 ``` val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter ``` `formatter_of_symbolic_output_buffer sob` returns a symbolic formatter that outputs to `symbolic_output_buffer` `sob`. + since 4.06 + ## Convenience formatting functions. + ``` val pp_print_iter : ?pp_sep:(formatter -> unit -> unit) -> @@ -855,6 +1105,7 @@ val pp_print_iter : unit ``` `pp_print_iter ~pp_sep iter pp_v ppf v` formats on `ppf` the iterations of `iter` over a collection `v` of values using `pp_v`. Iterations are separated by `pp_sep` (defaults to [`pp_print_cut`](./#val-pp_print_cut)). + since 5.1 ``` val pp_print_list : @@ -865,6 +1116,7 @@ val pp_print_list : unit ``` `pp_print_list ?pp_sep pp_v ppf l` prints items of list `l`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty lists. + since 4.02 ``` val pp_print_array : @@ -875,7 +1127,9 @@ val pp_print_array : unit ``` `pp_print_array ?pp_sep pp_v ppf a` prints items of array `a`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty arrays. + If `a` is mutated after `pp_print_array` is called, the printed values may not be what is expected because `Format` can delay the printing. This can be avoided by flushing `ppf`. + since 5.1 ``` val pp_print_seq : @@ -886,12 +1140,15 @@ val pp_print_seq : unit ``` `pp_print_seq ?pp_sep pp_v ppf s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut). Does nothing on empty sequences. + This function does not terminate on infinite sequences. + since 4.12 ``` val pp_print_text : formatter -> string -> unit ``` `pp_print_text ppf s` prints `s` with spaces and newlines respectively printed using [`pp_print_space`](./#val-pp_print_space) and [`pp_force_newline`](./#val-pp_force_newline). + since 4.02 ``` val pp_print_option : @@ -902,6 +1159,7 @@ val pp_print_option : unit ``` `pp_print_option ?none pp_v ppf o` prints `o` on `ppf` using `pp_v` if `o` is `Some v` and `none` if it is `None`. `none` prints nothing by default. + since 4.08 ``` val pp_print_result : @@ -912,6 +1170,7 @@ val pp_print_result : unit ``` `pp_print_result ~ok ~error ppf r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`. + since 4.08 ``` val pp_print_either : @@ -922,17 +1181,26 @@ val pp_print_either : unit ``` `pp_print_either ~left ~right ppf e` prints `e` on `ppf` using `left` if `e` is `Either.Left _` and `right` if `e` is `Either.Right _`. + since 4.13 + ## Formatted pretty-printing + Module `Format` provides a complete set of `printf` like functions for pretty-printing using format string specifications. + Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine. + Those annotations are introduced in the format strings using the `@` character. For instance, `@ ` means a space break, `@,` means a cut, `@[` opens a new box, and `@]` closes the last open box. + ``` val fprintf : formatter -> ('a, formatter, unit) format -> 'a ``` `fprintf ff fmt arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `fmt`, and outputs the resulting string on the formatter `ff`. + The format string `fmt` is a character string which contains three types of objects: plain characters and conversion specifications as specified in the [`Printf`](./Stdlib-Printf.md) module, and pretty-printing indications specific to the `Format` module. + The pretty-printing indication characters are introduced by a `@` character, and their meanings are: + - `@[`: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the `<` character, followed by an optional box type indication, then an optional integer offset, and the closing `>` character. Pretty-printing box type is one of `h`, `v`, `hv`, `b`, or `hov`. '`h`' stands for an 'horizontal' pretty-printing box, '`v`' stands for a 'vertical' pretty-printing box, '`hv`' stands for an 'horizontal/vertical' pretty-printing box, '`b`' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '`hov`' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, `@[` opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with `open_hovbox 2`. For more details about pretty-printing boxes, see the various box opening functions `open_*box`. - `@]`: close the most recently opened pretty-printing box. - `@,`: output a 'cut' break hint, as with `print_cut ()`. @@ -945,33 +1213,45 @@ The pretty-printing indication characters are introduced by a `@` character, and - `@?`: flush the pretty-printer as with `print_flush ()`. This is equivalent to the conversion `%!`. - `@\n`: force a newline, as with `force_newline ()`, not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box. Note: To prevent the interpretation of a `@` character as a pretty-printing indication, escape it with a `%` character. Old quotation mode `@@` is deprecated since it is not compatible with formatted input interpretation of character `'@'`. + Example: `printf "@[%s@ %d@]@." "x =" 1` is equivalent to `open_box (); print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()`. It prints `x = 1` within a pretty-printing 'horizontal-or-vertical' box. + ``` val printf : ('a, formatter, unit) format -> 'a ``` Same as `fprintf` above, but output on `get_std_formatter ()`. + It is defined similarly to `fun fmt -> fprintf (get_std_formatter ()) fmt` but delays calling `get_std_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + ``` val eprintf : ('a, formatter, unit) format -> 'a ``` Same as `fprintf` above, but output on `get_err_formatter ()`. + It is defined similarly to `fun fmt -> fprintf (get_err_formatter ()) fmt` but delays calling `get_err_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + ``` val sprintf : ('a, unit, string) format -> 'a ``` Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of *each call* to `sprintf`. Note that if your format string contains a `%a`, you should use `asprintf`. + In case of multiple and related calls to `sprintf` to output material on a single string, you should consider using `fprintf` with the predefined formatter `str_formatter` and call `flush_str_formatter ()` to get the final result. + Alternatively, you can use `Format.fprintf` with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string. + ``` val asprintf : ('a, formatter, unit, string) format4 -> 'a ``` Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. The type of `asprintf` is general enough to interact nicely with `%a` conversions. + since 4.01 ``` val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a ``` Same as [`fprintf`](./#val-fprintf), except the formatter is the last argument. `dprintf "..." a b c` is a function of type `formatter -> unit` which can be given to a format specifier `%t`. + This can be used as a replacement for [`asprintf`](./#val-asprintf) to delay formatting decisions. Using the string returned by [`asprintf`](./#val-asprintf) in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. [`dprintf`](./#val-dprintf) allows delay of formatting decisions until the final formatting context is known. For example: + ```ocaml let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in ... @@ -982,8 +1262,10 @@ since 4.08 val ifprintf : formatter -> ('a, formatter, unit) format -> 'a ``` Same as `fprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + since 3.10 Formatted Pretty-Printing with continuations. + ``` val kfprintf : (formatter -> 'a) -> @@ -992,6 +1274,7 @@ val kfprintf : 'b ``` Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing. + ``` val kdprintf : ((formatter -> unit) -> 'a) -> @@ -999,6 +1282,7 @@ val kdprintf : 'b ``` Same as [`dprintf`](./#val-dprintf) above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing. + since 4.08 ``` val ikfprintf : @@ -1008,19 +1292,26 @@ val ikfprintf : 'b ``` Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + since 3.12 ``` val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b ``` Same as `sprintf` above, but instead of returning the string, passes it to the first argument. + ``` val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b ``` Same as `asprintf` above, but instead of returning the string, passes it to the first argument. + since 4.03 + ## Examples + A few warmup examples to get an idea of how Format is used. + We have a list `l` of pairs `(int * bool)`, which the toplevel prints for us: + ```ocaml # let l = List.init 20 (fun n -> n, n mod 2 = 0) val l : (int * bool) list = @@ -1030,6 +1321,7 @@ val l : (int * bool) list = (18, true); (19, false)] ``` If we want to print it ourself without the toplevel magic, we can try this: + ```ocaml # let pp_pair out (x,y) = Format.fprintf out "(%d, %b)" x y val pp_pair : Format.formatter -> int * bool -> unit = @@ -1042,6 +1334,7 @@ val pp_pair : Format.formatter -> int * bool -> unit = ``` What this does, briefly, is: + - `pp_pair` prints a pair `bool*int` surrounded in "(" ")". It takes a formatter (into which formatting happens), and the pair itself. When printing is done it returns `()`. - `Format.printf "l = [@[%a@]]@." ... l` is like `printf`, but with additional formatting instructions (denoted with "@"). The pair "`@[`" and "`@]`" is a "horizontal-or-vertical box". - "@." ends formatting with a newline. It is similar to "\\n" but is also aware of the `Format.formatter`'s state. Do not use "\\n" with `Format`. @@ -1049,6 +1342,7 @@ What this does, briefly, is: - We build a list printer using `Format.pp_print_list ~pp_sep:(...) pp_pair`. `pp_print_list` takes an element printer and returns a list printer. The `?pp_sep` optional argument, if provided, is called in between each element to print a separator. - Here, for a separator, we use `(fun out () -> Format.fprintf out ";@ ")`. It prints ";", and then "@ " which is a breaking space (either it prints " ", or it prints a newline if the box is about to overflow). This "@ " is responsible for the list printing splitting into several lines. If we omit "@ ", we get an ugly single-line print: + ```ocaml # Format.printf "l: [@[%a@]]@." Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out "; ") pp_pair) l @@ -1056,6 +1350,7 @@ If we omit "@ ", we get an ugly single-line print: - : unit = () ``` Generally, it is good practice to define custom printers for important types in your program. If, for example, you were to define basic geometry types like so: + ```ocaml type point = { x: float; @@ -1068,6 +1363,7 @@ type rectangle = { } ``` For debugging purpose, or to display information in logs, or on the console, it would be convenient to define printers for these types. Here is an example of to do it. Note that "%.3f" is a `float` printer up to 3 digits of precision after the dot; "%f" would print as many digits as required, which is somewhat verbose; "%h" is an hexadecimal float printer. + ```ocaml let pp_point out (p:point) = Format.fprintf out "{ @[x=%.3f;@ y=%.3f@] }" p.x p.y @@ -1077,12 +1373,14 @@ let pp_rectangle out (r:rectangle) = pp_point r.ll pp_point r.ur ``` In the `.mli` file, we could have: + ```ocaml val pp_point : Format.formatter -> point -> unit val pp_rectangle : Format.formatter -> rectangle -> unit ``` These printers can now be used with "%a" inside other printers. + ```ocaml # Format.printf "some rectangle: %a@." (Format.pp_print_option pp_rectangle) @@ -1095,6 +1393,9 @@ some rectangle: { l={ x=1.000; y=2.000 }; ur={ x=42.000; y=500.123 } } no rectangle: ``` See how we combine `pp_print_option` (option printer) and our newly defined rectangle printer, like we did with `pp_print_list` earlier. + For a more extensive tutorial, see ["Using the Format module"](https://caml.inria.fr/resources/doc/guides/format.en.html). + A final note: the `Format` module is a starting point. The OCaml ecosystem has libraries that makes formatting easier and more expressive, with more combinators, more concise names, etc. An example of such a library is [Fmt](https://erratique.ch/software/fmt). -Automatic deriving of pretty-printers from type definitions is also possible, using [https://github.com/ocaml-ppx/ppx\_deriving](ppx_deriving.show) or similar ppx derivers. \ No newline at end of file + +Automatic deriving of pretty-printers from type definitions is also possible, using [https://github.com/ocaml-ppx/ppx\_deriving](ppx_deriving.show) or similar ppx derivers. diff --git a/docs/api/melange/Stdlib-Fun.md b/docs/api/melange/Stdlib-Fun.md index e8ecb4be4..ce11eb91e 100644 --- a/docs/api/melange/Stdlib-Fun.md +++ b/docs/api/melange/Stdlib-Fun.md @@ -1,36 +1,51 @@ + # Module `Stdlib.Fun` + Function manipulation. + since 4.08 + ## Combinators + ``` val id : 'a -> 'a ``` `id` is the identity function. For any argument `x`, `id x` is `x`. + ``` val const : 'a -> _ -> 'a ``` `const c` is a function that always returns the value `c`. For any argument `x`, `(const c) x` is `c`. + ``` val compose : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c ``` `compose f g` is a function composition of applying `g` then `f`. For any arguments `f`, `g`, and `x`, `compose f g x` is `f (g x)`. + since 5.2 ``` val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c ``` `flip f` reverses the argument order of the binary function `f`. For any arguments `x` and `y`, `(flip f) x y` is `f y x`. + ``` val negate : ('a -> bool) -> 'a -> bool ``` `negate p` is the negation of the predicate function `p`. For any argument `x`, `(negate p) x` is `not (p x)`. + + ## Exception handling + ``` val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a ``` `protect ~finally work` invokes `work ()` and then `finally ()` before `work ()` returns with its value or an exception. In the latter case the exception is re-raised after `finally ()`. If `finally ()` raises an exception, then the exception [`Finally_raised`](./#exception-Finally_raised) is raised instead. + `protect` can be used to enforce local invariants whether `work ()` returns normally or raises an exception. However, it does not protect against unexpected exceptions raised inside `finally ()` such as [`Stdlib.Out_of_memory`](./Stdlib.md#exception-Out_of_memory), [`Stdlib.Stack_overflow`](./Stdlib.md#exception-Stack_overflow), or asynchronous exceptions raised by signal handlers (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)). + Note: It is a *programming error* if other kinds of exceptions are raised by `finally`, as any exception raised in `work ()` will be lost in the event of a [`Finally_raised`](./#exception-Finally_raised) exception. Therefore, one should make sure to handle those inside the finally. + ``` exception Finally_raised of exn ``` -`Finally_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally_raised` exception except as part of a catch-all handler. \ No newline at end of file +`Finally_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally_raised` exception except as part of a catch-all handler. diff --git a/docs/api/melange/Stdlib-Gc-Memprof.md b/docs/api/melange/Stdlib-Gc-Memprof.md index 2514bb54d..4258d4511 100644 --- a/docs/api/melange/Stdlib-Gc-Memprof.md +++ b/docs/api/melange/Stdlib-Gc-Memprof.md @@ -1,12 +1,19 @@ + # Module `Gc.Memprof` + `Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. + Since blocks are composed of several words, a block can potentially be sampled several times. If a block is sampled several times, then each of the callbacks is called once for each event of this block: the multiplicity is given in the `n_samples` field of the `allocation` structure. + This engine makes it possible to implement a low-overhead memory profiler as an OCaml library. + Note: this API is EXPERIMENTAL. It may change without prior notice. + ``` type t ``` the type of a profile + ``` type allocation_source = ``` @@ -27,16 +34,21 @@ type allocation = private { ``` `n_samples : int;` The number of samples in this block (\>= 1\). + `size : int;` The size of the block, in words, excluding the header. + `source : allocation_source;` The cause of the allocation. + `callstack : Printexc.raw_backtrace;` The callstack for the allocation. + ``` } ``` The type of metadata associated with allocations. This is the type of records passed to the callback triggered by the sampling of an allocation. + ``` type ('minor, 'major) tracker = { ``` @@ -49,12 +61,16 @@ type ('minor, 'major) tracker = { } ``` A `('minor, 'major) tracker` describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: `'minor` is the type of metadata to keep for minor blocks, and `'major` the type of metadata for major blocks. + The member functions in a `tracker` are called callbacks. + If an allocation or promotion callback raises an exception or returns `None`, memprof stops tracking the corresponding block. + ``` val null_tracker : ('minor, 'major) tracker ``` Default callbacks simply return `None` or `()` + ``` val start : sampling_rate:float -> @@ -63,22 +79,35 @@ val start : t ``` Start a profile with the given parameters. Raises an exception if a profile is already sampling in the current domain. + Sampling begins immediately. The parameter `sampling_rate` is the sampling rate in samples per word (including headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on performance, and 1e-3 causes the program to run a few percent slower. 0.0 \<= sampling\_rate \<= 1\.0. + The parameter `callstack_size` is the length of the callstack recorded at every sample. Its default is `max_int`. + The parameter `tracker` determines how to track sampled blocks over their lifetime in the minor and major heap. + Sampling and running callbacks are temporarily disabled on the current thread when calling a callback, so callbacks do not need to be re-entrant if the program is single-threaded and single-domain. However, if threads or multiple domains are used, it is possible that several callbacks will run in parallel. In this case, callback functions must be re-entrant. + Note that a callback may be postponed slightly after the actual event. The callstack passed to an allocation callback always accurately reflects the allocation, but the program state may have evolved between the allocation and the call to the callback. + If a new thread or domain is created when the current domain is sampling for a profile, the child thread or domain joins that profile (using the same `sampling_rate`, `callstack_size`, and `tracker` callbacks). + An allocation callback is always run by the thread which allocated the block. If the thread exits or the profile is stopped before the callback is called, the allocation callback is not called and the block is not tracked. + Each subsequent callback is generally run by the domain which allocated the block. If the domain terminates or the profile is stopped before the callback is called, the callback may be run by a different domain. + Different domains may sample for different profiles simultaneously. + ``` val stop : unit -> unit ``` Stop sampling for the current profile. Fails if no profile is sampling in the current domain. Stops sampling in all threads and domains sharing the profile. + Promotion and deallocation callbacks from a profile may run after `stop` is called, until `discard` is applied to the profile. + A profile is implicitly stopped (but not discarded) if all domains and threads sampling for it are terminated. + ``` val discard : t -> unit ``` -Discards all profiling state for a stopped profile, which prevents any more callbacks for it. Raises an exception if called on a profile which has not been stopped. \ No newline at end of file +Discards all profiling state for a stopped profile, which prevents any more callbacks for it. Raises an exception if called on a profile which has not been stopped. diff --git a/docs/api/melange/Stdlib-Gc.md b/docs/api/melange/Stdlib-Gc.md index 098c3e3df..37e04a556 100644 --- a/docs/api/melange/Stdlib-Gc.md +++ b/docs/api/melange/Stdlib-Gc.md @@ -1,63 +1,92 @@ + # Module `Stdlib.Gc` + Memory management control and statistics; finalised values. + ``` type stat = { ``` `minor_words : float;` Number of words allocated in the minor heap since the program was started. + `promoted_words : float;` Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap since the program was started. + `major_words : float;` Number of words allocated in the major heap, including the promoted words, since the program was started. + `minor_collections : int;` Number of minor collections since the program was started. + `major_collections : int;` Number of major collection cycles completed since the program was started. + `heap_words : int;` Total size of the major heap, in words. + `heap_chunks : int;` Number of contiguous pieces of memory that make up the major heap. This metric is currently not available in OCaml 5: the field value is always `0`. + `live_words : int;` Number of words of live data in the major heap, including the header words. + Note that "live" words refers to every word in the major heap that isn't currently known to be collectable, which includes words that have become unreachable by the program after the start of the previous gc cycle. It is typically much simpler and more predictable to call [`Gc.full_major`](./#val-full_major) (or [`Gc.compact`](./#val-compact)) then computing gc stats, as then "live" words has the simple meaning of "reachable by the program". One caveat is that a single call to [`Gc.full_major`](./#val-full_major) will not reclaim values that have a finaliser from [`Gc.finalise`](./#val-finalise) (this does not apply to [`Gc.finalise_last`](./#val-finalise_last)). If this caveat matters, simply call [`Gc.full_major`](./#val-full_major) twice instead of once. + `live_blocks : int;` Number of live blocks in the major heap. + See `live_words` for a caveat about what "live" means. + `free_words : int;` Number of words in the free list. + `free_blocks : int;` Number of blocks in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. + `largest_free : int;` Size (in words) of the largest block in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. + `fragments : int;` Number of wasted words due to fragmentation. These are 1-words free blocks placed between two live blocks. They are not available for allocation. + `compactions : int;` Number of heap compactions since the program was started. + `top_heap_words : int;` Maximum size reached by the major heap, in words. + `stack_size : int;` Current size of the stack, in words. This metric is currently not available in OCaml 5: the field value is always `0`. + since 3.12 `forced_major_collections : int;` Number of forced full major collections completed since the program was started. + since 4.12 ``` } ``` The memory management counters are returned in a `stat` record. These counters give values for the whole program. + The total amount of memory allocated by the program since it was started is (in words) `minor_words + major_words - promoted_words`. Multiply by the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes. + ``` type control = { ``` `minor_heap_size : int;` The size (in words) of the minor heap. Changing this parameter will trigger a minor collection. The total size of the minor heap used by this program is the sum of the heap sizes of the active domains. Default: 256k. + `major_heap_increment : int;` How much to add to the major heap when increasing it. If this number is less than or equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will double the heap size at each increase). If it is more than 1000, it is a fixed number of words that will be added to the heap. + This field is currently not available in OCaml 5: the field value is always `0`. + `space_overhead : int;` The major GC speed is computed from this parameter. This is the memory that will be "wasted" because the GC does not immediately collect unreachable blocks. It is expressed as a percentage of the memory used for live data. The GC will work more (use more CPU time and collect blocks more eagerly) if `space_overhead` is smaller. Default: 120. + `verbose : int;` This value controls the GC messages on standard error output. It is a sum of some of the following flags, to print messages on the corresponding events: + - `0x001` Start and end of major GC cycle. - `0x002` Minor collection and major GC slice. - `0x004` Growing and shrinking of the heap. @@ -71,129 +100,172 @@ This value controls the GC messages on standard error output. It is a sum of som - `0x400` Output GC statistics at program exit. Default: 0. `max_overhead : int;` Heap compaction is triggered when the estimated amount of "wasted" memory is more than `max_overhead` percent of the amount of live data. If `max_overhead` is set to 0, heap compaction is triggered at the end of each major GC cycle (this setting is intended for testing purposes only). If `max_overhead >= 1000000`, compaction is never triggered. + This field is currently not available in OCaml 5: the field value is always `0`. + `stack_limit : int;` The maximum size of the fiber stacks (in words). Default: 128M. + `allocation_policy : int;` The policy used for allocating in the major heap. + This field is currently not available in OCaml 5: the field value is always `0`. + Prior to OCaml 5.0, possible values were 0, 1 and 2. + - 0 was the next-fit policy - 1 was the first-fit policy (since OCaml 3.11) - 2 was the best-fit policy (since OCaml 4.10) since 3.11 `window_size : int;` The size of the window used by the major GC for smoothing out variations in its workload. This is an integer between 1 and 50. + since 4.03 This field is currently not available in OCaml 5: the field value is always `0`. + `custom_major_ratio : int;` Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. The default value keeps the out-of-heap floating garbage about the same size as the in-heap overhead. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 44. + since 4.08 `custom_minor_ratio : int;` Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 100. + since 4.08 `custom_minor_max_size : int;` Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. Custom values that hold more than this many bytes are allocated on the major heap. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 70000 bytes. + since 4.08 ``` } ``` The GC parameters are given as a `control` record. Note that these parameters can also be initialised by setting the OCAMLRUNPARAM environment variable. See the documentation of `ocamlrun`. + ``` val stat : unit -> stat ``` Return the current values of the memory management counters in a `stat` record that represents the program's total memory stats. The `heap_chunks`, `free_blocks`, `largest_free`, and `stack_size` metrics are currently not available in OCaml 5: their returned field values are therefore `0`. This function causes a full major collection. + ``` val quick_stat : unit -> stat ``` Returns a record with the current values of the memory management counters like `stat`. Unlike `stat`, `quick_stat` does not perform a full major collection, and hence, is much faster. However, `quick_stat` reports the counters sampled at the last minor collection or at the end of the last major collection cycle (whichever is the latest). Hence, the memory stats returned by `quick_stat` are not instantaneously accurate. + ``` val counters : unit -> float * float * float ``` Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. This function is as fast as `quick_stat`. + ``` val minor_words : unit -> float ``` Number of words allocated in the minor heap by this domain or potentially previous domains. This number is accurate in byte-code programs, but only an approximation in programs compiled to native code. + In native code this function does not allocate. + since 4.04 ``` val get : unit -> control ``` Return the current values of the GC parameters in a `control` record. + The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: their returned field values are therefore `0`. + alert unsynchronized\_access GC parameters are a mutable global state. ``` val set : control -> unit ``` `set r` changes the GC parameters according to the `control` record `r`. The normal usage is: `Gc.set { (Gc.get()) with Gc.verbose = 0x00d }` + The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: setting them therefore has no effect. + alert unsynchronized\_access GC parameters are a mutable global state. ``` val minor : unit -> unit ``` Trigger a minor collection. + ``` val major_slice : int -> int ``` `major_slice n` Do a minor collection and a slice of major collection. `n` is the size of the slice: the GC will do enough work to free (on average) `n` words of memory. If `n` \= 0, the GC will try to do enough work to ensure that the next automatic slice has no work to do. This function returns an unspecified integer (currently: 0). + ``` val major : unit -> unit ``` Do a minor collection and finish the current major collection cycle. + ``` val full_major : unit -> unit ``` Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. This will collect all currently unreachable blocks. + ``` val compact : unit -> unit ``` Perform a full major collection and compact the heap. Note that heap compaction is a lengthy operation. + ``` val print_stat : out_channel -> unit ``` Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument. + ``` val allocated_bytes : unit -> float ``` Return the number of bytes allocated by this domain and potentially a previous domain. It is returned as a `float` to avoid overflow problems with `int` on 32-bit machines. + ``` val get_minor_free : unit -> int ``` Return the current size of the free space inside the minor heap of this domain. + since 4.03 ``` val finalise : ('a -> unit) -> 'a -> unit ``` `finalise f v` registers `f` as a finalisation function for `v`. `v` must be heap-allocated. `f` will be called with `v` as argument at some point between the first time `v` becomes unreachable (including through weak pointers) and the time `v` is collected by the GC. Several functions can be registered for the same value, or even several instances of the same function. Each instance will be called once (or never, if the program terminates before `v` becomes unreachable). + The GC will call the finalisation functions in the order of deallocation. When several values become unreachable at the same time (i.e. during the same GC cycle), the finalisation functions will be called in the reverse order of the corresponding calls to `finalise`. If `finalise` is called in the same order as the values are allocated, that means each value is finalised before the values it depends upon. Of course, this becomes false if additional dependencies are introduced by assignments. + In the presence of multiple OCaml threads it should be assumed that any particular finaliser may be executed in any of the threads. + Anything reachable from the closure of finalisation functions is considered reachable, so the following code will not work as expected: + - ` let v = ... in Gc.finalise (fun _ -> ...v...) v ` Instead you should make sure that `v` is not in the closure of the finalisation function by writing: + - ` let f = fun x -> ... let v = ... in Gc.finalise f v ` The `f` function can use all features of OCaml, including assignments that make the value reachable again. It can also loop forever (in this case, the other finalisation functions will not be called during the execution of f, unless it calls `finalise_release`). It can call `finalise` on `v` or other values to register other functions or even itself. It can raise an exception; in this case the exception will interrupt whatever the program was doing when the function was called. + `finalise` will raise `Invalid_argument` if `v` is not guaranteed to be heap-allocated. Some examples of values that are not heap-allocated are integers, constant constructors, booleans, the empty array, the empty list, the unit value. The exact list of what is heap-allocated or not is implementation-dependent. Some constant values can be heap-allocated but never deallocated during the lifetime of the program, for example a list of integer constants; this is also implementation-dependent. Note that values of types `float` are sometimes allocated and sometimes not, so finalising them is unsafe, and `finalise` will also raise `Invalid_argument` for them. Values of type `'a Lazy.t` (for any `'a`) are like `float` in this respect, except that the compiler sometimes optimizes them in a way that prevents `finalise` from detecting them. In this case, it will not raise `Invalid_argument`, but you should still avoid calling `finalise` on lazy values. + The results of calling [`String.make`](./Stdlib-String.md#val-make), [`Bytes.make`](./Stdlib-Bytes.md#val-make), [`Bytes.create`](./Stdlib-Bytes.md#val-create), [`Array.make`](./Stdlib-Array.md#val-make), and [`Stdlib.ref`](./Stdlib.md#val-ref) are guaranteed to be heap-allocated and non-constant except when the length argument is `0`. + ``` val finalise_last : (unit -> unit) -> 'a -> unit ``` same as [`finalise`](./#val-finalise) except the value is not given as argument. So you can't use the given value for the computation of the finalisation function. The benefit is that the function is called after the value is unreachable for the last time instead of the first time. So contrary to [`finalise`](./#val-finalise) the value will never be reachable again or used again. In particular every weak pointer and ephemeron that contained this value as key or data is unset before running the finalisation function. Moreover the finalisation functions attached with [`finalise`](./#val-finalise) are always called before the finalisation functions attached with [`finalise_last`](./#val-finalise_last). + since 4.04 ``` val finalise_release : unit -> unit ``` A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return. + ``` type alarm ``` An alarm is a piece of data that calls a user function at the end of major GC cycle. The following functions are provided to create and delete alarms. + ``` val create_alarm : (unit -> unit) -> alarm ``` `create_alarm f` will arrange for `f` to be called at the end of major GC cycles, not caused by `f` itself, starting with the current cycle or the next one. `f` will run on the same domain that created the alarm, until the domain exits or `delete_alarm` is called. A value of type `alarm` is returned that you can use to call `delete_alarm`. + It is not guaranteed that the Gc alarm runs at the end of every major GC cycle, but it is guaranteed that it will run eventually. + As an example, here is a crude way to interrupt a function if the memory consumption of the program exceeds a given `limit` in MB, suitable for use in the toplevel: + ```ocaml let run_with_memory_limit (limit : int) (f : unit -> 'a) : 'a = let limit_memory () = @@ -208,6 +280,7 @@ let run_with_memory_limit (limit : int) (f : unit -> 'a) : 'a = val delete_alarm : alarm -> unit ``` `delete_alarm a` will stop the calls to the function associated to `a`. Calling `delete_alarm a` again has no effect. + ``` val eventlog_pause : unit -> unit ``` @@ -219,4 +292,4 @@ deprecated Use Runtime\_events.resume instead. ``` module Memprof : sig ... end ``` -`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. \ No newline at end of file +`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. diff --git a/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md b/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md index 492b57f0f..80efdc53c 100644 --- a/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md +++ b/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md @@ -1,16 +1,21 @@ + # Parameter `Make.H` + ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val hash : t -> int ``` A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + - (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) - (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly - (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-Make.md b/docs/api/melange/Stdlib-Hashtbl-Make.md index 887725936..ec79c26fe 100644 --- a/docs/api/melange/Stdlib-Hashtbl-Make.md +++ b/docs/api/melange/Stdlib-Hashtbl-Make.md @@ -1,10 +1,17 @@ + # Module `Hashtbl.Make` + Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + + ## Parameters + ``` module H : HashedType ``` + ## Signature + ``` type key = H.t ``` diff --git a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md index 7f8d54ae8..66eb409ed 100644 --- a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md +++ b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md @@ -1,13 +1,17 @@ + # Parameter `MakeSeeded.H` + ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val seeded_hash : int -> t -> int ``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md index af7731734..23f14bd52 100644 --- a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md +++ b/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md @@ -1,11 +1,18 @@ + # Module `Hashtbl.MakeSeeded` + Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-Hashtbl.md#val-randomize)). + since 4.00 + ## Parameters + ``` module H : SeededHashedType ``` + ## Signature + ``` type key = H.t ``` diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md b/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md index aae1e09a4..6c2dc6de5 100644 --- a/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md @@ -1,17 +1,23 @@ + # Module type `Hashtbl.HashedType` + The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val hash : t -> int ``` A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + - (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) - (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly - (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-S.md b/docs/api/melange/Stdlib-Hashtbl-module-type-S.md index 2720a929a..c4d7f8b23 100644 --- a/docs/api/melange/Stdlib-Hashtbl-module-type-S.md +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-S.md @@ -1,5 +1,8 @@ + # Module type `Hashtbl.S` + The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + ``` type key ``` diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md index e96072c4a..63efb5650 100644 --- a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md @@ -1,15 +1,20 @@ + # Module type `Hashtbl.SeededHashedType` + The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 4.00 ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val seeded_hash : int -> t -> int ``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md index b811c5912..da23d5c25 100644 --- a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md +++ b/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md @@ -1,5 +1,8 @@ + # Module type `Hashtbl.SeededS` + The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 4.00 ``` type key diff --git a/docs/api/melange/Stdlib-Hashtbl.md b/docs/api/melange/Stdlib-Hashtbl.md index fa2b5865c..cd0022e7f 100644 --- a/docs/api/melange/Stdlib-Hashtbl.md +++ b/docs/api/melange/Stdlib-Hashtbl.md @@ -1,123 +1,174 @@ + # Module `Stdlib.Hashtbl` + Hash tables and hash functions. + Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-Map.md). + The functors [`Make`](./Stdlib-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. + **Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. + The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. + See [the examples section](./#examples). + **Unsynchronized accesses** + Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ## Generic interface + ``` type (!'a, !'b) t ``` The type of hash tables from type `'a` to type `'b`. + ``` val create : ?random:bool -> int -> ('a, 'b) t ``` `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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. + A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. + 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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. + before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. ``` val clear : ('a, 'b) t -> unit ``` Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. + ``` val reset : ('a, 'b) t -> unit ``` Empty a hash table and shrink the size of the bucket table to its initial size. + since 4.00 ``` val copy : ('a, 'b) t -> ('a, 'b) t ``` Return a copy of the given hashtable. + ``` val add : ('a, 'b) t -> 'a -> 'b -> unit ``` `Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`. + **Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) + If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). + ``` val find : ('a, 'b) t -> 'a -> 'b ``` `Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. + ``` val find_opt : ('a, 'b) t -> 'a -> 'b option ``` `Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. + since 4.05 ``` val find_all : ('a, 'b) t -> 'a -> 'b list ``` `Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. + ``` val mem : ('a, 'b) t -> 'a -> bool ``` `Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. + ``` val remove : ('a, 'b) t -> 'a -> unit ``` `Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. + ``` val replace : ('a, 'b) t -> 'a -> 'b -> unit ``` `Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. + ``` val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit ``` `Hashtbl.iter f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. + The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + The behavior is not specified if the hash table is modified by `f` during the iteration. + ``` val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit ``` `Hashtbl.filter_map_inplace f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. + Other comments for [`iter`](./#val-iter) apply as well. + since 4.03 ``` val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc ``` `Hashtbl.fold f tbl init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. + The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + The behavior is not specified if the hash table is modified by `f` during the iteration. + ``` val length : ('a, 'b) t -> int ``` `Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. + ``` val randomize : unit -> unit ``` After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. + It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. + Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. + since 4.00 ``` val is_randomized : unit -> bool ``` Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. + since 4.03 ``` val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t ``` Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. + [`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. + since 4.12 ``` type statistics = { ``` `num_bindings : int;` Number of bindings present in the table. Same value as returned by [`length`](./#val-length). + `num_buckets : int;` Number of buckets in the table. + `max_bucket_length : int;` Maximal number of bindings per bucket. + `bucket_histogram : int array;` Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. + ``` } ``` @@ -126,42 +177,56 @@ since 4.00 val stats : ('a, 'b) t -> statistics ``` `Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. + since 4.00 + ## Hash tables and Sequences + ``` val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t ``` Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. + The behavior is not specified if the hash table is modified during the iteration. + since 4.07 ``` val to_seq_keys : ('a, _) t -> 'a Seq.t ``` Same as `Seq.map fst (to_seq m)` + since 4.07 ``` val to_seq_values : (_, 'b) t -> 'b Seq.t ``` Same as `Seq.map snd (to_seq m)` + since 4.07 ``` val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit ``` Add the given bindings to the table, using [`add`](./#val-add) + since 4.07 ``` val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit ``` Add the given bindings to the table, using [`replace`](./#val-replace) + since 4.07 ``` val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t ``` Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. + since 4.07 + ## Functorial interface + The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. + For instance, one might want to specialize a table for integer keys: + ```ocaml module IntHash = struct @@ -176,52 +241,70 @@ For instance, one might want to specialize a table for integer keys: IntHashtbl.add h 12 "hello" ``` This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. + Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. + ``` module type HashedType = sig ... end ``` The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + ``` module type S = sig ... end ``` The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + ``` module Make (H : HashedType) : S with type key = H.t ``` Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + ``` module type SeededHashedType = sig ... end ``` The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + ``` module type SeededS = sig ... end ``` The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + ``` module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t ``` Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). + + ## The polymorphic hash functions + ``` val hash : 'a -> int ``` `Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. + ``` val seeded_hash : int -> 'a -> int ``` A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. + since 4.00 ``` val hash_param : int -> int -> 'a -> int ``` `Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. + ``` val seeded_hash_param : int -> int -> int -> 'a -> int ``` A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. + since 4.00 + ## Examples + + ### Basic Example + ```ocaml (* 0...99 *) let seq = Seq.ints 0 |> Seq.take 100 @@ -251,9 +334,13 @@ since 4.00 # Hashtbl.length tbl - : int = 101 ``` + ### Counting Elements + Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. + Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. + ```ocaml # module Char_tbl = Hashtbl.Make(struct type t = char diff --git a/docs/api/melange/Stdlib-In_channel.md b/docs/api/melange/Stdlib-In_channel.md index 97608184b..7f2f9497e 100644 --- a/docs/api/melange/Stdlib-In_channel.md +++ b/docs/api/melange/Stdlib-In_channel.md @@ -1,13 +1,21 @@ + # Module `Stdlib.In_channel` + Input channels. + This module provides functions for working with input channels. + See [the example section](./#examples) below. + since 4.14 + ## Channels + ``` type t = in_channel ``` The type of input channel. + ``` type open_flag = open_flag = ``` @@ -15,162 +23,216 @@ type open_flag = open_flag = | Open_rdonly ``` open for reading. + ``` | Open_wronly ``` open for writing. + ``` | Open_append ``` open for appending: always write at end of file. + ``` | Open_creat ``` create the file if it does not exist. + ``` | Open_trunc ``` empty the file if it already exists. + ``` | Open_excl ``` fail if Open\_creat and the file already exists. + ``` | Open_binary ``` open in binary mode (no conversion). + ``` | Open_text ``` open in text mode (may perform conversions). + ``` | Open_nonblock ``` open in non-blocking mode. + ``` ``` Opening modes for [`open_gen`](./#val-open_gen). + ``` val stdin : t ``` The standard input for the process. + ``` val open_bin : string -> t ``` Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. + ``` val open_text : string -> t ``` Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). + ``` val open_gen : open_flag list -> int -> string -> t ``` `open_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. + ``` val with_open_bin : string -> (t -> 'a) -> 'a ``` `with_open_bin fn f` opens a channel `ic` on file `fn` and returns `f ic`. After `f` returns, either with a value or by raising an exception, `ic` is guaranteed to be closed. + ``` val with_open_text : string -> (t -> 'a) -> 'a ``` Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). + ``` val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a ``` Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). + ``` val close : t -> unit ``` Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except [`close`](./#val-close), which does nothing when applied to an already closed channel. + ``` val close_noerr : t -> unit ``` Same as [`close`](./#val-close), but ignore all errors. + + ## Input + ``` val input_char : t -> char option ``` Read one character from the given input channel. Returns `None` if there are no more characters to read. + ``` val input_byte : t -> int option ``` Same as [`input_char`](./#val-input_char), but return the 8-bit integer representing the character. Returns `None` if the end of file was reached. + ``` val input_line : t -> string option ``` `input_line ic` reads characters from `ic` until a newline or the end of file is reached. Returns the string of all characters read, without the newline (if any). Returns `None` if the end of the file has been reached. In particular, this will be the case if the last line of input is empty. + A newline is the character `\n` unless the file is open in text mode and [`Sys.win32`](./Stdlib-Sys.md#val-win32) is `true` in which case it is the sequence of characters `\r\n`. + ``` val really_input_string : t -> int -> string option ``` `really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. Returns `None` if the end of file is reached before `len` characters have been read. + If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. + ``` val input_all : t -> string ``` `input_all ic` reads all remaining data from `ic`. + If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. + ``` val input_lines : t -> string list ``` `input_lines ic` reads lines using [`input_line`](./#val-input_line) until the end of file is reached. It returns the list of all lines read, in the order they were read. The newline characters that terminate lines are not included in the returned strings. Empty lines produce empty strings. + since 5.1 + ## Advanced input + ``` val input : t -> bytes -> int -> int -> int ``` `input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. + Use [`really_input`](./#val-really_input) to read exactly `len` characters. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. ``` val really_input : t -> bytes -> int -> int -> unit option ``` `really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. + Returns `None` if the end of file is reached before `len` characters have been read. + If the same channel is read concurrently by multiple threads, the bytes read by `really_input` are not guaranteed to be contiguous. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. ``` val fold_lines : ('acc -> string -> 'acc) -> 'acc -> t -> 'acc ``` `fold_lines f init ic` reads lines from `ic` using [`input_line`](./#val-input_line) until the end of file is reached, and successively passes each line to function `f` in the style of a fold. More precisely, if lines `l1, ..., lN` are read, `fold_lines f init ic` computes `f (... (f (f init l1) l2) ...) lN`. If `f` has no side effects, this is equivalent to `List.fold_left f init (In_channel.input_lines ic)`, but is more efficient since it does not construct the list of all lines read. + since 5.1 + ## Seeking + ``` val seek : t -> int64 -> unit ``` `seek chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. + ``` val pos : t -> int64 ``` Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + + ## Attributes + ``` val length : t -> int64 ``` Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. + ``` val set_binary_mode : t -> bool -> unit ``` `set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input. + `set_binary_mode ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. + This function has no effect under operating systems that do not distinguish between text mode and binary mode. + ``` val is_binary_mode : t -> bool ``` `is_binary_mode ic` returns whether the channel `ic` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). + since 5.2 ``` val isatty : t -> bool ``` `isatty ic` is `true` if `ic` refers to a terminal or console window, `false` otherwise. + since 5.1 + ## Examples + Reading the contents of a file: + ```ocaml let read_file file = In_channel.with_open_bin file In_channel.input_all ``` Reading a line from stdin: + ```ocaml let user_input () = In_channel.input_line In_channel.stdin ``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Int.md b/docs/api/melange/Stdlib-Int.md index 9f46e5b77..cf5344cce 100644 --- a/docs/api/melange/Stdlib-Int.md +++ b/docs/api/melange/Stdlib-Int.md @@ -1,135 +1,176 @@ + # Module `Stdlib.Int` + Integer values. + Integers are [`Sys.int_size`](./Stdlib-Sys.md#val-int_size) bits wide and use two's complement representation. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. + since 4.08 + ## Integers + ``` type t = int ``` The type for integer values. + ``` val zero : int ``` `zero` is the integer `0`. + ``` val one : int ``` `one` is the integer `1`. + ``` val minus_one : int ``` `minus_one` is the integer `-1`. + ``` val neg : int -> int ``` `neg x` is `~-x`. + ``` val add : int -> int -> int ``` `add x y` is the addition `x + y`. + ``` val sub : int -> int -> int ``` `sub x y` is the subtraction `x - y`. + ``` val mul : int -> int -> int ``` `mul x y` is the multiplication `x * y`. + ``` val div : int -> int -> int ``` `div x y` is the division `x / y`. See [`Stdlib.(/)`](./Stdlib.md#val-\(/\)) for details. + ``` val rem : int -> int -> int ``` `rem x y` is the remainder `x mod y`. See [`Stdlib.(mod)`](./Stdlib.md#val-\(mod\)) for details. + ``` val succ : int -> int ``` `succ x` is `add x 1`. + ``` val pred : int -> int ``` `pred x` is `sub x 1`. + ``` val abs : int -> int ``` `abs x` is the absolute value of `x`. That is `x` if `x` is positive and `neg x` if `x` is negative. **Warning.** This may be negative if the argument is [`min_int`](./#val-min_int). + ``` val max_int : int ``` `max_int` is the greatest representable integer, `2``Sys.int_size - 1``-1`. + ``` val min_int : int ``` `min_int` is the smallest representable integer, `-2``Sys.int_size - 1`. + ``` val logand : int -> int -> int ``` `logand x y` is the bitwise logical and of `x` and `y`. + ``` val logor : int -> int -> int ``` `logor x y` is the bitwise logical or of `x` and `y`. + ``` val logxor : int -> int -> int ``` `logxor x y` is the bitwise logical exclusive or of `x` and `y`. + ``` val lognot : int -> int ``` `lognot x` is the bitwise logical negation of `x`. + ``` val shift_left : int -> int -> int ``` `shift_left x n` shifts `x` to the left by `n` bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). + ``` val shift_right : int -> int -> int ``` `shift_right x n` shifts `x` to the right by `n` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). + ``` val shift_right_logical : int -> int -> int ``` `shift_right x n` shifts `x` to the right by `n` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). + + ## Predicates and comparisons + ``` val equal : int -> int -> bool ``` `equal x y` is `true` if and only if `x = y`. + ``` val compare : int -> int -> int ``` `compare x y` is [`Stdlib.compare`](./Stdlib.md#val-compare)` x y` but more efficient. + ``` val min : int -> int -> int ``` Return the smaller of the two arguments. + since 4.13 ``` val max : int -> int -> int ``` Return the greater of the two arguments. + since 4.13 + ## Converting + ``` val to_float : int -> float ``` `to_float x` is `x` as a floating point number. + ``` val of_float : float -> int ``` `of_float x` truncates `x` to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. + ``` val to_string : int -> string ``` `to_string x` is the written representation of `x` in decimal. + ``` val seeded_hash : int -> int -> int ``` A seeded hash function for ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.1 ``` val hash : int -> int ``` An unseeded hash function for ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Int32.md b/docs/api/melange/Stdlib-Int32.md index e1d0ca0ab..0f3011b3a 100644 --- a/docs/api/melange/Stdlib-Int32.md +++ b/docs/api/melange/Stdlib-Int32.md @@ -1,8 +1,14 @@ + # Module `Stdlib.Int32` + 32-bit integers. + This module provides operations on the type `int32` of signed 32-bit integers. Unlike the built-in `int` type, the type `int32` is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over `int32` are taken modulo 232. + Performance notice: values of type `int32` occupy more memory space than values of type `int`, and arithmetic operations on `int32` are generally slower than those on `int`. Use `int32` only when the application requires exact 32-bit arithmetic. + Literals for 32-bit integers are suffixed by l: + ```ocaml let zero: int32 = 0l let one: int32 = 1l @@ -12,177 +18,220 @@ Literals for 32-bit integers are suffixed by l: val zero : int32 ``` The 32-bit integer 0. + ``` val one : int32 ``` The 32-bit integer 1\. + ``` val minus_one : int32 ``` The 32-bit integer \-1. + ``` val neg : int32 -> int32 ``` Unary negation. + ``` val add : int32 -> int32 -> int32 ``` Addition. + ``` val sub : int32 -> int32 -> int32 ``` Subtraction. + ``` val mul : int32 -> int32 -> int32 ``` Multiplication. + ``` val div : int32 -> int32 -> int32 ``` Integer division. This division rounds the real quotient of its arguments towards zero, as specified for [`Stdlib.(/)`](./Stdlib.md#val-\(/\)). + raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. ``` val unsigned_div : int32 -> int32 -> int32 ``` Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 32-bit integers. + since 4.08 ``` val rem : int32 -> int32 -> int32 ``` Integer remainder. If `y` is not zero, the result of `Int32.rem x y` satisfies the following property: `x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)`. If `y = 0`, `Int32.rem x y` raises `Division_by_zero`. + ``` val unsigned_rem : int32 -> int32 -> int32 ``` Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 32-bit integers. + since 4.08 ``` val succ : int32 -> int32 ``` Successor. `Int32.succ x` is `Int32.add x Int32.one`. + ``` val pred : int32 -> int32 ``` Predecessor. `Int32.pred x` is `Int32.sub x Int32.one`. + ``` val abs : int32 -> int32 ``` `abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. + ``` val max_int : int32 ``` The greatest representable 32-bit integer, 231 \- 1\. + ``` val min_int : int32 ``` The smallest representable 32-bit integer, \-231. + ``` val logand : int32 -> int32 -> int32 ``` Bitwise logical and. + ``` val logor : int32 -> int32 -> int32 ``` Bitwise logical or. + ``` val logxor : int32 -> int32 -> int32 ``` Bitwise logical exclusive or. + ``` val lognot : int32 -> int32 ``` Bitwise logical negation. + ``` val shift_left : int32 -> int -> int32 ``` `Int32.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 32`. + ``` val shift_right : int32 -> int -> int32 ``` `Int32.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 32`. + ``` val shift_right_logical : int32 -> int -> int32 ``` `Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 32`. + ``` val of_int : int -> int32 ``` Convert the given integer (type `int`) to a 32-bit integer (type `int32`). On 64-bit platforms, the argument is taken modulo 232. + ``` val to_int : int32 -> int ``` Convert the given 32-bit integer (type `int32`) to an integer (type `int`). On 32-bit platforms, the 32-bit integer is taken modulo 231, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. + ``` val unsigned_to_int : int32 -> int option ``` Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. + since 4.08 ``` val of_float : float -> int32 ``` Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int32.min_int`](./#val-min_int), [`Int32.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. + ``` val to_float : int32 -> float ``` Convert the given 32-bit integer to a floating-point number. + ``` val of_string : string -> int32 ``` Convert the given string to a 32-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. + The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int32.max_int+1]`. If the input exceeds [`Int32.max_int`](./#val-max_int) it is converted to the signed integer `Int32.min_int + input - Int32.max_int - 1`. + The `_` (underscore) character can appear anywhere in the string and is ignored. + raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int32. ``` val of_string_opt : string -> int32 option ``` Same as `of_string`, but return `None` instead of raising. + since 4.05 ``` val to_string : int32 -> string ``` Return the string representation of its argument, in signed decimal. + ``` val bits_of_float : float -> int32 ``` Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa. + ``` val float_of_bits : int32 -> float ``` Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`. + ``` type t = int32 ``` An alias for the type of 32-bit integers. + ``` val compare : t -> t -> int ``` The comparison function for 32-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + ``` val unsigned_compare : t -> t -> int ``` Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 32-bit integers. + since 4.08 ``` val equal : t -> t -> bool ``` The equal function for int32s. + since 4.03 ``` val min : t -> t -> t ``` Return the smaller of the two arguments. + since 4.13 ``` val max : t -> t -> t ``` Return the greater of the two arguments. + since 4.13 ``` val seeded_hash : int -> t -> int ``` A seeded hash function for 32-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.1 ``` val hash : t -> int ``` An unseeded hash function for 32-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Int64.md b/docs/api/melange/Stdlib-Int64.md index 676e377b0..f7d334e83 100644 --- a/docs/api/melange/Stdlib-Int64.md +++ b/docs/api/melange/Stdlib-Int64.md @@ -1,8 +1,14 @@ + # Module `Stdlib.Int64` + 64-bit integers. + This module provides operations on the type `int64` of signed 64-bit integers. Unlike the built-in `int` type, the type `int64` is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over `int64` are taken modulo 264 + Performance notice: values of type `int64` occupy more memory space than values of type `int`, and arithmetic operations on `int64` are generally slower than those on `int`. Use `int64` only when the application requires exact 64-bit arithmetic. + Literals for 64-bit integers are suffixed by L: + ```ocaml let zero: int64 = 0L let one: int64 = 1L @@ -12,193 +18,240 @@ Literals for 64-bit integers are suffixed by L: val zero : int64 ``` The 64-bit integer 0. + ``` val one : int64 ``` The 64-bit integer 1\. + ``` val minus_one : int64 ``` The 64-bit integer \-1. + ``` val neg : int64 -> int64 ``` Unary negation. + ``` val add : int64 -> int64 -> int64 ``` Addition. + ``` val sub : int64 -> int64 -> int64 ``` Subtraction. + ``` val mul : int64 -> int64 -> int64 ``` Multiplication. + ``` val div : int64 -> int64 -> int64 ``` Integer division. + raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/). ``` val unsigned_div : int64 -> int64 -> int64 ``` Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 64-bit integers. + since 4.08 ``` val rem : int64 -> int64 -> int64 ``` Integer remainder. If `y` is not zero, the result of `Int64.rem x y` satisfies the following property: `x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)`. If `y = 0`, `Int64.rem x y` raises `Division_by_zero`. + ``` val unsigned_rem : int64 -> int64 -> int64 ``` Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 64-bit integers. + since 4.08 ``` val succ : int64 -> int64 ``` Successor. `Int64.succ x` is `Int64.add x Int64.one`. + ``` val pred : int64 -> int64 ``` Predecessor. `Int64.pred x` is `Int64.sub x Int64.one`. + ``` val abs : int64 -> int64 ``` `abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. + ``` val max_int : int64 ``` The greatest representable 64-bit integer, 263 \- 1\. + ``` val min_int : int64 ``` The smallest representable 64-bit integer, \-263. + ``` val logand : int64 -> int64 -> int64 ``` Bitwise logical and. + ``` val logor : int64 -> int64 -> int64 ``` Bitwise logical or. + ``` val logxor : int64 -> int64 -> int64 ``` Bitwise logical exclusive or. + ``` val lognot : int64 -> int64 ``` Bitwise logical negation. + ``` val shift_left : int64 -> int -> int64 ``` `Int64.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 64`. + ``` val shift_right : int64 -> int -> int64 ``` `Int64.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 64`. + ``` val shift_right_logical : int64 -> int -> int64 ``` `Int64.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 64`. + ``` val of_int : int -> int64 ``` Convert the given integer (type `int`) to a 64-bit integer (type `int64`). + ``` val to_int : int64 -> int ``` Convert the given 64-bit integer (type `int64`) to an integer (type `int`). On 64-bit platforms, the 64-bit integer is taken modulo 263, i.e. the high-order bit is lost during the conversion. On 32-bit platforms, the 64-bit integer is taken modulo 231, i.e. the top 33 bits are lost during the conversion. + ``` val unsigned_to_int : int64 -> int option ``` Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. + since 4.08 ``` val of_float : float -> int64 ``` Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int64.min_int`](./#val-min_int), [`Int64.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. + ``` val to_float : int64 -> float ``` Convert the given 64-bit integer to a floating-point number. + ``` val of_int32 : int32 -> int64 ``` Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`). + ``` val to_int32 : int64 -> int32 ``` Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). The 64-bit integer is taken modulo 232, i.e. the top 32 bits are lost during the conversion. + ``` val of_nativeint : nativeint -> int64 ``` Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`). + ``` val to_nativeint : int64 -> nativeint ``` Convert the given 64-bit integer (type `int64`) to a native integer. On 32-bit platforms, the 64-bit integer is taken modulo 232. On 64-bit platforms, the conversion is exact. + ``` val of_string : string -> int64 ``` Convert the given string to a 64-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. + The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int64.max_int+1]`. If the input exceeds [`Int64.max_int`](./#val-max_int) it is converted to the signed integer `Int64.min_int + input - Int64.max_int - 1`. + The `_` (underscore) character can appear anywhere in the string and is ignored. + raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int64. ``` val of_string_opt : string -> int64 option ``` Same as `of_string`, but return `None` instead of raising. + since 4.05 ``` val to_string : int64 -> string ``` Return the string representation of its argument, in decimal. + ``` val bits_of_float : float -> int64 ``` Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. Bit 63 of the result represents the sign of the float; bits 62 to 52 represent the (biased) exponent; bits 51 to 0 represent the mantissa. + ``` val float_of_bits : int64 -> float ``` Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`. + ``` type t = int64 ``` An alias for the type of 64-bit integers. + ``` val compare : t -> t -> int ``` The comparison function for 64-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int64` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + ``` val unsigned_compare : t -> t -> int ``` Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 64-bit integers. + since 4.08 ``` val equal : t -> t -> bool ``` The equal function for int64s. + since 4.03 ``` val min : t -> t -> t ``` Return the smaller of the two arguments. + since 4.13 ``` val max : t -> t -> t ``` Return the greater of the two arguments. + since 4.13 ``` val seeded_hash : int -> t -> int ``` A seeded hash function for 64-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.1 ``` val hash : t -> int ``` An unseeded hash function for 64-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-LargeFile.md b/docs/api/melange/Stdlib-LargeFile.md index 2c120e4de..b4e663dc2 100644 --- a/docs/api/melange/Stdlib-LargeFile.md +++ b/docs/api/melange/Stdlib-LargeFile.md @@ -1,5 +1,8 @@ + # Module `Stdlib.LargeFile` + Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. + ``` val seek_out : out_channel -> int64 -> unit ``` diff --git a/docs/api/melange/Stdlib-Lazy.md b/docs/api/melange/Stdlib-Lazy.md index 9c36975cf..519b7cec5 100644 --- a/docs/api/melange/Stdlib-Lazy.md +++ b/docs/api/melange/Stdlib-Lazy.md @@ -1,9 +1,13 @@ + # Module `Stdlib.Lazy` + Deferred computations. + ``` type 'a t = 'a CamlinternalLazy.t ``` A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. The special expression syntax `lazy (expr)` makes a suspension of the computation of `expr`, without computing `expr` itself yet. "Forcing" the suspension will then compute `expr` and return its result. Matching a suspension with the special pattern syntax `lazy(pattern)` also computes the underlying expression and tries to bind it to `pattern`: + ```ocaml let lazy_option_map f x = match x with @@ -11,56 +15,81 @@ A value of type `'a Lazy.t` is a deferred computation, called a suspension, that | _ -> None ``` Note: If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may be forced even outside of the case ultimately selected by the pattern matching. In the example above, the suspension `x` is always computed. + Note: `lazy_t` is the built-in type constructor used by the compiler for the `lazy` keyword. You should not use it directly. Always use `Lazy.t` instead. + Note: `Lazy.force` is not concurrency-safe. If you use this module with multiple fibers, systhreads or domains, then you will need to add some locks. The module however ensures memory-safety, and hence, concurrently accessing this module will not lead to a crash but the behaviour is unspecified. + Note: if the program is compiled with the `-rectypes` option, ill-founded recursive definitions of the form `let rec x = lazy x` or `let rec x = lazy(lazy(...(lazy x)))` are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the `-rectypes` option, such ill-founded recursive definitions are rejected by the type-checker. + ``` exception Undefined ``` Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or when the suspension tries to force itself recursively. + ``` val force : 'a t -> 'a ``` `force x` forces the suspension `x` and returns its result. If `x` has already been forced, `Lazy.force x` returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. + raises [`Undefined`](./#exception-Undefined) (see Undefined). + ## Iterators + ``` val map : ('a -> 'b) -> 'a t -> 'b t ``` `map f x` returns a suspension that, when forced, forces `x` and applies `f` to its value. + It is equivalent to `lazy (f (Lazy.force x))`. + since 4.13 + ## Reasoning on already-forced suspensions + ``` val is_val : 'a t -> bool ``` `is_val x` returns `true` if `x` has already been forced and did not raise an exception. + since 4.00 ``` val from_val : 'a -> 'a t ``` `from_val v` evaluates `v` first (as any function would) and returns an already-forced suspension of its result. It is the same as `let x = v in lazy x`, but uses dynamic tests to optimize suspension creation in some cases. + since 4.00 ``` val map_val : ('a -> 'b) -> 'a t -> 'b t ``` `map_val f x` applies `f` directly if `x` is already forced, otherwise it behaves as `map f x`. + When `x` is already forced, this behavior saves the construction of a suspension, but on the other hand it performs more work eagerly that may not be useful if you never force the function result. + If `f` raises an exception, it will be raised immediately when `is_val x`, or raised only when forcing the thunk otherwise. + If `map_val f x` does not raise an exception, then `is_val (map_val f x)` is equal to `is_val x`. + since 4.13 + ## Advanced + The following definitions are for advanced uses only; they require familiarity with the lazy compilation scheme to be used appropriately. + ``` val from_fun : (unit -> 'a) -> 'a t ``` `from_fun f` is the same as `lazy (f ())` but slightly more efficient. + It should only be used if the function `f` is already defined. In particular it is always less efficient to write `from_fun (fun () -> expr)` than `lazy expr`. + since 4.00 ``` val force_val : 'a t -> 'a ``` `force_val x` forces the suspension `x` and returns its result. If `x` has already been forced, `force_val x` returns the same value again without recomputing it. + If the computation of `x` raises an exception, it is unspecified whether `force_val x` raises the same exception or [`Undefined`](./#exception-Undefined). + raises [`Undefined`](./#exception-Undefined) if the forcing of x tries to force x itself recursively. raises [`Undefined`](./#exception-Undefined) (see Undefined). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Lexing.md b/docs/api/melange/Stdlib-Lexing.md index adf419b31..44ca6045c 100644 --- a/docs/api/melange/Stdlib-Lexing.md +++ b/docs/api/melange/Stdlib-Lexing.md @@ -1,6 +1,11 @@ + # Module `Stdlib.Lexing` + The run-time library for lexers generated by `ocamllex`. + + ## Positions + ``` type position = { ``` @@ -12,12 +17,17 @@ type position = { } ``` A value of type `position` describes a point in a source file. `pos_fname` is the file name; `pos_lnum` is the line number; `pos_bol` is the offset of the beginning of the line (number of characters between the beginning of the lexbuf and the beginning of the line); `pos_cnum` is the offset of the position (number of characters between the beginning of the lexbuf and the position). The difference between `pos_cnum` and `pos_bol` is the character offset within the line (i.e. the column number, assuming each character is one column wide). + See the documentation of type `lexbuf` for information about how the lexing engine will manage positions. + ``` val dummy_pos : position ``` A value of type `position`, guaranteed to be different from any valid position. + + ## Lexer buffers + ``` type lexbuf = { ``` @@ -37,68 +47,90 @@ type lexbuf = { } ``` The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input. + Lexers can optionally maintain the `lex_curr_p` and `lex_start_p` position fields. This "position tracking" mode is the default, and it corresponds to passing `~with_position:true` to functions that create lexer buffers. In this mode, the lexing engine and lexer actions are co-responsible for properly updating the position fields, as described in the next paragraph. When the mode is explicitly disabled (with `~with_position:false`), the lexing engine will not touch the position fields and the lexer actions should be careful not to do it either; the `lex_curr_p` and `lex_start_p` field will then always hold the `dummy_pos` invalid position. Not tracking positions avoids allocations and memory writes and can significantly improve the performance of the lexer in contexts where `lex_start_p` and `lex_curr_p` are not needed. + Position tracking mode works as follows. At each token, the lexing engine will copy `lex_curr_p` to `lex_start_p`, then change the `pos_cnum` field of `lex_curr_p` by updating it with the number of characters read since the start of the `lexbuf`. The other fields are left unchanged by the lexing engine. In order to keep them accurate, they must be initialised before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end of line \-- see also `new_line`). + ``` val from_channel : ?with_positions:bool -> in_channel -> lexbuf ``` Create a lexer buffer on the given input channel. `Lexing.from_channel inchan` returns a lexer buffer which reads from the input channel `inchan`, at the current reading position. + ``` val from_string : ?with_positions:bool -> string -> lexbuf ``` Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached. + ``` val from_function : ?with_positions:bool -> (bytes -> int -> int) -> lexbuf ``` Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a byte sequence `s` and a byte count `n`. The function should put `n` bytes or fewer in `s`, starting at index 0, and return the number of bytes provided. A return value of 0 means end of input. + ``` val set_position : lexbuf -> position -> unit ``` Set the initial tracked input position for `lexbuf` to a custom value. Ignores `pos_fname`. See [`set_filename`](./#val-set_filename) for changing this field. + since 4.11 ``` val set_filename : lexbuf -> string -> unit ``` Set filename in the initial tracked position to `file` in `lexbuf`. + since 4.11 ``` val with_positions : lexbuf -> bool ``` Tell whether the lexer buffer keeps track of position fields `lex_curr_p` / `lex_start_p`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`). + When `with_positions` is `false`, lexer actions should not modify position fields. Doing it nevertheless could re-enable the `with_position` mode and degrade performances. + + ## Functions for lexer semantic actions + The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument `lexbuf`, which, in the code generated by `ocamllex`, is bound to the lexer buffer passed to the parsing function. + ``` val lexeme : lexbuf -> string ``` `Lexing.lexeme lexbuf` returns the string matched by the regular expression. + ``` val lexeme_char : lexbuf -> int -> char ``` `Lexing.lexeme_char lexbuf i` returns character number `i` in the matched string. + ``` val lexeme_start : lexbuf -> int ``` `Lexing.lexeme_start lexbuf` returns the offset in the input stream of the first character of the matched string. The first character of the stream has offset 0. + ``` val lexeme_end : lexbuf -> int ``` `Lexing.lexeme_end lexbuf` returns the offset in the input stream of the character following the last character of the matched string. The first character of the stream has offset 0. + ``` val lexeme_start_p : lexbuf -> position ``` Like `lexeme_start`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. + ``` val lexeme_end_p : lexbuf -> position ``` Like `lexeme_end`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. + ``` val new_line : lexbuf -> unit ``` Update the `lex_curr_p` field of the lexbuf to reflect the start of a new line. You can call this function in the semantic action of the rule that matches the end-of-line character. The function does nothing when position tracking is disabled. + since 3.11 + ## Miscellaneous functions + ``` val flush_input : lexbuf -> unit ``` -Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill. \ No newline at end of file +Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill. diff --git a/docs/api/melange/Stdlib-List.md b/docs/api/melange/Stdlib-List.md index b5c404618..448c79785 100644 --- a/docs/api/melange/Stdlib-List.md +++ b/docs/api/melange/Stdlib-List.md @@ -1,8 +1,14 @@ + # Module `Stdlib.List` + List operations. + Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. + The above considerations can usually be ignored if your lists are not longer than about 10000 elements. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + ``` type 'a t = 'a list = ``` @@ -16,126 +22,157 @@ type 'a t = 'a list = ``` An alias for the type of lists. + ``` val length : 'a list -> int ``` Return the length (number of elements) of the given list. + ``` val compare_lengths : 'a list -> 'b list -> int ``` Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. + since 4.05 ``` val compare_length_with : 'a list -> int -> int ``` Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. + since 4.05 ``` val is_empty : 'a list -> bool ``` `is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. + since 5.1 ``` val cons : 'a -> 'a list -> 'a list ``` `cons x xs` is `x :: xs` + since 4.03 (4.05 in ListLabels) ``` val hd : 'a list -> 'a ``` Return the first element of the given list. + raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. ``` val tl : 'a list -> 'a list ``` Return the given list without its first element. + raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. ``` val nth : 'a list -> int -> 'a ``` Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. + raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. ``` val nth_opt : 'a list -> int -> 'a option ``` Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 4.05 ``` val rev : 'a list -> 'a list ``` List reversal. + ``` val init : int -> (int -> 'a) -> 'a list ``` `init len f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. since 4.06 ``` val append : 'a list -> 'a list -> 'a list ``` `append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. + since 5.1 this function is tail-recursive. ``` val rev_append : 'a list -> 'a list -> 'a list ``` `rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. + ``` val concat : 'a list list -> 'a list ``` Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). + ``` val flatten : 'a list list -> 'a list ``` Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). + + ## Comparison + ``` val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool ``` `equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. + Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. + since 4.12 ``` val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int ``` `compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): + - `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` - the empty list `[]` is strictly smaller than non-empty lists Note: the `cmp` function will be called even if the lists have different lengths. + since 4.12 + ## Iterators + ``` val iter : ('a -> unit) -> 'a list -> unit ``` `iter f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. + ``` val iteri : (int -> 'a -> unit) -> 'a list -> unit ``` Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 4.00 ``` val map : ('a -> 'b) -> 'a list -> 'b list ``` `map f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. + ``` val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list ``` Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 4.00 ``` val rev_map : ('a -> 'b) -> 'a list -> 'b list ``` `rev_map f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. + ``` val filter_map : ('a -> 'b option) -> 'a list -> 'b list ``` `filter_map f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. + since 4.08 ``` val concat_map : ('a -> 'b list) -> 'a list -> 'b list ``` `concat_map f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. + since 4.10 ``` val fold_left_map : @@ -145,30 +182,38 @@ val fold_left_map : 'acc * 'b list ``` `fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. + since 4.11 ``` val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc ``` `fold_left f init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. + ``` val fold_right : ('a -> 'acc -> 'acc) -> 'a list -> 'acc -> 'acc ``` `fold_right f [a1; ...; an] init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. + + ## Iterators on two lists + ``` val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit ``` `iter2 f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list ``` `map2 f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list ``` `rev_map2 f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. + ``` val fold_left2 : ('acc -> 'a -> 'b -> 'acc) -> @@ -178,6 +223,7 @@ val fold_left2 : 'acc ``` `fold_left2 f init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val fold_right2 : @@ -188,190 +234,249 @@ val fold_right2 : 'acc ``` `fold_right2 f [a1; ...; an] [b1; ...; bn] init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. + ## List scanning + ``` val for_all : ('a -> bool) -> 'a list -> bool ``` `for_all f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. + ``` val exists : ('a -> bool) -> 'a list -> bool ``` `exists f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. + ``` val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool ``` Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool ``` Same as [`exists`](./#val-exists), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val mem : 'a -> 'a list -> bool ``` `mem a set` is true if and only if `a` is equal to an element of `set`. + ``` val memq : 'a -> 'a list -> bool ``` Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. + + ## List searching + ``` val find : ('a -> bool) -> 'a list -> 'a ``` `find f l` returns the first element of the list `l` that satisfies the predicate `f`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. ``` val find_opt : ('a -> bool) -> 'a list -> 'a option ``` `find f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. + since 4.05 ``` val find_index : ('a -> bool) -> 'a list -> int option ``` `find_index f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. + It returns `None` if there is no such element. + since 5.1 ``` val find_map : ('a -> 'b option) -> 'a list -> 'b option ``` `find_map f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. + since 4.10 ``` val find_mapi : (int -> 'a -> 'b option) -> 'a list -> 'b option ``` Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 5.1 ``` val filter : ('a -> bool) -> 'a list -> 'a list ``` `filter f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. + ``` val find_all : ('a -> bool) -> 'a list -> 'a list ``` `find_all` is another name for [`filter`](./#val-filter). + ``` val filteri : (int -> 'a -> bool) -> 'a list -> 'a list ``` Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 4.11 + ## List manipulation + ``` val take : int -> 'a list -> 'a list ``` `take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. + `n` must be nonnegative. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 5.3 ``` val drop : int -> 'a list -> 'a list ``` `drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. + `n` must be nonnegative. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 5.3 ``` val take_while : ('a -> bool) -> 'a list -> 'a list ``` `take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. + since 5.3 ``` val drop_while : ('a -> bool) -> 'a list -> 'a list ``` `drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. + since 5.3 ``` val partition : ('a -> bool) -> 'a list -> 'a list * 'a list ``` `partition f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. + ``` val partition_map : ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list ``` `partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: + - if `f x` is `Left y1`, then `y1` is in `l1`, and - if `f x` is `Right y2`, then `y2` is in `l2`. The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. + In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. + since 4.12 + ## Association lists + ``` val assoc : 'a -> ('a * 'b) list -> 'b ``` `assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. ``` val assoc_opt : 'a -> ('a * 'b) list -> 'b option ``` `assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. + since 4.05 ``` val assq : 'a -> ('a * 'b) list -> 'b ``` Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. + ``` val assq_opt : 'a -> ('a * 'b) list -> 'b option ``` Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. + since 4.05 ``` val mem_assoc : 'a -> ('a * 'b) list -> bool ``` Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. + ``` val mem_assq : 'a -> ('a * 'b) list -> bool ``` Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. + ``` val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list ``` `remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. + ``` val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list ``` Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. + + ## Lists of pairs + ``` val split : ('a * 'b) list -> 'a list * 'b list ``` Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. + ``` val combine : 'a list -> 'b list -> ('a * 'b) list ``` Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. + ## Sorting + ``` val sort : ('a -> 'a -> int) -> 'a list -> 'a list ``` Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. + The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + ``` val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list ``` Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). + The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + ``` val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list ``` Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + ``` val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list ``` Same as [`sort`](./#val-sort), but also remove duplicates. + since 4.02 (4.03 in ListLabels) ``` val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list ``` Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). + + ## Lists and Sequences + ``` val to_seq : 'a list -> 'a Seq.t ``` Iterate on the list. + since 4.07 ``` val of_seq : 'a Seq.t -> 'a list ``` Create a list from a sequence. + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-ListLabels.md b/docs/api/melange/Stdlib-ListLabels.md index 2ea636627..03b11df1f 100644 --- a/docs/api/melange/Stdlib-ListLabels.md +++ b/docs/api/melange/Stdlib-ListLabels.md @@ -1,8 +1,14 @@ + # Module `Stdlib.ListLabels` + List operations. + Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. + The above considerations can usually be ignored if your lists are not longer than about 10000 elements. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + ``` type 'a t = 'a list = ``` @@ -16,126 +22,157 @@ type 'a t = 'a list = ``` An alias for the type of lists. + ``` val length : 'a list -> int ``` Return the length (number of elements) of the given list. + ``` val compare_lengths : 'a list -> 'b list -> int ``` Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. + since 4.05 ``` val compare_length_with : 'a list -> len:int -> int ``` Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. + since 4.05 ``` val is_empty : 'a list -> bool ``` `is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. + since 5.1 ``` val cons : 'a -> 'a list -> 'a list ``` `cons x xs` is `x :: xs` + since 4.03 (4.05 in ListLabels) ``` val hd : 'a list -> 'a ``` Return the first element of the given list. + raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. ``` val tl : 'a list -> 'a list ``` Return the given list without its first element. + raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. ``` val nth : 'a list -> int -> 'a ``` Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. + raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. ``` val nth_opt : 'a list -> int -> 'a option ``` Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 4.05 ``` val rev : 'a list -> 'a list ``` List reversal. + ``` val init : len:int -> f:(int -> 'a) -> 'a list ``` `init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. since 4.06 ``` val append : 'a list -> 'a list -> 'a list ``` `append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. + since 5.1 this function is tail-recursive. ``` val rev_append : 'a list -> 'a list -> 'a list ``` `rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. + ``` val concat : 'a list list -> 'a list ``` Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). + ``` val flatten : 'a list list -> 'a list ``` Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). + + ## Comparison + ``` val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool ``` `equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. + Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. + since 4.12 ``` val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int ``` `compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): + - `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` - the empty list `[]` is strictly smaller than non-empty lists Note: the `cmp` function will be called even if the lists have different lengths. + since 4.12 + ## Iterators + ``` val iter : f:('a -> unit) -> 'a list -> unit ``` `iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. + ``` val iteri : f:(int -> 'a -> unit) -> 'a list -> unit ``` Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 4.00 ``` val map : f:('a -> 'b) -> 'a list -> 'b list ``` `map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. + ``` val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list ``` Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 4.00 ``` val rev_map : f:('a -> 'b) -> 'a list -> 'b list ``` `rev_map ~f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. + ``` val filter_map : f:('a -> 'b option) -> 'a list -> 'b list ``` `filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. + since 4.08 ``` val concat_map : f:('a -> 'b list) -> 'a list -> 'b list ``` `concat_map ~f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. + since 4.10 ``` val fold_left_map : @@ -145,30 +182,38 @@ val fold_left_map : 'acc * 'b list ``` `fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. + since 4.11 ``` val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc ``` `fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. + ``` val fold_right : f:('a -> 'acc -> 'acc) -> 'a list -> init:'acc -> 'acc ``` `fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. + + ## Iterators on two lists + ``` val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit ``` `iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list ``` `map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list ``` `rev_map2 ~f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. + ``` val fold_left2 : f:('acc -> 'a -> 'b -> 'acc) -> @@ -178,6 +223,7 @@ val fold_left2 : 'acc ``` `fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val fold_right2 : @@ -188,190 +234,249 @@ val fold_right2 : 'acc ``` `fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. + ## List scanning + ``` val for_all : f:('a -> bool) -> 'a list -> bool ``` `for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. + ``` val exists : f:('a -> bool) -> 'a list -> bool ``` `exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. + ``` val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool ``` Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool ``` Same as [`exists`](./#val-exists), but for a two-argument predicate. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. ``` val mem : 'a -> set:'a list -> bool ``` `mem a ~set` is true if and only if `a` is equal to an element of `set`. + ``` val memq : 'a -> set:'a list -> bool ``` Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. + + ## List searching + ``` val find : f:('a -> bool) -> 'a list -> 'a ``` `find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. ``` val find_opt : f:('a -> bool) -> 'a list -> 'a option ``` `find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. + since 4.05 ``` val find_index : f:('a -> bool) -> 'a list -> int option ``` `find_index ~f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. + It returns `None` if there is no such element. + since 5.1 ``` val find_map : f:('a -> 'b option) -> 'a list -> 'b option ``` `find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. + since 4.10 ``` val find_mapi : f:(int -> 'a -> 'b option) -> 'a list -> 'b option ``` Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 5.1 ``` val filter : f:('a -> bool) -> 'a list -> 'a list ``` `filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. + ``` val find_all : f:('a -> bool) -> 'a list -> 'a list ``` `find_all` is another name for [`filter`](./#val-filter). + ``` val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list ``` Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + since 4.11 + ## List manipulation + ``` val take : int -> 'a list -> 'a list ``` `take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. + `n` must be nonnegative. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 5.3 ``` val drop : int -> 'a list -> 'a list ``` `drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. + `n` must be nonnegative. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 5.3 ``` val take_while : f:('a -> bool) -> 'a list -> 'a list ``` `take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. + since 5.3 ``` val drop_while : f:('a -> bool) -> 'a list -> 'a list ``` `drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. + since 5.3 ``` val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list ``` `partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. + ``` val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list ``` `partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: + - if `f x` is `Left y1`, then `y1` is in `l1`, and - if `f x` is `Right y2`, then `y2` is in `l2`. The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. + In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. + since 4.12 + ## Association lists + ``` val assoc : 'a -> ('a * 'b) list -> 'b ``` `assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. ``` val assoc_opt : 'a -> ('a * 'b) list -> 'b option ``` `assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. + since 4.05 ``` val assq : 'a -> ('a * 'b) list -> 'b ``` Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. + ``` val assq_opt : 'a -> ('a * 'b) list -> 'b option ``` Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. + since 4.05 ``` val mem_assoc : 'a -> map:('a * 'b) list -> bool ``` Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. + ``` val mem_assq : 'a -> map:('a * 'b) list -> bool ``` Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. + ``` val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list ``` `remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. + ``` val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list ``` Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. + + ## Lists of pairs + ``` val split : ('a * 'b) list -> 'a list * 'b list ``` Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. + ``` val combine : 'a list -> 'b list -> ('a * 'b) list ``` Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. + ## Sorting + ``` val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list ``` Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. + The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + ``` val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list ``` Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). + The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + ``` val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list ``` Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + ``` val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list ``` Same as [`sort`](./#val-sort), but also remove duplicates. + since 4.02 (4.03 in ListLabels) ``` val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list ``` Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). + + ## Lists and Sequences + ``` val to_seq : 'a list -> 'a Seq.t ``` Iterate on the list. + since 4.07 ``` val of_seq : 'a Seq.t -> 'a list ``` Create a list from a sequence. + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md index 6fcf99036..d02ffc06f 100644 --- a/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md +++ b/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md @@ -1,9 +1,12 @@ + # Parameter `Make.Ord` + ``` type t ``` The type of the map keys. + ``` val compare : t -> t -> int ``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-Map-Make.md b/docs/api/melange/Stdlib-Map-Make.md index 712cb4188..ce73f7b9a 100644 --- a/docs/api/melange/Stdlib-Map-Make.md +++ b/docs/api/melange/Stdlib-Map-Make.md @@ -1,47 +1,64 @@ + # Module `Map.Make` + Functor building an implementation of the map structure given a totally ordered type. + + ## Parameters + ``` module Ord : OrderedType ``` + ## Signature + + ## Maps + ``` type key = Ord.t ``` The type of the map keys. + ``` type !+'a t ``` The type of maps from type `key` to type `'a`. + ``` val empty : 'a t ``` The empty map. + ``` val add : key -> 'a -> 'a t -> 'a t ``` `add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + before 4.03 Physical equality was not ensured. ``` val add_to_list : key -> 'a -> 'a list t -> 'a list t ``` `add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + since 5.1 ``` val update : key -> ('a option -> 'a option) -> 'a t -> 'a t ``` `update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + since 4.06 ``` val singleton : key -> 'a -> 'a t ``` `singleton x y` returns the one-element map that contains a binding `y` for `x`. + since 3.12 ``` val remove : key -> 'a t -> 'a t ``` `remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + before 4.03 Physical equality was not ensured. ``` val merge : @@ -51,11 +68,13 @@ val merge : 'c t ``` `merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + since 3.12 ``` val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t ``` `union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + - `f' _key None None = None` - `f' _key (Some v) None = Some v` - `f' _key None (Some v) = Some v` @@ -65,182 +84,232 @@ since 4.03 val cardinal : 'a t -> int ``` Return the number of bindings of a map. + since 3.12 + ## Bindings + ``` val bindings : 'a t -> (key * 'a) list ``` Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). + since 3.12 ``` val min_binding : 'a t -> key * 'a ``` Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + since 3.12 ``` val min_binding_opt : 'a t -> (key * 'a) option ``` Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + since 4.05 ``` val max_binding : 'a t -> key * 'a ``` Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + since 3.12 ``` val max_binding_opt : 'a t -> (key * 'a) option ``` Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + since 4.05 ``` val choose : 'a t -> key * 'a ``` Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 3.12 ``` val choose_opt : 'a t -> (key * 'a) option ``` Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 4.05 + ## Searching + ``` val find : key -> 'a t -> 'a ``` `find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + ``` val find_opt : key -> 'a t -> 'a option ``` `find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + since 4.05 ``` val find_first : (key -> bool) -> 'a t -> key * 'a ``` `find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + since 4.05 ``` val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option ``` `find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 ``` val find_last : (key -> bool) -> 'a t -> key * 'a ``` `find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + since 4.05 ``` val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option ``` `find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 + ## Traversing + ``` val iter : (key -> 'a -> unit) -> 'a t -> unit ``` `iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc ``` `fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + ## Transforming + ``` val map : ('a -> 'b) -> 'a t -> 'b t ``` `map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t ``` Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + ``` val filter : (key -> 'a -> bool) -> 'a t -> 'a t ``` `filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + since 3.12 before 4.03 Physical equality was not ensured. ``` val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t ``` `filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + - if `f k v` is `None` then `k` is not in the result, - if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. For example, the following function on maps whose values are lists + ```ocaml filter_map (fun _k li -> match li with [] -> None | _::tl -> Some tl) m ``` drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + since 4.11 ``` val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t ``` `partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + since 3.12 ``` val split : key -> 'a t -> 'a t * 'a option * 'a t ``` `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + since 3.12 + ## Predicates and comparisons + ``` val is_empty : 'a t -> bool ``` Test whether a map is empty or not. + ``` val mem : key -> 'a t -> bool ``` `mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + ``` val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool ``` `equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + ``` val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int ``` Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + ``` val for_all : (key -> 'a -> bool) -> 'a t -> bool ``` `for_all f m` checks if all the bindings of the map satisfy the predicate `f`. + since 3.12 ``` val exists : (key -> 'a -> bool) -> 'a t -> bool ``` `exists f m` checks if at least one binding of the map satisfies the predicate `f`. + since 3.12 + ## Converting + ``` val to_list : 'a t -> (key * 'a) list ``` `to_list m` is [`bindings`](./#val-bindings)` m`. + since 5.1 ``` val of_list : (key * 'a) list -> 'a t ``` `of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + since 5.1 ``` val to_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in ascending order of keys + since 4.07 ``` val to_rev_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in descending order of keys + since 4.12 ``` val to_seq_from : key -> 'a t -> (key * 'a) Seq.t ``` `to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + since 4.07 ``` val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t ``` Add the given bindings to the map, in order. + since 4.07 ``` val of_seq : (key * 'a) Seq.t -> 'a t ``` Build a map from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map-module-type-OrderedType.md b/docs/api/melange/Stdlib-Map-module-type-OrderedType.md index 5e6859113..269a6a025 100644 --- a/docs/api/melange/Stdlib-Map-module-type-OrderedType.md +++ b/docs/api/melange/Stdlib-Map-module-type-OrderedType.md @@ -1,10 +1,14 @@ + # Module type `Map.OrderedType` + Input signature of the functor [`Make`](./Stdlib-Map-Make.md). + ``` type t ``` The type of the map keys. + ``` val compare : t -> t -> int ``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-Map-module-type-S.md b/docs/api/melange/Stdlib-Map-module-type-S.md index cc3c77be4..849b1ff51 100644 --- a/docs/api/melange/Stdlib-Map-module-type-S.md +++ b/docs/api/melange/Stdlib-Map-module-type-S.md @@ -1,42 +1,55 @@ + # Module type `Map.S` + Output signature of the functor [`Make`](./Stdlib-Map-Make.md). + + ## Maps + ``` type key ``` The type of the map keys. + ``` type !+'a t ``` The type of maps from type `key` to type `'a`. + ``` val empty : 'a t ``` The empty map. + ``` val add : key -> 'a -> 'a t -> 'a t ``` `add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + before 4.03 Physical equality was not ensured. ``` val add_to_list : key -> 'a -> 'a list t -> 'a list t ``` `add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + since 5.1 ``` val update : key -> ('a option -> 'a option) -> 'a t -> 'a t ``` `update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + since 4.06 ``` val singleton : key -> 'a -> 'a t ``` `singleton x y` returns the one-element map that contains a binding `y` for `x`. + since 3.12 ``` val remove : key -> 'a t -> 'a t ``` `remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + before 4.03 Physical equality was not ensured. ``` val merge : @@ -46,11 +59,13 @@ val merge : 'c t ``` `merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + since 3.12 ``` val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t ``` `union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + - `f' _key None None = None` - `f' _key (Some v) None = Some v` - `f' _key None (Some v) = Some v` @@ -60,182 +75,232 @@ since 4.03 val cardinal : 'a t -> int ``` Return the number of bindings of a map. + since 3.12 + ## Bindings + ``` val bindings : 'a t -> (key * 'a) list ``` Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-Map-Make.md). + since 3.12 ``` val min_binding : 'a t -> key * 'a ``` Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + since 3.12 ``` val min_binding_opt : 'a t -> (key * 'a) option ``` Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + since 4.05 ``` val max_binding : 'a t -> key * 'a ``` Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + since 3.12 ``` val max_binding_opt : 'a t -> (key * 'a) option ``` Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + since 4.05 ``` val choose : 'a t -> key * 'a ``` Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 3.12 ``` val choose_opt : 'a t -> (key * 'a) option ``` Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 4.05 + ## Searching + ``` val find : key -> 'a t -> 'a ``` `find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + ``` val find_opt : key -> 'a t -> 'a option ``` `find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + since 4.05 ``` val find_first : (key -> bool) -> 'a t -> key * 'a ``` `find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + since 4.05 ``` val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option ``` `find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 ``` val find_last : (key -> bool) -> 'a t -> key * 'a ``` `find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + since 4.05 ``` val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option ``` `find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 + ## Traversing + ``` val iter : (key -> 'a -> unit) -> 'a t -> unit ``` `iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc ``` `fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + ## Transforming + ``` val map : ('a -> 'b) -> 'a t -> 'b t ``` `map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t ``` Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + ``` val filter : (key -> 'a -> bool) -> 'a t -> 'a t ``` `filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + since 3.12 before 4.03 Physical equality was not ensured. ``` val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t ``` `filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + - if `f k v` is `None` then `k` is not in the result, - if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. For example, the following function on maps whose values are lists + ```ocaml filter_map (fun _k li -> match li with [] -> None | _::tl -> Some tl) m ``` drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + since 4.11 ``` val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t ``` `partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + since 3.12 ``` val split : key -> 'a t -> 'a t * 'a option * 'a t ``` `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + since 3.12 + ## Predicates and comparisons + ``` val is_empty : 'a t -> bool ``` Test whether a map is empty or not. + ``` val mem : key -> 'a t -> bool ``` `mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + ``` val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool ``` `equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + ``` val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int ``` Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + ``` val for_all : (key -> 'a -> bool) -> 'a t -> bool ``` `for_all f m` checks if all the bindings of the map satisfy the predicate `f`. + since 3.12 ``` val exists : (key -> 'a -> bool) -> 'a t -> bool ``` `exists f m` checks if at least one binding of the map satisfies the predicate `f`. + since 3.12 + ## Converting + ``` val to_list : 'a t -> (key * 'a) list ``` `to_list m` is [`bindings`](./#val-bindings)` m`. + since 5.1 ``` val of_list : (key * 'a) list -> 'a t ``` `of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + since 5.1 ``` val to_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in ascending order of keys + since 4.07 ``` val to_rev_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in descending order of keys + since 4.12 ``` val to_seq_from : key -> 'a t -> (key * 'a) Seq.t ``` `to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + since 4.07 ``` val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t ``` Add the given bindings to the map, in order. + since 4.07 ``` val of_seq : (key * 'a) Seq.t -> 'a t ``` Build a map from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Map.md b/docs/api/melange/Stdlib-Map.md index 1593aa278..e91aa6845 100644 --- a/docs/api/melange/Stdlib-Map.md +++ b/docs/api/melange/Stdlib-Map.md @@ -1,7 +1,12 @@ + # Module `Stdlib.Map` + Association tables over ordered types. + This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + For instance: + ```ocaml module IntPairs = struct @@ -17,15 +22,18 @@ For instance: let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world") ``` This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. + ``` module type OrderedType = sig ... end ``` Input signature of the functor [`Make`](./Stdlib-Map-Make.md). + ``` module type S = sig ... end ``` Output signature of the functor [`Make`](./Stdlib-Map-Make.md). + ``` module Make (Ord : OrderedType) : S with type key = Ord.t ``` -Functor building an implementation of the map structure given a totally ordered type. \ No newline at end of file +Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/melange/Stdlib-Marshal.md b/docs/api/melange/Stdlib-Marshal.md index af037840f..b2619652a 100644 --- a/docs/api/melange/Stdlib-Marshal.md +++ b/docs/api/melange/Stdlib-Marshal.md @@ -1,10 +1,17 @@ + # Module `Stdlib.Marshal` + Marshaling of data structures. + This module provides functions to encode arbitrary data structures as sequences of bytes, which can then be written on a file or sent over a pipe or network connection. The bytes can then be read back later, possibly in another process, and decoded back into a data structure. The format for the byte sequences is compatible across all machines for a given version of OCaml. + Warning: marshaling is currently not type-safe. The type of marshaled data is not transmitted along the value of the data, making it impossible to check that the data read back possesses the type expected by the context. In particular, the result type of the `Marshal.from_*` functions is given as `'a`, but this is misleading: the returned OCaml value does not possess type `'a` for all `'a`; it has one, unique type which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax: + - `(Marshal.from_channel chan : type)`. Anything can happen at run-time if the object in the file does not belong to the given type. Values of extensible variant types, for example exceptions (of extensible type `exn`), returned by the unmarshaller should not be pattern-matched over through `match ... with` or `try ... with`, because unmarshalling does not preserve the information required for matching their constructors. Structural equalities with other extensible variant values does not work either. Most other uses such as Printexc.to\_string, will still work as expected. + The representation of marshaled values is not human-readable, and uses bytes that are not printable characters. Therefore, input and output channels used in conjunction with `Marshal.to_channel` and `Marshal.from_channel` must be opened in binary mode, using e.g. `open_out_bin` or `open_in_bin`; channels opened in text mode will cause unmarshaling errors on platforms where text channels behave differently than binary channels, e.g. Windows. + ``` type extern_flags = ``` @@ -12,67 +19,88 @@ type extern_flags = | No_sharing ``` Don't preserve sharing + ``` | Closures ``` Send function closures + ``` | Compat_32 ``` Ensure 32-bit compatibility + ``` ``` The flags to the `Marshal.to_*` functions below. + ``` val to_channel : out_channel -> 'a -> extern_flags list -> unit ``` `Marshal.to_channel chan v flags` writes the representation of `v` on channel `chan`. The `flags` argument is a possibly empty list of flags that governs the marshaling behavior with respect to sharing, functional values, and compatibility between 32- and 64-bit platforms. + If `flags` does not contain `Marshal.No_sharing`, circularities and sharing inside the value `v` are detected and preserved in the sequence of bytes produced. In particular, this guarantees that marshaling always terminates. Sharing between values marshaled by successive calls to `Marshal.to_channel` is neither detected nor preserved, though. If `flags` contains `Marshal.No_sharing`, sharing is ignored. This results in faster marshaling if `v` contains no shared substructures, but may cause slower marshaling and larger byte representations if `v` actually contains sharing, or even non-termination if `v` contains cycles. + If `flags` does not contain `Marshal.Closures`, marshaling fails when it encounters a functional value inside `v`: only 'pure' data structures, containing neither functions nor objects, can safely be transmitted between different programs. If `flags` contains `Marshal.Closures`, functional values will be marshaled as a the position in the code of the program together with the values corresponding to the free variables captured in the closure. In this case, the output of marshaling can only be read back in processes that run exactly the same program, with exactly the same compiled code. (This is checked at un-marshaling time, using an MD5 digest of the code transmitted along with the code position.) + The exact definition of which free variables are captured in a closure is not specified and can vary between bytecode and native code (and according to optimization flags). In particular, a function value accessing a global reference may or may not include the reference in its closure. If it does, unmarshaling the corresponding closure will create a new reference, different from the global one. + If `flags` contains `Marshal.Compat_32`, marshaling fails when it encounters an integer value outside the range `-2``30`, `2``30``-1` of integers that are representable on a 32-bit platform. This ensures that marshaled data generated on a 64-bit platform can be safely read back on a 32-bit platform. If `flags` does not contain `Marshal.Compat_32`, integer values outside the range `-2``30`, `2``30``-1` are marshaled, and can be read back on a 64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit platform. The `Mashal.Compat_32` flag only matters when marshaling is performed on a 64-bit platform; it has no effect if marshaling is performed on a 32-bit platform. + raises [`Failure`](./Stdlib.md#exception-Failure) if chan is not in binary mode. ``` val to_bytes : 'a -> extern_flags list -> bytes ``` `Marshal.to_bytes v flags` returns a byte sequence containing the representation of `v`. The `flags` argument has the same meaning as for [`Marshal.to_channel`](./#val-to_channel). + since 4.02 ``` val to_string : 'a -> extern_flags list -> string ``` Same as `to_bytes` but return the result as a string instead of a byte sequence. + ``` val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int ``` `Marshal.to_buffer buff ofs len v flags` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. It returns the number of bytes actually written to the sequence. If the byte representation of `v` does not fit in `len` characters, the exception `Failure` is raised. + ``` val from_channel : in_channel -> 'a ``` `Marshal.from_channel chan` reads from channel `chan` the byte representation of a structured value, as produced by one of the `Marshal.to_*` functions, and reconstructs and returns the corresponding value. + raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if chan is already at the end of the file. raises [`Failure`](./Stdlib.md#exception-Failure) if the end of the file is reached during unmarshalling itself or if chan is not in binary mode. ``` val from_bytes : bytes -> int -> 'a ``` `Marshal.from_bytes buff ofs` unmarshals a structured value like [`Marshal.from_channel`](./#val-from_channel) does, except that the byte representation is not read from a channel, but taken from the byte sequence `buff`, starting at position `ofs`. The byte sequence is not mutated. + since 4.02 ``` val from_string : string -> int -> 'a ``` Same as `from_bytes` but take a string as argument instead of a byte sequence. + ``` val header_size : int ``` The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header. [`Marshal.header_size`](./#val-header_size) is the size, in bytes, of the header. [`Marshal.data_size`](./#val-data_size)` buff ofs` is the size, in bytes, of the data part, assuming a valid header is stored in `buff` starting at position `ofs`. Finally, [`Marshal.total_size`](./#val-total_size) `buff ofs` is the total size, in bytes, of the marshaled value. Both [`Marshal.data_size`](./#val-data_size) and [`Marshal.total_size`](./#val-total_size) raise `Failure` if `buff`, `ofs` does not contain a valid header. + To read the byte representation of a marshaled value into a byte sequence, the program needs to read first [`Marshal.header_size`](./#val-header_size) bytes into the sequence, then determine the length of the remainder of the representation using [`Marshal.data_size`](./#val-data_size), make sure the sequence is large enough to hold the remaining data, then read it, and finally call [`Marshal.from_bytes`](./#val-from_bytes) to unmarshal the value. + ``` val data_size : bytes -> int -> int ``` See [`Marshal.header_size`](./#val-header_size). + ``` val total_size : bytes -> int -> int ``` See [`Marshal.header_size`](./#val-header_size). + + ## Marshal and domain safety -Care must be taken when marshaling a mutable value that may be modified by a different domain. Mutating a value that is being marshaled (i.e., turned into a sequence of bytes) is a programming error and might result in surprising values (when unmarshaling) due to tearing, since marshaling involves byte-per-byte copy. \ No newline at end of file + +Care must be taken when marshaling a mutable value that may be modified by a different domain. Mutating a value that is being marshaled (i.e., turned into a sequence of bytes) is a programming error and might result in surprising values (when unmarshaling) due to tearing, since marshaling involves byte-per-byte copy. diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md index 492b57f0f..80efdc53c 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md @@ -1,16 +1,21 @@ + # Parameter `Make.H` + ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val hash : t -> int ``` A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + - (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) - (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly - (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md index cd745f1cb..3743681ec 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md @@ -1,10 +1,17 @@ + # Module `Hashtbl.Make` + Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + + ## Parameters + ``` module H : HashedType ``` + ## Signature + ``` type key = H.t ``` diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md index e0b262332..d47afa082 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md @@ -1,13 +1,17 @@ + # Parameter `MakeSeeded.H` + ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val seeded_hash : int -> t -> int ``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md index 39a9f6885..3fe6e44f2 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md @@ -1,11 +1,18 @@ + # Module `Hashtbl.MakeSeeded` + Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-MoreLabels-Hashtbl.md#val-randomize)). + since 4.00 + ## Parameters + ``` module H : SeededHashedType ``` + ## Signature + ``` type key = H.t ``` diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md index 0a6c34cdd..b8aa185ce 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md @@ -1,17 +1,23 @@ + # Module type `Hashtbl.HashedType` + The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val hash : t -> int ``` A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + - (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) - (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly - (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md index 772d73ee6..9843ac29b 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md @@ -1,5 +1,8 @@ + # Module type `Hashtbl.S` + The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + ``` type key ``` diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md index 3cdf7fe07..09e30086f 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md @@ -1,15 +1,20 @@ + # Module type `Hashtbl.SeededHashedType` + The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + since 4.00 ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val seeded_hash : int -> t -> int ``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. \ No newline at end of file +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md index 044f1bf40..909c707c6 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md @@ -1,5 +1,8 @@ + # Module type `Hashtbl.SeededS` + The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + since 4.00 ``` type key diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md b/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md index e8a2e3f9d..9a4b5177e 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md +++ b/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md @@ -1,77 +1,111 @@ + # Module `MoreLabels.Hashtbl` + Hash tables and hash functions. + Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-MoreLabels-Map.md). + The functors [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. + **Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. + The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. + See [the examples section](./#examples). + **Unsynchronized accesses** + Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ## Generic interface + ``` type (!'a, !'b) t = ('a, 'b) Hashtbl.t ``` The type of hash tables from type `'a` to type `'b`. + ``` val create : ?random:bool -> int -> ('a, 'b) t ``` `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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. + A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. + 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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. + before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. ``` val clear : ('a, 'b) t -> unit ``` Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. + ``` val reset : ('a, 'b) t -> unit ``` Empty a hash table and shrink the size of the bucket table to its initial size. + since 4.00 ``` val copy : ('a, 'b) t -> ('a, 'b) t ``` Return a copy of the given hashtable. + ``` val add : ('a, 'b) t -> key:'a -> data:'b -> unit ``` `Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`. + **Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) + If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). + ``` val find : ('a, 'b) t -> 'a -> 'b ``` `Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. + ``` val find_opt : ('a, 'b) t -> 'a -> 'b option ``` `Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. + since 4.05 ``` val find_all : ('a, 'b) t -> 'a -> 'b list ``` `Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. + ``` val mem : ('a, 'b) t -> 'a -> bool ``` `Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. + ``` val remove : ('a, 'b) t -> 'a -> unit ``` `Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. + ``` val replace : ('a, 'b) t -> key:'a -> data:'b -> unit ``` `Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. + ``` val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit ``` `Hashtbl.iter ~f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. + The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + The behavior is not specified if the hash table is modified by `f` during the iteration. + ``` val filter_map_inplace : f:(key:'a -> data:'b -> 'b option) -> @@ -79,7 +113,9 @@ val filter_map_inplace : unit ``` `Hashtbl.filter_map_inplace ~f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. + Other comments for [`iter`](./#val-iter) apply as well. + since 4.03 ``` val fold : @@ -89,42 +125,57 @@ val fold : 'acc ``` `Hashtbl.fold ~f tbl ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. + The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + The behavior is not specified if the hash table is modified by `f` during the iteration. + ``` val length : ('a, 'b) t -> int ``` `Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. + ``` val randomize : unit -> unit ``` After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. + It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. + Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. + since 4.00 ``` val is_randomized : unit -> bool ``` Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. + since 4.03 ``` val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t ``` Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. + [`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. + since 4.12 ``` type statistics = Hashtbl.statistics = { ``` `num_bindings : int;` Number of bindings present in the table. Same value as returned by [`length`](./#val-length). + `num_buckets : int;` Number of buckets in the table. + `max_bucket_length : int;` Maximal number of bindings per bucket. + `bucket_histogram : int array;` Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. + ``` } ``` @@ -133,42 +184,56 @@ since 4.00 val stats : ('a, 'b) t -> statistics ``` `Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. + since 4.00 + ## Hash tables and Sequences + ``` val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t ``` Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. + The behavior is not specified if the hash table is modified during the iteration. + since 4.07 ``` val to_seq_keys : ('a, _) t -> 'a Seq.t ``` Same as `Seq.map fst (to_seq m)` + since 4.07 ``` val to_seq_values : (_, 'b) t -> 'b Seq.t ``` Same as `Seq.map snd (to_seq m)` + since 4.07 ``` val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit ``` Add the given bindings to the table, using [`add`](./#val-add) + since 4.07 ``` val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit ``` Add the given bindings to the table, using [`replace`](./#val-replace) + since 4.07 ``` val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t ``` Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. + since 4.07 + ## Functorial interface + The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. + For instance, one might want to specialize a table for integer keys: + ```ocaml module IntHash = struct @@ -183,56 +248,74 @@ For instance, one might want to specialize a table for integer keys: IntHashtbl.add h 12 "hello" ``` This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. + Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. + ``` module type HashedType = sig ... end ``` The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + ``` module type S = sig ... end ``` The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + ``` module Make (H : HashedType) : S with type key = H.t and type 'a t = 'a Hashtbl.Make(H).t ``` Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + ``` module type SeededHashedType = sig ... end ``` The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + ``` module type SeededS = sig ... end ``` The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + ``` module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t and type 'a t = 'a Hashtbl.MakeSeeded(H).t ``` Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). + + ## The polymorphic hash functions + ``` val hash : 'a -> int ``` `Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. + ``` val seeded_hash : int -> 'a -> int ``` A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. + since 4.00 ``` val hash_param : int -> int -> 'a -> int ``` `Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. + ``` val seeded_hash_param : int -> int -> int -> 'a -> int ``` A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. + since 4.00 + ## Examples + + ### Basic Example + ```ocaml (* 0...99 *) let seq = Seq.ints 0 |> Seq.take 100 @@ -262,9 +345,13 @@ since 4.00 # Hashtbl.length tbl - : int = 101 ``` + ### Counting Elements + Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. + Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. + ```ocaml # module Char_tbl = Hashtbl.Make(struct type t = char diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md index 6fcf99036..d02ffc06f 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md +++ b/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md @@ -1,9 +1,12 @@ + # Parameter `Make.Ord` + ``` type t ``` The type of the map keys. + ``` val compare : t -> t -> int ``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-Make.md b/docs/api/melange/Stdlib-MoreLabels-Map-Make.md index d056acc17..b876ef70d 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Map-Make.md +++ b/docs/api/melange/Stdlib-MoreLabels-Map-Make.md @@ -1,47 +1,64 @@ + # Module `Map.Make` + Functor building an implementation of the map structure given a totally ordered type. + + ## Parameters + ``` module Ord : OrderedType ``` + ## Signature + + ## Maps + ``` type key = Ord.t ``` The type of the map keys. + ``` type 'a t = 'a Map.Make(Ord).t ``` The type of maps from type `key` to type `'a`. + ``` val empty : 'a t ``` The empty map. + ``` val add : key:key -> data:'a -> 'a t -> 'a t ``` `add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + before 4.03 Physical equality was not ensured. ``` val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t ``` `add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + since 5.1 ``` val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t ``` `update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + since 4.06 ``` val singleton : key -> 'a -> 'a t ``` `singleton x y` returns the one-element map that contains a binding `y` for `x`. + since 3.12 ``` val remove : key -> 'a t -> 'a t ``` `remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + before 4.03 Physical equality was not ensured. ``` val merge : @@ -51,11 +68,13 @@ val merge : 'c t ``` `merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + since 3.12 ``` val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t ``` `union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + - `f' _key None None = None` - `f' _key (Some v) None = Some v` - `f' _key None (Some v) = Some v` @@ -65,182 +84,232 @@ since 4.03 val cardinal : 'a t -> int ``` Return the number of bindings of a map. + since 3.12 + ## Bindings + ``` val bindings : 'a t -> (key * 'a) list ``` Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). + since 3.12 ``` val min_binding : 'a t -> key * 'a ``` Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + since 3.12 ``` val min_binding_opt : 'a t -> (key * 'a) option ``` Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + since 4.05 ``` val max_binding : 'a t -> key * 'a ``` Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + since 3.12 ``` val max_binding_opt : 'a t -> (key * 'a) option ``` Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + since 4.05 ``` val choose : 'a t -> key * 'a ``` Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 3.12 ``` val choose_opt : 'a t -> (key * 'a) option ``` Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 4.05 + ## Searching + ``` val find : key -> 'a t -> 'a ``` `find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + ``` val find_opt : key -> 'a t -> 'a option ``` `find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + since 4.05 ``` val find_first : f:(key -> bool) -> 'a t -> key * 'a ``` `find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + since 4.05 ``` val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option ``` `find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 ``` val find_last : f:(key -> bool) -> 'a t -> key * 'a ``` `find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + since 4.05 ``` val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option ``` `find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 + ## Traversing + ``` val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit ``` `iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc ``` `fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + ## Transforming + ``` val map : f:('a -> 'b) -> 'a t -> 'b t ``` `map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t ``` Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + ``` val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t ``` `filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + since 3.12 before 4.03 Physical equality was not ensured. ``` val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t ``` `filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + - if `f k v` is `None` then `k` is not in the result, - if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. For example, the following function on maps whose values are lists + ```ocaml filter_map (fun _k li -> match li with [] -> None | _::tl -> Some tl) m ``` drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + since 4.11 ``` val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t ``` `partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + since 3.12 ``` val split : key -> 'a t -> 'a t * 'a option * 'a t ``` `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + since 3.12 + ## Predicates and comparisons + ``` val is_empty : 'a t -> bool ``` Test whether a map is empty or not. + ``` val mem : key -> 'a t -> bool ``` `mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + ``` val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool ``` `equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + ``` val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int ``` Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + ``` val for_all : f:(key -> 'a -> bool) -> 'a t -> bool ``` `for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. + since 3.12 ``` val exists : f:(key -> 'a -> bool) -> 'a t -> bool ``` `exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. + since 3.12 + ## Converting + ``` val to_list : 'a t -> (key * 'a) list ``` `to_list m` is [`bindings`](./#val-bindings)` m`. + since 5.1 ``` val of_list : (key * 'a) list -> 'a t ``` `of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + since 5.1 ``` val to_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in ascending order of keys + since 4.07 ``` val to_rev_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in descending order of keys + since 4.12 ``` val to_seq_from : key -> 'a t -> (key * 'a) Seq.t ``` `to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + since 4.07 ``` val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t ``` Add the given bindings to the map, in order. + since 4.07 ``` val of_seq : (key * 'a) Seq.t -> 'a t ``` Build a map from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md index c8268b5ae..6858e0bdf 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md +++ b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md @@ -1,10 +1,14 @@ + # Module type `Map.OrderedType` + Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + ``` type t ``` The type of the map keys. + ``` val compare : t -> t -> int ``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md index 2444c85f0..83ac73341 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md +++ b/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md @@ -1,42 +1,55 @@ + # Module type `Map.S` + Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + + ## Maps + ``` type key ``` The type of the map keys. + ``` type !+'a t ``` The type of maps from type `key` to type `'a`. + ``` val empty : 'a t ``` The empty map. + ``` val add : key:key -> data:'a -> 'a t -> 'a t ``` `add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + before 4.03 Physical equality was not ensured. ``` val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t ``` `add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + since 5.1 ``` val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t ``` `update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + since 4.06 ``` val singleton : key -> 'a -> 'a t ``` `singleton x y` returns the one-element map that contains a binding `y` for `x`. + since 3.12 ``` val remove : key -> 'a t -> 'a t ``` `remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + before 4.03 Physical equality was not ensured. ``` val merge : @@ -46,11 +59,13 @@ val merge : 'c t ``` `merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + since 3.12 ``` val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t ``` `union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + - `f' _key None None = None` - `f' _key (Some v) None = Some v` - `f' _key None (Some v) = Some v` @@ -60,182 +75,232 @@ since 4.03 val cardinal : 'a t -> int ``` Return the number of bindings of a map. + since 3.12 + ## Bindings + ``` val bindings : 'a t -> (key * 'a) list ``` Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-MoreLabels-Map-Make.md). + since 3.12 ``` val min_binding : 'a t -> key * 'a ``` Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + since 3.12 ``` val min_binding_opt : 'a t -> (key * 'a) option ``` Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + since 4.05 ``` val max_binding : 'a t -> key * 'a ``` Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + since 3.12 ``` val max_binding_opt : 'a t -> (key * 'a) option ``` Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + since 4.05 ``` val choose : 'a t -> key * 'a ``` Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 3.12 ``` val choose_opt : 'a t -> (key * 'a) option ``` Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + since 4.05 + ## Searching + ``` val find : key -> 'a t -> 'a ``` `find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + ``` val find_opt : key -> 'a t -> 'a option ``` `find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + since 4.05 ``` val find_first : f:(key -> bool) -> 'a t -> key * 'a ``` `find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + since 4.05 ``` val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option ``` `find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 ``` val find_last : f:(key -> bool) -> 'a t -> key * 'a ``` `find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + since 4.05 ``` val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option ``` `find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + since 4.05 + ## Traversing + ``` val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit ``` `iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc ``` `fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + ## Transforming + ``` val map : f:('a -> 'b) -> 'a t -> 'b t ``` `map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + ``` val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t ``` Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + ``` val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t ``` `filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + since 3.12 before 4.03 Physical equality was not ensured. ``` val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t ``` `filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + - if `f k v` is `None` then `k` is not in the result, - if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. For example, the following function on maps whose values are lists + ```ocaml filter_map (fun _k li -> match li with [] -> None | _::tl -> Some tl) m ``` drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + since 4.11 ``` val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t ``` `partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + since 3.12 ``` val split : key -> 'a t -> 'a t * 'a option * 'a t ``` `split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + since 3.12 + ## Predicates and comparisons + ``` val is_empty : 'a t -> bool ``` Test whether a map is empty or not. + ``` val mem : key -> 'a t -> bool ``` `mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + ``` val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool ``` `equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + ``` val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int ``` Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + ``` val for_all : f:(key -> 'a -> bool) -> 'a t -> bool ``` `for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. + since 3.12 ``` val exists : f:(key -> 'a -> bool) -> 'a t -> bool ``` `exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. + since 3.12 + ## Converting + ``` val to_list : 'a t -> (key * 'a) list ``` `to_list m` is [`bindings`](./#val-bindings)` m`. + since 5.1 ``` val of_list : (key * 'a) list -> 'a t ``` `of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + since 5.1 ``` val to_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in ascending order of keys + since 4.07 ``` val to_rev_seq : 'a t -> (key * 'a) Seq.t ``` Iterate on the whole map, in descending order of keys + since 4.12 ``` val to_seq_from : key -> 'a t -> (key * 'a) Seq.t ``` `to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + since 4.07 ``` val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t ``` Add the given bindings to the map, in order. + since 4.07 ``` val of_seq : (key * 'a) Seq.t -> 'a t ``` Build a map from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Map.md b/docs/api/melange/Stdlib-MoreLabels-Map.md index c331af125..d7033ed13 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Map.md +++ b/docs/api/melange/Stdlib-MoreLabels-Map.md @@ -1,7 +1,12 @@ + # Module `MoreLabels.Map` + Association tables over ordered types. + This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + For instance: + ```ocaml module IntPairs = struct @@ -17,17 +22,20 @@ For instance: let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world") ``` This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. + ``` module type OrderedType = sig ... end ``` Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + ``` module type S = sig ... end ``` Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + ``` module Make (Ord : OrderedType) : S with type key = Ord.t and type 'a t = 'a Map.Make(Ord).t ``` -Functor building an implementation of the map structure given a totally ordered type. \ No newline at end of file +Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md index bce17bb85..3abdead73 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md +++ b/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md @@ -1,9 +1,12 @@ + # Parameter `Make.Ord` + ``` type t ``` The type of the set elements. + ``` val compare : t -> t -> int ``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-Make.md b/docs/api/melange/Stdlib-MoreLabels-Set-Make.md index 7a13ff86d..df47ebd04 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Set-Make.md +++ b/docs/api/melange/Stdlib-MoreLabels-Set-Make.md @@ -1,225 +1,297 @@ + # Module `Set.Make` + Functor building an implementation of the set structure given a totally ordered type. + + ## Parameters + ``` module Ord : OrderedType ``` + ## Signature + + ## Sets + ``` type elt = Ord.t ``` The type of the set elements. + ``` type t = Set.Make(Ord).t ``` The type of sets. + ``` val empty : t ``` The empty set. + ``` val add : elt -> t -> t ``` `add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val singleton : elt -> t ``` `singleton x` returns the one-element set containing only `x`. + ``` val remove : elt -> t -> t ``` `remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val union : t -> t -> t ``` Set union. + ``` val inter : t -> t -> t ``` Set intersection. + ``` val disjoint : t -> t -> bool ``` Test if two sets are disjoint. + since 4.08 ``` val diff : t -> t -> t ``` Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + ``` val cardinal : t -> int ``` Return the number of elements of a set. + + ## Elements + ``` val elements : t -> elt list ``` Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). + ``` val min_elt : t -> elt ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + ``` val min_elt_opt : t -> elt option ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + since 4.05 ``` val max_elt : t -> elt ``` Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + ``` val max_elt_opt : t -> elt option ``` Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + since 4.05 ``` val choose : t -> elt ``` Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + ``` val choose_opt : t -> elt option ``` Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + since 4.05 + ## Searching + ``` val find : elt -> t -> elt ``` `find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + since 4.01 ``` val find_opt : elt -> t -> elt option ``` `find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + since 4.05 ``` val find_first : f:(elt -> bool) -> t -> elt ``` `find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + since 4.05 ``` val find_first_opt : f:(elt -> bool) -> t -> elt option ``` `find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 ``` val find_last : f:(elt -> bool) -> t -> elt ``` `find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + since 4.05 ``` val find_last_opt : f:(elt -> bool) -> t -> elt option ``` `find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 + ## Traversing + ``` val iter : f:(elt -> unit) -> t -> unit ``` `iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + ``` val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc ``` `fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + ## Transforming + ``` val map : f:(elt -> elt) -> t -> t ``` `map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + since 4.04 ``` val filter : f:(elt -> bool) -> t -> t ``` `filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val filter_map : f:(elt -> elt option) -> t -> t ``` `filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + For example, + ```ocaml filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s ``` is the set of halves of the even elements of `s`. + If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + since 4.11 ``` val partition : f:(elt -> bool) -> t -> t * t ``` `partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + ``` val split : elt -> t -> t * bool * t ``` `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + ## Predicates and comparisons + ``` val is_empty : t -> bool ``` Test whether a set is empty or not. + ``` val mem : elt -> t -> bool ``` `mem x s` tests whether `x` belongs to the set `s`. + ``` val equal : t -> t -> bool ``` `equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + ``` val compare : t -> t -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. + ``` val subset : t -> t -> bool ``` `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + ``` val for_all : f:(elt -> bool) -> t -> bool ``` `for_all ~f s` checks if all elements of the set satisfy the predicate `f`. + ``` val exists : f:(elt -> bool) -> t -> bool ``` `exists ~f s` checks if at least one element of the set satisfies the predicate `f`. + + ## Converting + ``` val to_list : t -> elt list ``` `to_list s` is [`elements`](./#val-elements)` s`. + since 5.1 ``` val of_list : elt list -> t ``` `of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + since 4.02 ``` val to_seq_from : elt -> t -> elt Seq.t ``` `to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + since 4.07 ``` val to_seq : t -> elt Seq.t ``` Iterate on the whole set, in ascending order + since 4.07 ``` val to_rev_seq : t -> elt Seq.t ``` Iterate on the whole set, in descending order + since 4.12 ``` val add_seq : elt Seq.t -> t -> t ``` Add the given elements to the set, in order. + since 4.07 ``` val of_seq : elt Seq.t -> t ``` Build a set from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md index 7e93c469f..4f07540de 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md +++ b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md @@ -1,10 +1,14 @@ + # Module type `Set.OrderedType` + Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + ``` type t ``` The type of the set elements. + ``` val compare : t -> t -> int ``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md index 1de8581e3..853191d56 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md +++ b/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md @@ -1,220 +1,288 @@ + # Module type `Set.S` + Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + + ## Sets + ``` type elt ``` The type of the set elements. + ``` type t ``` The type of sets. + ``` val empty : t ``` The empty set. + ``` val add : elt -> t -> t ``` `add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val singleton : elt -> t ``` `singleton x` returns the one-element set containing only `x`. + ``` val remove : elt -> t -> t ``` `remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val union : t -> t -> t ``` Set union. + ``` val inter : t -> t -> t ``` Set intersection. + ``` val disjoint : t -> t -> bool ``` Test if two sets are disjoint. + since 4.08 ``` val diff : t -> t -> t ``` Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + ``` val cardinal : t -> int ``` Return the number of elements of a set. + + ## Elements + ``` val elements : t -> elt list ``` Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-MoreLabels-Set-Make.md). + ``` val min_elt : t -> elt ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + ``` val min_elt_opt : t -> elt option ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + since 4.05 ``` val max_elt : t -> elt ``` Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + ``` val max_elt_opt : t -> elt option ``` Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + since 4.05 ``` val choose : t -> elt ``` Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + ``` val choose_opt : t -> elt option ``` Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + since 4.05 + ## Searching + ``` val find : elt -> t -> elt ``` `find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + since 4.01 ``` val find_opt : elt -> t -> elt option ``` `find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + since 4.05 ``` val find_first : f:(elt -> bool) -> t -> elt ``` `find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + since 4.05 ``` val find_first_opt : f:(elt -> bool) -> t -> elt option ``` `find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 ``` val find_last : f:(elt -> bool) -> t -> elt ``` `find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + since 4.05 ``` val find_last_opt : f:(elt -> bool) -> t -> elt option ``` `find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 + ## Traversing + ``` val iter : f:(elt -> unit) -> t -> unit ``` `iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + ``` val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc ``` `fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + ## Transforming + ``` val map : f:(elt -> elt) -> t -> t ``` `map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + since 4.04 ``` val filter : f:(elt -> bool) -> t -> t ``` `filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val filter_map : f:(elt -> elt option) -> t -> t ``` `filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + For example, + ```ocaml filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s ``` is the set of halves of the even elements of `s`. + If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + since 4.11 ``` val partition : f:(elt -> bool) -> t -> t * t ``` `partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + ``` val split : elt -> t -> t * bool * t ``` `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + ## Predicates and comparisons + ``` val is_empty : t -> bool ``` Test whether a set is empty or not. + ``` val mem : elt -> t -> bool ``` `mem x s` tests whether `x` belongs to the set `s`. + ``` val equal : t -> t -> bool ``` `equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + ``` val compare : t -> t -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. + ``` val subset : t -> t -> bool ``` `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + ``` val for_all : f:(elt -> bool) -> t -> bool ``` `for_all ~f s` checks if all elements of the set satisfy the predicate `f`. + ``` val exists : f:(elt -> bool) -> t -> bool ``` `exists ~f s` checks if at least one element of the set satisfies the predicate `f`. + + ## Converting + ``` val to_list : t -> elt list ``` `to_list s` is [`elements`](./#val-elements)` s`. + since 5.1 ``` val of_list : elt list -> t ``` `of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + since 4.02 ``` val to_seq_from : elt -> t -> elt Seq.t ``` `to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + since 4.07 ``` val to_seq : t -> elt Seq.t ``` Iterate on the whole set, in ascending order + since 4.07 ``` val to_rev_seq : t -> elt Seq.t ``` Iterate on the whole set, in descending order + since 4.12 ``` val add_seq : elt Seq.t -> t -> t ``` Add the given elements to the set, in order. + since 4.07 ``` val of_seq : elt Seq.t -> t ``` Build a set from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-MoreLabels-Set.md b/docs/api/melange/Stdlib-MoreLabels-Set.md index 5a9665c53..489cab218 100644 --- a/docs/api/melange/Stdlib-MoreLabels-Set.md +++ b/docs/api/melange/Stdlib-MoreLabels-Set.md @@ -1,7 +1,12 @@ + # Module `MoreLabels.Set` + Sets over ordered types. + This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. + The [`Make`](./Stdlib-MoreLabels-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: + ```ocaml module IntPairs = struct @@ -17,17 +22,20 @@ The [`Make`](./Stdlib-MoreLabels-Set-Make.md) functor constructs implementations let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) ``` This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. + ``` module type OrderedType = sig ... end ``` Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + ``` module type S = sig ... end ``` Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + ``` module Make (Ord : OrderedType) : S with type elt = Ord.t and type t = Set.Make(Ord).t ``` -Functor building an implementation of the set structure given a totally ordered type. \ No newline at end of file +Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/melange/Stdlib-MoreLabels.md b/docs/api/melange/Stdlib-MoreLabels.md index 8037ad8cb..3dda53b24 100644 --- a/docs/api/melange/Stdlib-MoreLabels.md +++ b/docs/api/melange/Stdlib-MoreLabels.md @@ -1,8 +1,14 @@ + # Module `Stdlib.MoreLabels` + Extra labeled libraries. + This meta-module provides labelized versions of the [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md) and [`Set`](./Stdlib-MoreLabels-Set.md) modules. + This module is intended to be used through `open MoreLabels` which replaces [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md), and [`Set`](./Stdlib-MoreLabels-Set.md) with their labeled counterparts. + For example: + ```ocaml open MoreLabels @@ -12,11 +18,13 @@ For example: module Hashtbl : sig ... end ``` Hash tables and hash functions. + ``` module Map : sig ... end ``` Association tables over ordered types. + ``` module Set : sig ... end ``` -Sets over ordered types. \ No newline at end of file +Sets over ordered types. diff --git a/docs/api/melange/Stdlib-Mutex.md b/docs/api/melange/Stdlib-Mutex.md index 6f93f481d..7e8180f6c 100644 --- a/docs/api/melange/Stdlib-Mutex.md +++ b/docs/api/melange/Stdlib-Mutex.md @@ -1,6 +1,10 @@ + # Module `Stdlib.Mutex` + Locks for mutual exclusion. + Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if `m` is the mutex associated with the data structure `D`): + ```ocaml Mutex.lock m; (* Critical section that operates over D *); @@ -10,29 +14,36 @@ Mutexes (mutual-exclusion locks) are used to implement critical sections and pro type t ``` The type of mutexes. + ``` val create : unit -> t ``` Return a new mutex. + ``` val lock : t -> unit ``` Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex. + raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is already locked by the thread calling Mutex.lock. before 4.12 Sys\_error was not raised for recursive locking (platform-dependent behaviour) ``` val try_lock : t -> bool ``` Same as [`Mutex.lock`](./#val-lock), but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. If the mutex is unlocked, lock it and return `true`. + ``` val unlock : t -> unit ``` Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. The mutex must have been previously locked by the thread that calls [`Mutex.unlock`](./#val-unlock). + raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is unlocked or was locked by another thread. before 4.12 Sys\_error was not raised when unlocking an unlocked mutex or when unlocking a mutex from a different thread. ``` val protect : t -> (unit -> 'a) -> 'a ``` `protect mutex f` runs `f()` in a critical section where `mutex` is locked (using [`lock`](./#val-lock)); it then takes care of releasing `mutex`, whether `f()` returned a value or raised an exception. + The unlocking operation is guaranteed to always takes place, even in the event an asynchronous exception (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)) is raised in some signal handler. + since 5.1 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Obj-Ephemeron.md b/docs/api/melange/Stdlib-Obj-Ephemeron.md index 80b05826d..4020b901b 100644 --- a/docs/api/melange/Stdlib-Obj-Ephemeron.md +++ b/docs/api/melange/Stdlib-Obj-Ephemeron.md @@ -1,21 +1,28 @@ + # Module `Obj.Ephemeron` + Ephemeron with arbitrary arity and untyped + ``` type obj_t = t ``` alias for [`Obj.t`](./Stdlib-Obj.md#type-t) + ``` type t ``` an ephemeron cf [`Ephemeron`](#) + ``` val create : int -> t ``` `create n` returns an ephemeron with `n` keys. All the keys and the data are initially empty. The argument `n` must be between zero and [`max_ephe_length`](./#val-max_ephe_length) (limits included). + ``` val length : t -> int ``` return the number of keys + ``` val get_key : t -> int -> obj_t option ``` @@ -55,4 +62,4 @@ val blit_data : t -> t -> unit ``` val max_ephe_length : int ``` -Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain \ No newline at end of file +Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain diff --git a/docs/api/melange/Stdlib-Obj-Extension_constructor.md b/docs/api/melange/Stdlib-Obj-Extension_constructor.md index a008cdace..c08771eb4 100644 --- a/docs/api/melange/Stdlib-Obj-Extension_constructor.md +++ b/docs/api/melange/Stdlib-Obj-Extension_constructor.md @@ -1,4 +1,6 @@ + # Module `Obj.Extension_constructor` + ``` type t = extension_constructor ``` diff --git a/docs/api/melange/Stdlib-Obj.md b/docs/api/melange/Stdlib-Obj.md index c2eeffd0f..2e619aff6 100644 --- a/docs/api/melange/Stdlib-Obj.md +++ b/docs/api/melange/Stdlib-Obj.md @@ -1,6 +1,10 @@ + # Module `Stdlib.Obj` + Operations on internal representations of values. + Not for the casual user. + ``` type t ``` @@ -32,6 +36,7 @@ val size : t -> int val reachable_words : t -> int ``` Computes the total size (in words, including the headers) of all heap blocks accessible from the argument. Statically allocated blocks are included. + since 4.04 ``` val field : t -> int -> t @@ -40,9 +45,13 @@ val field : t -> int -> t val set_field : t -> int -> t -> unit ``` When using flambda: + `set_field` MUST NOT be called on immutable blocks. (Blocks allocated in C stubs, or with `new_block` below, are always considered mutable.) + The same goes for `set_double_field`. + For experts only: `set_field` et al can be made safe by first wrapping the block in [`Sys.opaque_identity`](./Stdlib-Sys.md#val-opaque_identity), so any information about its contents will not be propagated. + ``` val double_field : t -> int -> float ``` @@ -127,4 +136,4 @@ module Extension_constructor : sig ... end ``` module Ephemeron : sig ... end ``` -Ephemeron with arbitrary arity and untyped \ No newline at end of file +Ephemeron with arbitrary arity and untyped diff --git a/docs/api/melange/Stdlib-Oo.md b/docs/api/melange/Stdlib-Oo.md index 24f735eb0..f212cee13 100644 --- a/docs/api/melange/Stdlib-Oo.md +++ b/docs/api/melange/Stdlib-Oo.md @@ -1,11 +1,15 @@ + # Module `Stdlib.Oo` + Operations on objects + ``` val copy : < .. > as 'a -> 'a ``` `Oo.copy o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`. + alert unsynchronized\_access Unsynchronized accesses to mutable objects are a programming error. ``` val id : < .. > -> int ``` -Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures. \ No newline at end of file +Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures. diff --git a/docs/api/melange/Stdlib-Option.md b/docs/api/melange/Stdlib-Option.md index 06d5b4134..c84df4dca 100644 --- a/docs/api/melange/Stdlib-Option.md +++ b/docs/api/melange/Stdlib-Option.md @@ -1,8 +1,14 @@ + # Module `Stdlib.Option` + Option values. + Option values explicitly indicate the presence or absence of a value. + since 4.08 + ## Options + ``` type 'a t = 'a option = ``` @@ -16,70 +22,90 @@ type 'a t = 'a option = ``` The type for option values. Either `None` or a value `Some v`. + ``` val none : 'a option ``` `none` is `None`. + ``` val some : 'a -> 'a option ``` `some v` is `Some v`. + ``` val value : 'a option -> default:'a -> 'a ``` `value o ~default` is `v` if `o` is `Some v` and `default` otherwise. + ``` val get : 'a option -> 'a ``` `get o` is `v` if `o` is `Some v` and raise otherwise. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if o is None. ``` val bind : 'a option -> ('a -> 'b option) -> 'b option ``` `bind o f` is `f v` if `o` is `Some v` and `None` if `o` is `None`. + ``` val join : 'a option option -> 'a option ``` `join oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise. + ``` val map : ('a -> 'b) -> 'a option -> 'b option ``` `map f o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`. + ``` val fold : none:'a -> some:('b -> 'a) -> 'b option -> 'a ``` `fold ~none ~some o` is `none` if `o` is `None` and `some v` if `o` is `Some v`. + ``` val iter : ('a -> unit) -> 'a option -> unit ``` `iter f o` is `f v` if `o` is `Some v` and `()` otherwise. + + ## Predicates and comparisons + ``` val is_none : 'a option -> bool ``` `is_none o` is `true` if and only if `o` is `None`. + ``` val is_some : 'a option -> bool ``` `is_some o` is `true` if and only if `o` is `Some o`. + ``` val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool ``` `equal eq o0 o1` is `true` if and only if `o0` and `o1` are both `None` or if they are `Some v0` and `Some v1` and `eq v0 v1` is `true`. + ``` val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int ``` `compare cmp o0 o1` is a total order on options using `cmp` to compare values wrapped by `Some _`. `None` is smaller than `Some _` values. + + ## Converting + ``` val to_result : none:'e -> 'a option -> ('a, 'e) result ``` `to_result ~none o` is `Ok v` if `o` is `Some v` and `Error none` otherwise. + ``` val to_list : 'a option -> 'a list ``` `to_list o` is `[]` if `o` is `None` and `[v]` if `o` is `Some v`. + ``` val to_seq : 'a option -> 'a Seq.t ``` -`to_seq o` is `o` as a sequence. `None` is the empty sequence and `Some v` is the singleton sequence containing `v`. \ No newline at end of file +`to_seq o` is `o` as a sequence. `None` is the empty sequence and `Some v` is the singleton sequence containing `v`. diff --git a/docs/api/melange/Stdlib-Out_channel.md b/docs/api/melange/Stdlib-Out_channel.md index 5d27942bf..35eade38e 100644 --- a/docs/api/melange/Stdlib-Out_channel.md +++ b/docs/api/melange/Stdlib-Out_channel.md @@ -1,13 +1,21 @@ + # Module `Stdlib.Out_channel` + Output channels. + This module provides functions for working with output channels. + See [the example section](./#examples) below. + since 4.14 + ## Channels + ``` type t = out_channel ``` The type of output channel. + ``` type open_flag = open_flag = ``` @@ -15,161 +23,215 @@ type open_flag = open_flag = | Open_rdonly ``` open for reading. + ``` | Open_wronly ``` open for writing. + ``` | Open_append ``` open for appending: always write at end of file. + ``` | Open_creat ``` create the file if it does not exist. + ``` | Open_trunc ``` empty the file if it already exists. + ``` | Open_excl ``` fail if Open\_creat and the file already exists. + ``` | Open_binary ``` open in binary mode (no conversion). + ``` | Open_text ``` open in text mode (may perform conversions). + ``` | Open_nonblock ``` open in non-blocking mode. + ``` ``` Opening modes for [`open_gen`](./#val-open_gen). + ``` val stdout : t ``` The standard output for the process. + ``` val stderr : t ``` The standard error output for the process. + ``` val open_bin : string -> t ``` Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. + ``` val open_text : string -> t ``` Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). + ``` val open_gen : open_flag list -> int -> string -> t ``` `open_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. + ``` val with_open_bin : string -> (t -> 'a) -> 'a ``` `with_open_bin fn f` opens a channel `oc` on file `fn` and returns `f oc`. After `f` returns, either with a value or by raising an exception, `oc` is guaranteed to be closed. + ``` val with_open_text : string -> (t -> 'a) -> 'a ``` Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). + ``` val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a ``` Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). + ``` val close : t -> unit ``` Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except [`close`](./#val-close) and [`flush`](./#val-flush), which do nothing when applied to an already closed channel. Note that [`close`](./#val-close) may raise `Sys_error` if the operating system signals an error when flushing or closing. + ``` val close_noerr : t -> unit ``` Same as [`close`](./#val-close), but ignore all errors. + + ## Output + ``` val output_char : t -> char -> unit ``` Write the character on the given output channel. + ``` val output_byte : t -> int -> unit ``` Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. + ``` val output_string : t -> string -> unit ``` Write the string on the given output channel. + ``` val output_bytes : t -> bytes -> unit ``` Write the byte sequence on the given output channel. + + ## Advanced output + ``` val output : t -> bytes -> int -> int -> unit ``` `output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. ``` val output_substring : t -> string -> int -> int -> unit ``` Same as [`output`](./#val-output) but take a string as argument instead of a byte sequence. + + ## Flushing + ``` val flush : t -> unit ``` Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. + ``` val flush_all : unit -> unit ``` Flush all open output channels; ignore errors. + + ## Seeking + ``` val seek : t -> int64 -> unit ``` `seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. + ``` val pos : t -> int64 ``` Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). + For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + + ## Attributes + ``` val length : t -> int64 ``` Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. + ``` val set_binary_mode : t -> bool -> unit ``` `set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output. + `set_binary_mode oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. + This function has no effect under operating systems that do not distinguish between text mode and binary mode. + ``` val is_binary_mode : t -> bool ``` `is_binary_mode oc` returns whether the channel `oc` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). + since 5.2 ``` val set_buffered : t -> bool -> unit ``` `set_buffered oc true` sets the channel `oc` to *buffered* mode. In this mode, data output on `oc` will be buffered until either the internal buffer is full or the function [`flush`](./#val-flush) or [`flush_all`](./#val-flush_all) is called, at which point it will be sent to the output device. + `set_buffered oc false` sets the channel `oc` to *unbuffered* mode. In this mode, data output on `oc` will be sent to the output device immediately. + All channels are open in *buffered* mode by default. + ``` val is_buffered : t -> bool ``` `is_buffered oc` returns whether the channel `oc` is buffered (see [`set_buffered`](./#val-set_buffered)). + ``` val isatty : t -> bool ``` `isatty oc` is `true` if `oc` refers to a terminal or console window, `false` otherwise. + since 5.1 + ## Examples + Writing the contents of a file: + ```ocaml let write_file file s = Out_channel.with_open_bin file diff --git a/docs/api/melange/Stdlib-Parsing.md b/docs/api/melange/Stdlib-Parsing.md index 6f77c29ea..b95445513 100644 --- a/docs/api/melange/Stdlib-Parsing.md +++ b/docs/api/melange/Stdlib-Parsing.md @@ -1,47 +1,61 @@ + # Module `Stdlib.Parsing` + The run-time library for parsers generated by `ocamlyacc`. + ``` val symbol_start : unit -> int ``` `symbol_start` and [`Parsing.symbol_end`](./#val-symbol_end) are to be called in the action part of a grammar rule only. They return the offset of the string that matches the left-hand side of the rule: `symbol_start()` returns the offset of the first character; `symbol_end()` returns the offset after the last character. The first character in a file is at offset 0. + ``` val symbol_end : unit -> int ``` See [`Parsing.symbol_start`](./#val-symbol_start). + ``` val rhs_start : int -> int ``` Same as [`Parsing.symbol_start`](./#val-symbol_start) and [`Parsing.symbol_end`](./#val-symbol_end), but return the offset of the string matching the `n`th item on the right-hand side of the rule, where `n` is the integer parameter to `rhs_start` and `rhs_end`. `n` is 1 for the leftmost item. + ``` val rhs_end : int -> int ``` See [`Parsing.rhs_start`](./#val-rhs_start). + ``` val symbol_start_pos : unit -> Lexing.position ``` Same as `symbol_start`, but return a `position` instead of an offset. + ``` val symbol_end_pos : unit -> Lexing.position ``` Same as `symbol_end`, but return a `position` instead of an offset. + ``` val rhs_start_pos : int -> Lexing.position ``` Same as `rhs_start`, but return a `position` instead of an offset. + ``` val rhs_end_pos : int -> Lexing.position ``` Same as `rhs_end`, but return a `position` instead of an offset. + ``` val clear_parser : unit -> unit ``` Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs. + ``` exception Parse_error ``` Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery. + ``` val set_trace : bool -> bool ``` Control debugging support for `ocamlyacc`\-generated parsers. After `Parsing.set_trace true`, the pushdown automaton that executes the parsers prints a trace of its actions (reading a token, shifting a state, reducing by a rule) on standard output. `Parsing.set_trace false` turns this debugging trace off. The boolean returned is the previous state of the trace flag. + since 3.11 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Printexc-Slot.md b/docs/api/melange/Stdlib-Printexc-Slot.md index 95d9ea422..452eda49a 100644 --- a/docs/api/melange/Stdlib-Printexc-Slot.md +++ b/docs/api/melange/Stdlib-Printexc-Slot.md @@ -1,4 +1,6 @@ + # Module `Printexc.Slot` + since 4.02 ``` type t = backtrace_slot @@ -7,17 +9,21 @@ type t = backtrace_slot val is_raise : t -> bool ``` `is_raise slot` is `true` when `slot` refers to a raising point in the code, and `false` when it comes from a simple function call. + since 4.02 ``` val is_inline : t -> bool ``` `is_inline slot` is `true` when `slot` refers to a call that got inlined by the compiler, and `false` when it comes from any other context. + since 4.04 ``` val location : t -> location option ``` `location slot` returns the location information of the slot, if available, and `None` otherwise. + Some possible reasons for failing to return a location are as follow: + - the slot corresponds to a compiler-inserted raise - the slot corresponds to a part of the program that has not been compiled with debug information (`-g`) since 4.02 @@ -25,11 +31,15 @@ since 4.02 val name : t -> string option ``` `name slot` returns the name of the function or definition enclosing the location referred to by the slot. + `name slot` returns None if the name is unavailable, which may happen for the same reasons as `location` returning None. + since 4.11 ``` val format : int -> t -> string option ``` `format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`\-th element of the backtrace: the `0`\-th element is pretty-printed differently than the others. + Whole-backtrace printing functions also skip some uninformative slots; in that case, `format pos slot` returns `None`. + since 4.02 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Printexc.md b/docs/api/melange/Stdlib-Printexc.md index ca31fd509..47bfc94fe 100644 --- a/docs/api/melange/Stdlib-Printexc.md +++ b/docs/api/melange/Stdlib-Printexc.md @@ -1,75 +1,101 @@ + # Module `Stdlib.Printexc` + Facilities for printing exceptions and inspecting current call stack. + ``` type t = exn = .. ``` The type of exception values. + ``` val to_string : exn -> string ``` `Printexc.to_string e` returns a string representation of the exception `e`. + ``` val to_string_default : exn -> string ``` `Printexc.to_string_default e` returns a string representation of the exception `e`, ignoring all registered exception printers. + since 4.09 ``` val print : ('a -> 'b) -> 'a -> 'b ``` `Printexc.print fn x` applies `fn` to `x` and returns the result. If the evaluation of `fn x` raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application. + ``` val catch : ('a -> 'b) -> 'a -> 'b ``` `Printexc.catch fn x` is similar to [`Printexc.print`](./#val-print), but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as `Printexc.catch` does. Moreover, calling `Printexc.catch` makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use `Printexc.catch` in new code. + deprecated This function is no longer needed. ``` val print_backtrace : out_channel -> unit ``` `Printexc.print_backtrace oc` prints an exception backtrace on the output channel `oc`. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls. + If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one. + since 3.11 ``` val get_backtrace : unit -> string ``` `Printexc.get_backtrace ()` returns a string containing the same exception backtrace that `Printexc.print_backtrace` would print. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). + since 3.11 ``` val record_backtrace : bool -> unit ``` `Printexc.record_backtrace b` turns recording of exception backtraces on (if `b = true`) or off (if `b = false`). Initially, backtraces are not recorded, unless the `b` flag is given to the program through the `OCAMLRUNPARAM` variable. + since 3.11 ``` val backtrace_status : unit -> bool ``` `Printexc.backtrace_status()` returns `true` if exception backtraces are currently recorded, `false` if not. + since 3.11 ``` val register_printer : (exn -> string option) -> unit ``` `Printexc.register_printer fn` registers `fn` as an exception printer. The printer should return `None` or raise an exception if it does not know how to convert the passed exception, and `Some s` with `s` the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored. + When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a `Some s` value (if no such printer exists, the runtime will use a generic printer). + When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to `fn` should not use the backtrace if it has itself raised an exception before. + since 3.11.2 ``` val use_printers : exn -> string option ``` `Printexc.use_printers e` returns `None` if there are no registered printers and `Some s` with `s` the resulting string otherwise. + since 4.09 + ## Raw backtraces + ``` type raw_backtrace ``` The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below. + Converting backtraces to `backtrace_slot`s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use `raw_backtrace` to avoid or delay conversion. + Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the `backtrace_slots` function of the next section. + since 4.01 ``` type raw_backtrace_entry = private int ``` A `raw_backtrace_entry` is an element of a `raw_backtrace`. + Each `raw_backtrace_entry` is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary. + A `raw_backtrace_entry` can be converted to a usable form using `backtrace_slots_of_raw_entry` below. Note that, due to inlining, a single `raw_backtrace_entry` may convert to several `backtrace_slot`s. Since the values of a `raw_backtrace_entry` are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them. + Again due to inlining, there may be multiple distinct raw\_backtrace\_entry values that convert to equal `backtrace_slot`s. However, if two `raw_backtrace_entry`s are equal as integers, then they represent the same `backtrace_slot`s. + since 4.12 ``` val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array @@ -79,55 +105,76 @@ since 4.12 val get_raw_backtrace : unit -> raw_backtrace ``` `Printexc.get_raw_backtrace ()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). + since 4.01 ``` val print_raw_backtrace : out_channel -> raw_backtrace -> unit ``` Print a raw backtrace in the same format `Printexc.print_backtrace` uses. + since 4.01 ``` val raw_backtrace_to_string : raw_backtrace -> string ``` Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses. + since 4.01 ``` val raise_with_backtrace : exn -> raw_backtrace -> 'a ``` Reraise the exception using the given raw\_backtrace for the origin of the exception + since 4.05 + ## Current call stack + ``` val get_callstack : int -> raw_backtrace ``` `Printexc.get_callstack n` returns a description of the top of the call stack on the current program point (for the current thread), with at most `n` entries. (Note: this function is not related to exceptions at all, despite being part of the `Printexc` module.) + since 4.01 + ## Uncaught exceptions + ``` val default_uncaught_exception_handler : exn -> raw_backtrace -> unit ``` `Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output. + since 4.11 ``` val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit ``` `Printexc.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. The default handler is [`Printexc.default_uncaught_exception_handler`](./#val-default_uncaught_exception_handler). + Note that when `fn` is called all the functions registered with [`Stdlib.at_exit`](./Stdlib.md#val-at_exit) have already been called. Because of this you must make sure any output channel `fn` writes on is flushed. + Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself. + If `fn` raises an exception, both the exceptions passed to `fn` and raised by `fn` will be printed with their respective backtrace. + since 4.02 + ## Manipulation of backtrace information + These functions are used to traverse the slots of a raw backtrace and extract information from them in a programmer-friendly format. + ``` type backtrace_slot ``` The abstract type `backtrace_slot` represents a single slot of a backtrace. + since 4.02 ``` val backtrace_slots : raw_backtrace -> backtrace_slot array option ``` Returns the slots of a raw backtrace, or `None` if none of them contain useful information. + In the return array, the slot at index `0` corresponds to the most recent function call, raise, or primitive `get_backtrace` call in the trace. + Some possible reasons for returning `None` are as follow: + - none of the slots in the trace come from modules compiled with debug information (`-g`) - the program is a bytecode program that has not been linked with debug information enabled (`ocamlc -g`) since 4.02 @@ -137,7 +184,9 @@ val backtrace_slots_of_raw_entry : backtrace_slot array option ``` Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information. + Slots are returned in the same order as `backtrace_slots`: the slot at index `0` is the most recent call, raise, or primitive, and subsequent slots represent callers. + since 4.12 ``` type location = { @@ -154,32 +203,41 @@ since 5.2 } ``` The type of location information found in backtraces. `start_char` and `end_char` are positions relative to the beginning of `line_number`. `end_col` is relative to the beginning of `end_line`. + since 4.02 ``` module Slot : sig ... end ``` + ## Raw backtrace slots + ``` type raw_backtrace_slot ``` This type is used to iterate over the slots of a `raw_backtrace`. For most purposes, `backtrace_slots_of_raw_entry` is easier to use. + Like `raw_backtrace_entry`, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior). + Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example). + since 4.02 ``` val raw_backtrace_length : raw_backtrace -> int ``` `raw_backtrace_length bckt` returns the number of slots in the backtrace `bckt`. + since 4.02 ``` val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot ``` `get_raw_backtrace_slot bckt pos` returns the slot in position `pos` in the backtrace `bckt`. + since 4.02 ``` val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot ``` Extracts the user-friendly `backtrace_slot` from a low-level `raw_backtrace_slot`. + since 4.02 ``` val get_raw_backtrace_next_slot : @@ -187,7 +245,9 @@ val get_raw_backtrace_next_slot : raw_backtrace_slot option ``` `get_raw_backtrace_next_slot slot` returns the next slot inlined, if any. + Sample code to iterate over all frames (inlined and non-inlined): + ```ocaml (* Iterate over inlined frames *) let rec iter_raw_backtrace_slot f slot = @@ -203,14 +263,18 @@ Sample code to iterate over all frames (inlined and non-inlined): done ``` since 4.04 + ## Exception slots + ``` val exn_slot_id : exn -> int ``` `Printexc.exn_slot_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime). + since 4.02 ``` val exn_slot_name : exn -> string ``` `Printexc.exn_slot_name exn` returns the internal name of the constructor used to create the exception value `exn`. + since 4.02 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Printf.md b/docs/api/melange/Stdlib-Printf.md index 15da09c35..4c1d41539 100644 --- a/docs/api/melange/Stdlib-Printf.md +++ b/docs/api/melange/Stdlib-Printf.md @@ -1,14 +1,23 @@ + # Module `Stdlib.Printf` + Formatted output functions. + ``` val fprintf : out_channel -> ('a, out_channel, unit) format -> 'a ``` `fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`. + The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments. + Conversion specifications have the following form: + `% [flags] [width] [.precision] type` + In short, a conversion specification consists in the `%` character, followed by optional modifiers and a type which is made of one or two characters. + The types and their meanings are: + - `d`, `i`: convert an integer argument to signed decimal. The flag `#` adds underscores to large values for readability. - `u`, `n`, `l`, `L`, or `N`: convert an integer argument to unsigned decimal. Warning: `n`, `l`, `L`, and `N` are used for `scanf`, and should not be used for `printf`. The flag `#` adds underscores to large values for readability. - `x`: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag `#` adds a `0x` prefix to non zero values. @@ -37,41 +46,52 @@ The types and their meanings are: - `\@`: take no argument and output one `\@` character. - `,`: take no argument and output nothing: a no-op delimiter for conversion specifications. The optional `flags` are: + - `-`: left-justify the output (default is right justification). - `0`: for numerical conversions, pad with zeroes instead of spaces. - `+`: for signed numerical conversions, prefix number with a `+` sign if positive. - space: for signed numerical conversions, prefix number with a space if positive. - `#`: request an alternate formatting style for the integer types and the floating-point type `F`. The optional `width` is an integer indicating the minimal width of the result. For instance, `%6d` prints an integer, prefixing it with spaces to fill at least 6 characters. + The optional `precision` is a dot `.` followed by an integer indicating how many digits follow the decimal point in the `%f`, `%e`, `%E`, `%h`, and `%H` conversions or the maximum number of significant digits to appear for the `%F`, `%g` and `%G` conversions. For instance, `%.4f` prints a `float` with 4 fractional digits. + The integer in a `width` or `precision` can also be specified as `*`, in which case an extra integer argument is taken to specify the corresponding `width` or `precision`. This integer argument precedes immediately the argument to print. For instance, `%.*f` prints a `float` with as many fractional digits as the value of the argument given before the float. + ``` val printf : ('a, out_channel, unit) format -> 'a ``` Same as [`Printf.fprintf`](./#val-fprintf), but output on `stdout`. + ``` val eprintf : ('a, out_channel, unit) format -> 'a ``` Same as [`Printf.fprintf`](./#val-fprintf), but output on `stderr`. + ``` val sprintf : ('a, unit, string) format -> 'a ``` Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, return a string containing the result of formatting the arguments. + ``` val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a ``` Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module [`Buffer`](./Stdlib-Buffer.md)). + ``` val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a ``` Same as [`Printf.fprintf`](./#val-fprintf), but does not print anything. Useful to ignore some material when conditionally printing. + since 3.10 ``` val ibprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a ``` Same as [`Printf.bprintf`](./#val-bprintf), but does not print anything. Useful to ignore some material when conditionally printing. + since 4.11 Formatted output functions with continuations. + ``` val kfprintf : (out_channel -> 'd) -> @@ -80,16 +100,19 @@ val kfprintf : '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 ``` val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a ``` Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + since 4.01 ``` val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a ``` Same as `sprintf` above, but instead of returning the string, passes it to the first argument. + since 3.09 ``` val kbprintf : @@ -99,6 +122,7 @@ val kbprintf : 'a ``` Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing. + since 3.10 ``` val ikbprintf : @@ -108,10 +132,13 @@ val ikbprintf : 'a ``` Same as `kbprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + since 4.11 Deprecated + ``` val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a ``` A deprecated synonym for `ksprintf`. + deprecated Use Printf.ksprintf instead. \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Queue.md b/docs/api/melange/Stdlib-Queue.md index 1efb756bd..820e40343 100644 --- a/docs/api/melange/Stdlib-Queue.md +++ b/docs/api/melange/Stdlib-Queue.md @@ -1,106 +1,141 @@ + # Module `Stdlib.Queue` + First-in first-out queues. + This module implements queues (FIFOs), with in-place modification. See [the example section](./#examples) below. + **Unsynchronized accesses** + Unsynchronized accesses to a queue may lead to an invalid queue state. Thus, concurrent accesses to queues must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + ``` type !'a t ``` The type of queues containing elements of type `'a`. + ``` exception Empty ``` Raised when [`Queue.take`](./#val-take) or [`Queue.peek`](./#val-peek) is applied to an empty queue. + ``` val create : unit -> 'a t ``` Return a new queue, initially empty. + ``` val add : 'a -> 'a t -> unit ``` `add x q` adds the element `x` at the end of the queue `q`. + ``` val push : 'a -> 'a t -> unit ``` `push` is a synonym for `add`. + ``` val take : 'a t -> 'a ``` `take q` removes and returns the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. + ``` val take_opt : 'a t -> 'a option ``` `take_opt q` removes and returns the first element in queue `q`, or returns `None` if the queue is empty. + since 4.08 ``` val pop : 'a t -> 'a ``` `pop` is a synonym for `take`. + ``` val peek : 'a t -> 'a ``` `peek q` returns the first element in queue `q`, without removing it from the queue, or raises [`Empty`](./#exception-Empty) if the queue is empty. + ``` val peek_opt : 'a t -> 'a option ``` `peek_opt q` returns the first element in queue `q`, without removing it from the queue, or returns `None` if the queue is empty. + since 4.08 ``` val top : 'a t -> 'a ``` `top` is a synonym for `peek`. + ``` val drop : 'a t -> unit ``` `drop q` removes the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. + since 5.3 ``` val clear : 'a t -> unit ``` Discard all elements from a queue. + ``` val copy : 'a t -> 'a t ``` Return a copy of the given queue. + ``` val is_empty : 'a t -> bool ``` Return `true` if the given queue is empty, `false` otherwise. + ``` val length : 'a t -> int ``` Return the number of elements in a queue. + ``` val iter : ('a -> unit) -> 'a t -> unit ``` `iter f q` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. + ``` val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc ``` `fold f accu q` is equivalent to `List.fold_left f accu l`, where `l` is the list of `q`'s elements. The queue remains unchanged. + ``` val transfer : 'a t -> 'a t -> unit ``` `transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `iter (fun x -> add x q2) q1; clear q1`, but runs in constant time. + + ## Iterators + ``` val to_seq : 'a t -> 'a Seq.t ``` Iterate on the queue, in front-to-back order. The behavior is not specified if the queue is modified during the iteration. + since 4.07 ``` val add_seq : 'a t -> 'a Seq.t -> unit ``` Add the elements from a sequence to the end of the queue. + since 4.07 ``` val of_seq : 'a Seq.t -> 'a t ``` Create a queue from a sequence. + since 4.07 + ## Examples + + ### Basic Example + A basic example: + ```ocaml # let q = Queue.create () val q : '_weak1 Queue.t = @@ -124,8 +159,11 @@ val q : '_weak1 Queue.t = # Queue.pop q Exception: Stdlib.Queue.Empty. ``` + ### Search Through a Graph + For a more elaborate example, a classic algorithmic use of queues is to implement a BFS (breadth-first search) through a graph. + ```ocaml type graph = { edges: (int, int list) Hashtbl.t diff --git a/docs/api/melange/Stdlib-Random-State.md b/docs/api/melange/Stdlib-Random-State.md index 23d1d629e..cf10b7a30 100644 --- a/docs/api/melange/Stdlib-Random-State.md +++ b/docs/api/melange/Stdlib-Random-State.md @@ -1,20 +1,26 @@ + # Module `Random.State` + ``` type t ``` The type of PRNG states. + ``` val make : int array -> t ``` Create a new state and initialize it with the given seed. + ``` val make_self_init : unit -> t ``` Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in [`Random.self_init`](./Stdlib-Random.md#val-self_init). + ``` val copy : t -> t ``` Return a copy of the given state. + ``` val bits : t -> int ``` diff --git a/docs/api/melange/Stdlib-Random.md b/docs/api/melange/Stdlib-Random.md index 0ef606363..98f498047 100644 --- a/docs/api/melange/Stdlib-Random.md +++ b/docs/api/melange/Stdlib-Random.md @@ -1,69 +1,94 @@ + # Module `Stdlib.Random` + Pseudo-random number generators (PRNG). + With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain. + In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the `Random.split` function and used with the functions from the [`Random.State`](./Stdlib-Random-State.md) module. + before 5.0 Random value generation used a different algorithm. This affects all the functions in this module which return random values. + ## Basic functions + ``` val init : int -> unit ``` Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. + ``` val full_init : int array -> unit ``` Same as [`Random.init`](./#val-init) but takes more data as seed. + ``` val self_init : unit -> unit ``` Initialize the domain-local generator with a random seed chosen in a system-dependent way. If `/dev/urandom` is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state). + ``` val bits : unit -> int ``` Return 30 random bits in a nonnegative integer. + ``` val int : int -> int ``` `Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0 and less than 230. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0 or bound \>= 230. ``` val full_int : int -> int ``` `Random.full_int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` may be any positive integer. + If `bound` is less than 231, then `Random.full_int bound` yields identical output across systems with varying `int` sizes. + If `bound` is less than 230, then `Random.full_int bound` is equal to [`Random.int`](./#val-int)` bound`. + If `bound` is at least 230 (on 64-bit systems, or non-standard environments such as JavaScript), then `Random.full_int` returns a value whereas [`Random.int`](./#val-int) raises [`Stdlib.Invalid_argument`](./Stdlib.md#exception-Invalid_argument). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. since 4.13 ``` val int32 : Int32.t -> Int32.t ``` `Random.int32 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. ``` val int64 : Int64.t -> Int64.t ``` `Random.int64 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. ``` val float : float -> float ``` `Random.float bound` returns a random floating-point number between 0 and `bound` (inclusive). If `bound` is negative, the result is negative or zero. If `bound` is 0, the result is 0. + ``` val bool : unit -> bool ``` `Random.bool ()` returns `true` or `false` with probability 0.5 each. + ``` val bits32 : unit -> Int32.t ``` `Random.bits32 ()` returns 32 random bits as an integer between [`Int32.min_int`](./Stdlib-Int32.md#val-min_int) and [`Int32.max_int`](./Stdlib-Int32.md#val-max_int). + since 4.14 ``` val bits64 : unit -> Int64.t ``` `Random.bits64 ()` returns 64 random bits as an integer between [`Int64.min_int`](./Stdlib-Int64.md#val-min_int) and [`Int64.max_int`](./Stdlib-Int64.md#val-max_int). + since 4.14 + ## Advanced functions + The functions from module [`State`](./Stdlib-Random-State.md) manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. + ``` module State : sig ... end ``` @@ -71,7 +96,8 @@ module State : sig ... end val get_state : unit -> State.t ``` `get_state()` returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). + ``` val set_state : State.t -> unit ``` -`set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it. \ No newline at end of file +`set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it. diff --git a/docs/api/melange/Stdlib-Result.md b/docs/api/melange/Stdlib-Result.md index 3e7b579fb..5e42a7a68 100644 --- a/docs/api/melange/Stdlib-Result.md +++ b/docs/api/melange/Stdlib-Result.md @@ -1,8 +1,14 @@ + # Module `Stdlib.Result` + Result values. + Result values handle computation results and errors in an explicit and declarative manner without resorting to exceptions. + since 4.08 + ## Results + ``` type ('a, 'e) t = ('a, 'e) result = ``` @@ -16,65 +22,82 @@ type ('a, 'e) t = ('a, 'e) result = ``` The type for result values. Either a value `Ok v` or an error `Error e`. + ``` val ok : 'a -> ('a, 'e) result ``` `ok v` is `Ok v`. + ``` val error : 'e -> ('a, 'e) result ``` `error e` is `Error e`. + ``` val value : ('a, 'e) result -> default:'a -> 'a ``` `value r ~default` is `v` if `r` is `Ok v` and `default` otherwise. + ``` val get_ok : ('a, 'e) result -> 'a ``` `get_ok r` is `v` if `r` is `Ok v` and raise otherwise. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Error \_. ``` val get_error : ('a, 'e) result -> 'e ``` `get_error r` is `e` if `r` is `Error e` and raise otherwise. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Ok \_. ``` val bind : ('a, 'e) result -> ('a -> ('b, 'e) result) -> ('b, 'e) result ``` `bind r f` is `f v` if `r` is `Ok v` and `r` if `r` is `Error _`. + ``` val join : (('a, 'e) result, 'e) result -> ('a, 'e) result ``` `join rr` is `r` if `rr` is `Ok r` and `rr` if `rr` is `Error _`. + ``` val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result ``` `map f r` is `Ok (f v)` if `r` is `Ok v` and `r` if `r` is `Error _`. + ``` val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result ``` `map_error f r` is `Error (f e)` if `r` is `Error e` and `r` if `r` is `Ok _`. + ``` val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c ``` `fold ~ok ~error r` is `ok v` if `r` is `Ok v` and `error e` if `r` is `Error e`. + ``` val iter : ('a -> unit) -> ('a, 'e) result -> unit ``` `iter f r` is `f v` if `r` is `Ok v` and `()` otherwise. + ``` val iter_error : ('e -> unit) -> ('a, 'e) result -> unit ``` `iter_error f r` is `f e` if `r` is `Error e` and `()` otherwise. + + ## Predicates and comparisons + ``` val is_ok : ('a, 'e) result -> bool ``` `is_ok r` is `true` if and only if `r` is `Ok _`. + ``` val is_error : ('a, 'e) result -> bool ``` `is_error r` is `true` if and only if `r` is `Error _`. + ``` val equal : ok:('a -> 'a -> bool) -> @@ -84,6 +107,7 @@ val equal : bool ``` `equal ~ok ~error r0 r1` tests equality of `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. + ``` val compare : ok:('a -> 'a -> int) -> @@ -93,16 +117,21 @@ val compare : int ``` `compare ~ok ~error r0 r1` totally orders `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _ ` and `Error _`. `Ok _` values are smaller than `Error _` values. + + ## Converting + ``` val to_option : ('a, 'e) result -> 'a option ``` `to_option r` is `r` as an option, mapping `Ok v` to `Some v` and `Error _` to `None`. + ``` val to_list : ('a, 'e) result -> 'a list ``` `to_list r` is `[v]` if `r` is `Ok v` and `[]` otherwise. + ``` val to_seq : ('a, 'e) result -> 'a Seq.t ``` -`to_seq r` is `r` as a sequence. `Ok v` is the singleton sequence containing `v` and `Error _` is the empty sequence. \ No newline at end of file +`to_seq r` is `r` as a sequence. `Ok v` is the singleton sequence containing `v` and `Error _` is the empty sequence. diff --git a/docs/api/melange/Stdlib-Scanf-Scanning.md b/docs/api/melange/Stdlib-Scanf-Scanning.md index f123adeda..1bfe20e18 100644 --- a/docs/api/melange/Stdlib-Scanf-Scanning.md +++ b/docs/api/melange/Stdlib-Scanf-Scanning.md @@ -1,73 +1,95 @@ + # Module `Scanf.Scanning` + ``` type in_channel ``` The notion of input channel for the [`Scanf`](./Stdlib-Scanf.md) module: those channels provide all the machinery necessary to read from any source of characters, including a [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) value. A Scanf.Scanning.in\_channel value is also called a *formatted input channel* or equivalently a *scanning buffer*. The type [`Scanning.scanbuf`](./#type-scanbuf) below is an alias for `Scanning.in_channel`. Note that a `Scanning.in_channel` is not concurrency-safe: concurrent use may produce arbitrary values or exceptions. + since 3.12 ``` type scanbuf = in_channel ``` The type of scanning buffers. A scanning buffer is the source from which a formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far. + Note: a scanning action may often require to examine one character in advance; when this 'lookahead' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character yet to be read. + ``` val stdin : in_channel ``` The standard input notion for the [`Scanf`](./Stdlib-Scanf.md) module. `Scanning.stdin` is the [`Scanning.in_channel`](./#type-in_channel) formatted input channel attached to [`Stdlib.stdin`](./Stdlib.md#val-stdin). + Note: in the interactive system, when input is read from [`Stdlib.stdin`](./Stdlib.md#val-stdin), the newline character that triggers evaluation is part of the input; thus, the scanning specifications must properly skip this additional newline character (for instance, simply add a `'\n'` as the last character of the format string). + since 3.12 ``` type file_name = string ``` A convenient alias to designate a file name. + since 4.00 ``` val open_in : file_name -> in_channel ``` `Scanning.open_in fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in text mode from file `fname`. + Note: `open_in` returns a formatted input channel that efficiently reads characters in large chunks; in contrast, `from_channel` below returns formatted input channels that must read one character at a time, leading to a much slower scanning rate. + since 3.12 ``` val open_in_bin : file_name -> in_channel ``` `Scanning.open_in_bin fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in binary mode from file `fname`. + since 3.12 ``` val close_in : in_channel -> unit ``` Closes the [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) associated with the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + since 3.12 ``` val from_file : file_name -> in_channel ``` An alias for [`Scanning.open_in`](./#val-open_in) above. + ``` val from_file_bin : string -> in_channel ``` An alias for [`Scanning.open_in_bin`](./#val-open_in_bin) above. + ``` val from_string : string -> in_channel ``` `Scanning.from_string s` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached. + ``` val from_function : (unit -> char) -> in_channel ``` `Scanning.from_function f` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel with the given function as its reading method. + When scanning needs one more character, the given function is called. + When the function has no more character to provide, it *must* signal an end-of-input condition by raising the exception `End_of_file`. + ``` val from_channel : in_channel -> in_channel ``` `Scanning.from_channel ic` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the regular [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) input channel `ic` argument. Reading starts at current reading position of `ic`. + ``` val end_of_input : in_channel -> bool ``` `Scanning.end_of_input ic` tests the end-of-input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + ``` val beginning_of_input : in_channel -> bool ``` `Scanning.beginning_of_input ic` tests the beginning of input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + ``` val name_of_input : in_channel -> string ``` `Scanning.name_of_input ic` returns the name of the character source for the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + since 3.09 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Scanf.md b/docs/api/melange/Stdlib-Scanf.md index b6eb226e8..717b966f9 100644 --- a/docs/api/melange/Stdlib-Scanf.md +++ b/docs/api/melange/Stdlib-Scanf.md @@ -1,40 +1,68 @@ + # Module `Stdlib.Scanf` + Formatted input functions. + + ## Introduction + + ### Functional input with format strings + The module [`Scanf`](#) provides formatted input functions or *scanners*. + The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a *formatted input channel* (or *scanning buffer*) and has type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). The more general formatted input function reads from any scanning buffer and is named `bscanf`. + Generally speaking, the formatted input functions have 3 arguments: + - the first argument is a source of characters for the input, - the second argument is a format string that specifies the values to read, - the third argument is a *receiver function* that is applied to the values read. Hence, a typical call to the formatted input function [`Scanf.bscanf`](./#val-bscanf) is `bscanf ic fmt f`, where: + - `ic` is a source of characters (typically a *formatted input channel* with type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)), - `fmt` is a format string (the same format strings as those used to print material with module [`Printf`](./Stdlib-Printf.md) or [`Format`](./Stdlib-Format.md)), - `f` is a function that has as many arguments as the number of values to read in the input according to `fmt`. + ### A simple example + As suggested above, the expression `bscanf ic "%d" f` reads a decimal integer `n` from the source of characters `ic` and returns `f n`. + For instance, + - if we use `stdin` as the source of characters ([`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) is the predefined formatted input channel that reads from standard input), - if we define the receiver `f` as `let f x = x + 1`, then `bscanf Scanning.stdin "%d" f` reads an integer `n` from the standard input and returns `f n` (that is `n + 1`). Thus, if we evaluate `bscanf stdin "%d" f`, and then enter `41` at the keyboard, the result we get is `42`. + + ### Formatted input as a functional feature + The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assignment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time. + **Unsynchronized accesses** + Unsynchronized accesses to a [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) may lead to an invalid [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) state. Thus, concurrent accesses to [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)s must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + ## Formatted input channel + ``` module Scanning : sig ... end ``` + ## Type of formatted input functions + ``` type ('a, 'b, 'c, 'd) scanner = ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> 'c ``` The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic`. + For instance, the [`Scanf.scanf`](./#val-scanf) function below has type `('a, 'b, 'c, 'd) scanner`, since it is a formatted input function that reads from [`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin): `scanf fmt f` applies `f` to the arguments specified by `fmt`, reading those arguments from [`Stdlib.stdin`](./Stdlib.md#val-stdin) as expected. + If the format `fmt` has some `%r` indications, the corresponding formatted input functions must be provided *before* receiver function `f`. For instance, if `read_elem` is an input function for values of type `t`, then `bscanf ic "%r;" read_elem f` reads a value `v` of type `t` followed by a `';'` character, and returns `f v`. + since 3.10 ``` type ('a, 'b, 'c, 'd) scanner_opt = @@ -45,39 +73,59 @@ type ('a, 'b, 'c, 'd) scanner_opt = exception Scan_failure of string ``` When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan_failure`. + + ## The general formatted input function + ``` val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner ``` `bscanf ic fmt r1 ... rN f` reads characters from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic` and converts them to values according to format string `fmt`. As a final step, receiver function `f` is applied to the values read and gives the result of the `bscanf` call. + For instance, if `f` is the function `fun s i -> i + 1`, then `Scanf.sscanf "x = 1" "%s = %i" f` returns `2`. + Arguments `r1` to `rN` are user-defined input functions that read the argument corresponding to the `%r` conversions specified in the format string. + ``` val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt ``` Same as [`Scanf.bscanf`](./#val-bscanf), but returns `None` in case of scanning failure. + since 5.0 + ## Format string description + The format string is a character string which contains three types of objects: + - plain characters, which are simply matched with the characters of the input (with a special case for space and line feed, see [The space character in format strings](./#space)), - conversion specifications, each of which causes reading and conversion of one argument for the function `f` (see [Conversion specifications in format strings](./#conversion)), - scanning indications to specify boundaries of tokens (see scanning [Scanning indications in format strings](./#indication)). + ### The space character in format strings + As mentioned above, a plain character in the format string is just matched with the next character of the input; however, two characters are special exceptions to this rule: the space character (`' '` or ASCII code 32) and the line feed character (`'\n'` or ASCII code 10). A space does not match a single space character, but any amount of 'whitespace' in the input. More precisely, a space inside the format string matches *any number* of tab, space, line feed and carriage return characters. Similarly, a line feed character in the format string matches either a single line feed or a carriage return followed by a line feed. + Matching *any* amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call `bscanf ib "Price = %d $" (fun p -> p)` succeeds and returns `1` when reading an input with various whitespace in it, such as `Price = 1 $`, `Price = 1 $`, or even `Price=1$`. + + ### Conversion specifications in format strings + Conversion specifications consist in the `%` character, followed by an optional flag, an optional field width, and followed by one or two conversion characters. + The conversion characters and their meanings are: + - `d`: reads an optionally signed decimal integer (`0-9`\+). - `i`: reads an optionally signed integer (usual input conventions for decimal (`0-9`\+), hexadecimal (`0x[0-9a-f]+` and `0X[0-9A-F]+`), octal (`0o[0-7]+`), and binary (`0b[0-1]+`) notations are understood). - `u`: reads an unsigned decimal integer. - `x` or `X`: reads an unsigned hexadecimal integer (`[0-9a-fA-F]+`). - `o`: reads an unsigned octal integer (`[0-7]+`). - `s`: reads a string argument that spreads as much as possible, until the following bounding condition holds: + - a whitespace has been found (see [The space character in format strings](./#space)), - a scanning indication (see scanning [Scanning indications in format strings](./#indication)) has been encountered, - the end-of-input has been reached. Hence, this conversion always succeeds: it returns an empty string if the bounding condition holds when the scan begins. + - `S`: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml). - `c`: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification `%0c`. Raise `Invalid_argument`, if the field width specification is greater than 1\. - `C`: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml). @@ -101,42 +149,59 @@ The conversion characters and their meanings are: - `@`: matches one `@` character in the input. - `,`: does nothing. Following the `%` character that introduces a conversion, there may be the special flag `_`: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if `f` is the function `fun i -> i + 1`, and `s` is the string `"x = 1"`, then `Scanf.sscanf s "%_s = %i" f` returns `2`. + The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, `%6d` reads an integer, having at most 6 decimal digits; `%4f` reads a float with at most 4 characters; and `%8[\000-\255]` returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input). + Notes: + - as mentioned above, a `%s` conversion always succeeds, even if there is nothing to read in the input: in this case, it simply returns `""`. - in addition to the relevant digits, `'_'` characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions. - the `scanf` facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module `Str`), stream parsers, `ocamllex`\-generated lexers, `ocamlyacc`\-generated parsers. + ### Scanning indications in format strings + Scanning indications appear just after the string conversions `%s` and `%[ range ]` to delimit the end of the token. A scanning indication is introduced by a `@` character, followed by some plain character `c`. It means that the string token should end just before the next matching `c` (which is skipped). If no `c` character is encountered, the string token spreads as much as possible. For instance, `"%s@\t"` reads a string up to the next tab character or to the end of input. If a `@` character appears anywhere else in the format string, it is treated as a plain character. + Note: + - As usual in format strings, `%` and `@` characters must be escaped using `%%` and `%@`; this rule still holds within range specifications and scanning indications. For instance, format `"%s@%%"` reads a string up to the next `%` character, and format `"%s@%@"` reads a string up to the next `@`. - The scanning indications introduce slight differences in the syntax of [`Scanf`](#) format strings, compared to those used for the [`Printf`](./Stdlib-Printf.md) module. However, the scanning indications are similar to those used in the [`Format`](./Stdlib-Format.md) module; hence, when producing formatted text to be scanned by [`Scanf.bscanf`](./#val-bscanf), it is wise to use printing functions from the [`Format`](./Stdlib-Format.md) module (or, if you need to use functions from [`Printf`](./Stdlib-Printf.md), banish or carefully double check the format strings that contain `'@'` characters). + ### Exceptions during scanning + Scanners may raise the following exceptions when the input cannot be read according to the format string: + - Raise [`Scanf.Scan_failure`](./#exception-Scan_failure) if the input does not match the format. - Raise `Failure` if a conversion to a number is not possible. - Raise `End_of_file` if the end of input is encountered while some more characters are needed to read the current conversion specification. - Raise `Invalid_argument` if the format string is invalid. Note: + - as a consequence, scanning a `%s` conversion never raises exception `End_of_file`: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or `""` if none were ever read. + ## Specialised formatted input functions + ``` val sscanf : string -> ('a, 'b, 'c, 'd) scanner ``` Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the given string. + ``` val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt ``` Same as [`Scanf.sscanf`](./#val-sscanf), but returns `None` in case of scanning failure. + since 5.0 ``` val scanf : ('a, 'b, 'c, 'd) scanner ``` Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the predefined formatted input channel [`Scanf.Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) that is connected to [`Stdlib.stdin`](./Stdlib.md#val-stdin). + ``` val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt ``` Same as [`Scanf.scanf`](./#val-scanf), but returns `None` in case of scanning failure. + since 5.0 ``` val kscanf : @@ -145,6 +210,7 @@ val kscanf : ('a, 'b, 'c, 'd) scanner ``` Same as [`Scanf.bscanf`](./#val-bscanf), but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments. + ``` val ksscanf : string -> @@ -152,8 +218,11 @@ val ksscanf : ('a, 'b, 'c, 'd) scanner ``` Same as [`Scanf.kscanf`](./#val-kscanf) but reads from the given string. + since 4.02 + ## Reading format strings from input + ``` val bscanf_format : Scanning.in_channel -> @@ -162,6 +231,7 @@ val bscanf_format : 'g ``` `bscanf_format ic fmt f` reads a format string token from the formatted input channel `ic`, according to the given format string `fmt`, and applies `f` to the resulting format string value. + raises [`Scan_failure`](./#exception-Scan_failure) if the format string value read does not have the same type as fmt. since 3.09 ``` @@ -172,6 +242,7 @@ val sscanf_format : 'g ``` Same as [`Scanf.bscanf_format`](./#val-bscanf_format), but reads from the given string. + since 3.09 ``` val format_from_string : @@ -180,12 +251,15 @@ val format_from_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 ``` `format_from_string s fmt` converts a string argument to a format string, according to the given format string `fmt`. + raises [`Scan_failure`](./#exception-Scan_failure) if s, considered as a format string, does not have the same type as fmt. since 3.10 ``` val unescaped : string -> string ``` `unescaped s` return a copy of `s` with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, `Scanf.unescaped` has the following property: for all string `s`, `Scanf.unescaped (String.escaped s) = s`. + Always return a copy of the argument, even if there is no escape sequence in the argument. + raises [`Scan_failure`](./#exception-Scan_failure) if s is not properly escaped (i.e. s has invalid escape sequences or special characters that are not properly escaped). For instance, Scanf.unescaped "\\"" will fail. since 4.00 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Seq.md b/docs/api/melange/Stdlib-Seq.md index 37d85ea05..fae489474 100644 --- a/docs/api/melange/Stdlib-Seq.md +++ b/docs/api/melange/Stdlib-Seq.md @@ -1,23 +1,35 @@ + # Module `Stdlib.Seq` + Sequences. + A sequence of type `'a Seq.t` can be thought of as a **delayed list**, that is, a list whose elements are computed only when they are demanded by a consumer. This allows sequences to be produced and transformed lazily (one element at a time) rather than eagerly (all elements at once). This also allows constructing conceptually infinite sequences. + The type `'a Seq.t` is defined as a synonym for `unit -> 'a Seq.node`. This is a function type: therefore, it is opaque. The consumer can **query** a sequence in order to request the next element (if there is one), but cannot otherwise inspect the sequence in any way. + Because it is opaque, the type `'a Seq.t` does *not* reveal whether a sequence is: + - **persistent**, which means that the sequence can be used as many times as desired, producing the same elements every time, just like an immutable list; or - **ephemeral**, which means that the sequence is not persistent. Querying an ephemeral sequence might have an observable side effect, such as incrementing a mutable counter. As a common special case, an ephemeral sequence can be **affine**, which means that it must be queried at most once. It also does *not* reveal whether the elements of the sequence are: + - **pre-computed and stored** in memory, which means that querying the sequence is cheap; - **computed when first demanded and then stored** in memory, which means that querying the sequence once can be expensive, but querying the same sequence again is cheap; or - **re-computed every time they are demanded**, which may or may not be cheap. It is up to the programmer to keep these distinctions in mind so as to understand the time and space requirements of sequences. + For the sake of simplicity, most of the documentation that follows is written under the implicit assumption that the sequences at hand are persistent. We normally do not point out *when* or *how many times* each function is invoked, because that would be too verbose. For instance, in the description of `map`, we write: "if `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`". If we wished to be more explicit, we could point out that the transformation takes place on demand: that is, the elements of `map f xs` are computed only when they are demanded. In other words, the definition `let ys = map f xs` terminates immediately and does not invoke `f`. The function call `f x0` takes place only when the first element of `ys` is demanded, via the function call `ys()`. Furthermore, calling `ys()` twice causes `f x0` to be called twice as well. If one wishes for `f` to be applied at most once to each element of `xs`, even in scenarios where `ys` is queried more than once, then one should use `let ys = memoize (map f xs)`. + As a general rule, the functions that build sequences, such as `map`, `filter`, `scan`, `take`, etc., produce sequences whose elements are computed only on demand. The functions that eagerly consume sequences, such as `is_empty`, `find`, `length`, `iter`, `fold_left`, etc., are the functions that force computation to take place. + When possible, we recommend using sequences rather than dispensers (functions of type `unit -> 'a option` that produce elements upon demand). Whereas sequences can be persistent or ephemeral, dispensers are always ephemeral, and are typically more difficult to work with than sequences. Two conversion functions, [`to_dispenser`](./#val-to_dispenser) and [`of_dispenser`](./#val-of_dispenser), are provided. + since 4.07 ``` type 'a t = unit -> 'a node ``` A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. Such a sequence is queried by performing a function application `xs()`. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail. + ``` and +'a node = ``` @@ -31,408 +43,582 @@ and +'a node = ``` A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence. + + ## Consuming sequences + The functions in this section consume their argument, a sequence, either partially or completely: + - `is_empty` and `uncons` consume the sequence down to depth 1\. That is, they demand the first argument of the sequence, if there is one. - `iter`, `fold_left`, `length`, etc., consume the sequence all the way to its end. They terminate only if the sequence is finite. - `for_all`, `exists`, `find`, etc. consume the sequence down to a certain depth, which is a priori unpredictable. Similarly, among the functions that consume two sequences, one can distinguish two groups: + - `iter2` and `fold_left2` consume both sequences all the way to the end, provided the sequences have the same length. - `for_all2`, `exists2`, `equal`, `compare` consume the sequences down to a certain depth, which is a priori unpredictable. The functions that consume two sequences can be applied to two sequences of distinct lengths: in that case, the excess elements in the longer sequence are ignored. (It may be the case that one excess element is demanded, even though this element is not used.) + None of the functions in this section is lazy. These functions are consumers: they force some computation to take place. + ``` val is_empty : 'a t -> bool ``` `is_empty xs` determines whether the sequence `xs` is empty. + It is recommended that the sequence `xs` be persistent. Indeed, `is_empty xs` demands the head of the sequence `xs`, so, if `xs` is ephemeral, it may be the case that `xs` cannot be used any more after this call has taken place. + since 4.14 ``` val uncons : 'a t -> ('a * 'a t) option ``` If `xs` is empty, then `uncons xs` is `None`. + If `xs` is nonempty, then `uncons xs` is `Some (x, ys)` where `x` is the head of the sequence and `ys` its tail. + since 4.14 ``` val length : 'a t -> int ``` `length xs` is the length of the sequence `xs`. + The sequence `xs` must be finite. + since 4.14 ``` val iter : ('a -> unit) -> 'a t -> unit ``` `iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right. + It terminates only if the sequence `xs` is finite. + ``` val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc ``` `fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right. + An accumulator of type `'a` is threaded through the calls to `f`. + It terminates only if the sequence `xs` is finite. + ``` val iteri : (int -> 'a -> unit) -> 'a t -> unit ``` `iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`. + It terminates only if the sequence `xs` is finite. + `iteri f xs` is equivalent to `iter (fun (i, x) -> f i x) (zip (ints 0) xs)`. + since 4.14 ``` val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc ``` `fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`. + An accumulator of type `'b` is threaded through the calls to `f`. + It terminates only if the sequence `xs` is finite. + `fold_lefti f accu xs` is equivalent to `fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)`. + since 4.14 ``` val for_all : ('a -> bool) -> 'a t -> bool ``` `for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`. + The sequence `xs` must be finite. + since 4.14 ``` val exists : ('a -> bool) -> 'a t -> bool ``` `exists xs p` determines whether at least one element `x` of the sequence `xs` satisfies `p x`. + The sequence `xs` must be finite. + since 4.14 ``` val find : ('a -> bool) -> 'a t -> 'a option ``` `find p xs` returns `Some x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element. + It returns `None` if there is no such element. + The sequence `xs` must be finite. + since 4.14 ``` val find_index : ('a -> bool) -> 'a t -> int option ``` `find_index p xs` returns `Some i`, where `i` is the index of the first element of the sequence `xs` that satisfies `p x`, if there is such an element. + It returns `None` if there is no such element. + The sequence `xs` must be finite. + since 5.1 ``` val find_map : ('a -> 'b option) -> 'a t -> 'b option ``` `find_map f xs` returns `Some y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`. + It returns `None` if there is no such element. + The sequence `xs` must be finite. + since 4.14 ``` val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option ``` Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + The sequence `xs` must be finite. + since 5.1 ``` val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit ``` `iter2 f xs ys` invokes `f x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. + If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. + `iter2 f xs ys` is equivalent to `iter (fun (x, y) -> f x y) (zip xs ys)`. + since 4.14 ``` val fold_left2 : ('acc -> 'a -> 'b -> 'acc) -> 'acc -> 'a t -> 'b t -> 'acc ``` `fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. + An accumulator of type `'a` is threaded through the calls to `f`. + If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. + `fold_left2 f accu xs ys` is equivalent to `fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)`. + since 4.14 ``` val for_all2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool ``` `for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`. + If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if `xs` or `ys` is empty, then `for_all2 p xs ys` is true. This is where `for_all2` and `equal` differ: `equal eq xs ys` can be true only if `xs` and `ys` have the same length. + At least one of the sequences `xs` and `ys` must be finite. + `for_all2 p xs ys` is equivalent to `for_all (fun b -> b) (map2 p xs ys)`. + since 4.14 ``` val exists2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool ``` `exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`. + If the sequences `xs` and `ys` have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + At least one of the sequences `xs` and `ys` must be finite. + `exists2 p xs ys` is equivalent to `exists (fun b -> b) (map2 p xs ys)`. + since 4.14 ``` val equal : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool ``` Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal. + At least one of the sequences `xs` and `ys` must be finite. + since 4.14 ``` val compare : ('a -> 'b -> int) -> 'a t -> 'b t -> int ``` Provided the function `cmp` defines a preorder on elements, `compare cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder. + For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). + At least one of the sequences `xs` and `ys` must be finite. + since 4.14 + ## Constructing sequences + The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. + ``` val empty : 'a t ``` `empty` is the empty sequence. It has no elements. Its length is 0. + ``` val return : 'a -> 'a t ``` `return x` is the sequence whose sole element is `x`. Its length is 1\. + ``` val cons : 'a -> 'a t -> 'a t ``` `cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`. + Writing `cons (f()) xs` causes the function call `f()` to take place immediately. For this call to be delayed until the sequence is queried, one must instead write `(fun () -> Cons(f(), xs))`. + since 4.11 ``` val init : int -> (int -> 'a) -> 'a t ``` `init n f` is the sequence `f 0; f 1; ...; f (n-1)`. + `n` must be nonnegative. + If desired, the infinite sequence `f 0; f 1; ...` can be defined as `map f (ints 0)`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 4.14 ``` val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t ``` `unfold` constructs a sequence out of a step function and an initial state. + If `f u` is `None` then `unfold f u` is the empty sequence. If `f u` is `Some (x, u')` then `unfold f u` is the nonempty sequence `cons x (unfold f u')`. + For example, `unfold (function [] -> None | h :: t -> Some (h, t)) l` is equivalent to `List.to_seq l`. + since 4.11 ``` val repeat : 'a -> 'a t ``` `repeat x` is the infinite sequence where the element `x` is repeated indefinitely. + `repeat x` is equivalent to `cycle (return x)`. + since 4.14 ``` val forever : (unit -> 'a) -> 'a t ``` `forever f` is an infinite sequence where every element is produced (on demand) by the function call `f()`. + For instance, `forever Random.bool` is an infinite sequence of random bits. + `forever f` is equivalent to `map f (repeat ())`. + since 4.14 ``` val cycle : 'a t -> 'a t ``` `cycle xs` is the infinite sequence that consists of an infinite number of repetitions of the sequence `xs`. + If `xs` is an empty sequence, then `cycle xs` is empty as well. + Consuming (a prefix of) the sequence `cycle xs` once can cause the sequence `xs` to be consumed more than once. Therefore, `xs` must be persistent. + since 4.14 ``` val iterate : ('a -> 'a) -> 'a -> 'a t ``` `iterate f x` is the infinite sequence whose elements are `x`, `f x`, `f (f x)`, and so on. + In other words, it is the orbit of the function `f`, starting at `x`. + since 4.14 + ## Transforming sequences + The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. + ``` val map : ('a -> 'b) -> 'a t -> 'b t ``` `map f xs` is the image of the sequence `xs` through the transformation `f`. + If `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`. + ``` val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t ``` `mapi` is analogous to `map`, but applies the function `f` to an index and an element. + `mapi f xs` is equivalent to `map2 f (ints 0) xs`. + since 4.14 ``` val filter : ('a -> bool) -> 'a t -> 'a t ``` `filter p xs` is the sequence of the elements `x` of `xs` that satisfy `p x`. + In other words, `filter p xs` is the sequence `xs`, deprived of the elements `x` such that `p x` is false. + ``` val filter_map : ('a -> 'b option) -> 'a t -> 'b t ``` `filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`. + `filter_map f xs` is equivalent to `map Option.get (filter Option.is_some (map f xs))`. + ``` val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t ``` If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators `[a0; a1; a2; ...]` where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on. + Thus, `scan f a0 xs` is conceptually related to `fold_left f a0 xs`. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators. + For instance, `scan (+) 0` transforms a sequence of integers into the sequence of its partial sums. + If `xs` has length `n` then `scan f a0 xs` has length `n+1`. + since 4.14 ``` val take : int -> 'a t -> 'a t ``` `take n xs` is the sequence of the first `n` elements of `xs`. + If `xs` has fewer than `n` elements, then `take n xs` is equivalent to `xs`. + `n` must be nonnegative. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 4.14 ``` val drop : int -> 'a t -> 'a t ``` `drop n xs` is the sequence `xs`, deprived of its first `n` elements. + If `xs` has fewer than `n` elements, then `drop n xs` is empty. + `n` must be nonnegative. + `drop` is lazy: the first `n+1` elements of the sequence `xs` are demanded only when the first element of `drop n xs` is demanded. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. since 4.14 ``` val take_while : ('a -> bool) -> 'a t -> 'a t ``` `take_while p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`. + since 4.14 ``` val drop_while : ('a -> bool) -> 'a t -> 'a t ``` `drop_while p xs` is the sequence `xs`, deprived of the prefix `take_while p xs`. + since 4.14 ``` val group : ('a -> 'a -> bool) -> 'a t -> 'a t t ``` Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`. + Every element of `group eq xs` is a nonempty sequence of equal elements. + The concatenation `concat (group eq xs)` is equal to `xs`. + Consuming `group eq xs`, and consuming the sequences that it contains, can cause `xs` to be consumed more than once. Therefore, `xs` must be persistent. + since 4.14 ``` val memoize : 'a t -> 'a t ``` The sequence `memoize xs` has the same elements as the sequence `xs`. + Regardless of whether `xs` is ephemeral or persistent, `memoize xs` is persistent: even if it is queried several times, `xs` is queried at most once. + The construction of the sequence `memoize xs` internally relies on suspensions provided by the module [`Lazy`](./Stdlib-Lazy.md). These suspensions are *not* thread-safe. Therefore, the sequence `memoize xs` must *not* be queried by multiple threads concurrently. + since 4.14 ``` exception Forced_twice ``` This exception is raised when a sequence returned by [`once`](./#val-once) (or a suffix of it) is queried more than once. + since 4.14 ``` val once : 'a t -> 'a t ``` The sequence `once xs` has the same elements as the sequence `xs`. + Regardless of whether `xs` is ephemeral or persistent, `once xs` is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception `Forced_twice` is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once. + raises [`Forced_twice`](./#exception-Forced_twice) if once xs, or a suffix of it, is queried more than once. since 4.14 ``` val transpose : 'a t t -> 'a t t ``` If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`. + The rows of the matrix `xss` are not required to have the same length. + The matrix `xss` is not required to be finite (in either direction). + The matrix `xss` must be persistent. + since 4.14 + ## Combining sequences + ``` val append : 'a t -> 'a t -> 'a t ``` `append xs ys` is the concatenation of the sequences `xs` and `ys`. + Its elements are the elements of `xs`, followed by the elements of `ys`. + since 4.11 ``` val concat : 'a t t -> 'a t ``` If `xss` is a sequence of sequences, then `concat xss` is its concatenation. + If `xss` is the sequence `xs0; xs1; ...` then `concat xss` is the sequence `xs0 @ xs1 @ ...`. + since 4.13 ``` val flat_map : ('a -> 'b t) -> 'a t -> 'b t ``` `flat_map f xs` is equivalent to `concat (map f xs)`. + ``` val concat_map : ('a -> 'b t) -> 'a t -> 'b t ``` `concat_map f xs` is equivalent to `concat (map f xs)`. + `concat_map` is an alias for `flat_map`. + since 4.13 ``` val zip : 'a t -> 'b t -> ('a * 'b) t ``` `zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`. + If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + `zip xs ys` is equivalent to `map2 (fun a b -> (a, b)) xs ys`. + since 4.14 ``` val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t ``` `map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`. + If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + `map2 f xs ys` is equivalent to `map (fun (x, y) -> f x y) (zip xs ys)`. + since 4.14 ``` val interleave : 'a t -> 'a t -> 'a t ``` `interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on. + When one of the sequences `xs` and `ys` is exhausted, `interleave xs ys` continues with the rest of the other sequence. + since 4.14 ``` val sorted_merge : ('a -> 'a -> int) -> 'a t -> 'a t -> 'a t ``` If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`. + For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). + since 4.14 ``` val product : 'a t -> 'b t -> ('a * 'b) t ``` `product xs ys` is the Cartesian product of the sequences `xs` and `ys`. + For every element `x` of `xs` and for every element `y` of `ys`, the pair `(x, y)` appears once as an element of `product xs ys`. + The order in which the pairs appear is unspecified. + The sequences `xs` and `ys` are not required to be finite. + The sequences `xs` and `ys` must be persistent. + since 4.14 ``` val map_product : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t ``` The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`. + For every element `x` of `xs` and for every element `y` of `ys`, the element `f x y` appears once as an element of `map_product f xs ys`. + The order in which these elements appear is unspecified. + The sequences `xs` and `ys` are not required to be finite. + The sequences `xs` and `ys` must be persistent. + `map_product f xs ys` is equivalent to `map (fun (x, y) -> f x y) (product xs ys)`. + since 4.14 + ## Splitting a sequence into two sequences + ``` val unzip : ('a * 'b) t -> 'a t * 'b t ``` `unzip` transforms a sequence of pairs into a pair of sequences. + `unzip xs` is equivalent to `(map fst xs, map snd xs)`. + Querying either of the sequences returned by `unzip xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `unzip (memoize xs)`. + since 4.14 ``` val split : ('a * 'b) t -> 'a t * 'b t ``` `split` is an alias for `unzip`. + since 4.14 ``` val partition_map : ('a -> ('b, 'c) Either.t) -> 'a t -> 'b t * 'c t ``` `partition_map f xs` returns a pair of sequences `(ys, zs)`, where: + - `ys` is the sequence of the elements `y` such that `f x = Left y`, where `x` ranges over `xs`; - `zs` is the sequence of the elements `z` such that `f x = Right z`, where `x` ranges over `xs`. `partition_map f xs` is equivalent to a pair of `filter_map Either.find_left (map f xs)` and `filter_map Either.find_right (map f xs)`. + Querying either of the sequences returned by `partition_map f xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `partition_map f (memoize xs)`. + since 4.14 ``` val partition : ('a -> bool) -> 'a t -> 'a t * 'a t ``` `partition p xs` returns a pair of the subsequence of the elements of `xs` that satisfy `p` and the subsequence of the elements of `xs` that do not satisfy `p`. + `partition p xs` is equivalent to `filter p xs, filter (fun x -> not (p x)) xs`. + Consuming both of the sequences returned by `partition p xs` causes `xs` to be consumed twice and causes the function `f` to be applied twice to each element of the list. Therefore, `f` should be pure and cheap. Furthermore, `xs` should be persistent and cheap. If that is not the case, use `partition p (memoize xs)`. + since 4.14 + ## Converting between sequences and dispensers + A dispenser is a representation of a sequence as a function of type `unit -> 'a option`. Every time this function is invoked, it returns the next element of the sequence. When there are no more elements, it returns `None`. A dispenser has mutable internal state, therefore is ephemeral: the sequence that it represents can be consumed at most once. + ``` val of_dispenser : (unit -> 'a option) -> 'a t ``` `of_dispenser it` is the sequence of the elements produced by the dispenser `it`. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use `memoize (of_dispenser it)`. + since 4.14 ``` val to_dispenser : 'a t -> unit -> 'a option ``` `to_dispenser xs` is a fresh dispenser on the sequence `xs`. + This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently. + since 4.14 + ## Sequences of integers + ``` val ints : int -> int t ``` `ints i` is the infinite sequence of the integers beginning at `i` and counting up. + since 4.14 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md b/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md index bce17bb85..3abdead73 100644 --- a/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md +++ b/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md @@ -1,9 +1,12 @@ + # Parameter `Make.Ord` + ``` type t ``` The type of the set elements. + ``` val compare : t -> t -> int ``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-Set-Make.md b/docs/api/melange/Stdlib-Set-Make.md index f248d8dbe..93d2962e8 100644 --- a/docs/api/melange/Stdlib-Set-Make.md +++ b/docs/api/melange/Stdlib-Set-Make.md @@ -1,225 +1,297 @@ + # Module `Set.Make` + Functor building an implementation of the set structure given a totally ordered type. + + ## Parameters + ``` module Ord : OrderedType ``` + ## Signature + + ## Sets + ``` type elt = Ord.t ``` The type of the set elements. + ``` type t ``` The type of sets. + ``` val empty : t ``` The empty set. + ``` val add : elt -> t -> t ``` `add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val singleton : elt -> t ``` `singleton x` returns the one-element set containing only `x`. + ``` val remove : elt -> t -> t ``` `remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val union : t -> t -> t ``` Set union. + ``` val inter : t -> t -> t ``` Set intersection. + ``` val disjoint : t -> t -> bool ``` Test if two sets are disjoint. + since 4.08 ``` val diff : t -> t -> t ``` Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + ``` val cardinal : t -> int ``` Return the number of elements of a set. + + ## Elements + ``` val elements : t -> elt list ``` Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). + ``` val min_elt : t -> elt ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + ``` val min_elt_opt : t -> elt option ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + since 4.05 ``` val max_elt : t -> elt ``` Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + ``` val max_elt_opt : t -> elt option ``` Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + since 4.05 ``` val choose : t -> elt ``` Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + ``` val choose_opt : t -> elt option ``` Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + since 4.05 + ## Searching + ``` val find : elt -> t -> elt ``` `find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + since 4.01 ``` val find_opt : elt -> t -> elt option ``` `find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + since 4.05 ``` val find_first : (elt -> bool) -> t -> elt ``` `find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + since 4.05 ``` val find_first_opt : (elt -> bool) -> t -> elt option ``` `find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 ``` val find_last : (elt -> bool) -> t -> elt ``` `find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + since 4.05 ``` val find_last_opt : (elt -> bool) -> t -> elt option ``` `find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 + ## Traversing + ``` val iter : (elt -> unit) -> t -> unit ``` `iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + ``` val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc ``` `fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + ## Transforming + ``` val map : (elt -> elt) -> t -> t ``` `map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + since 4.04 ``` val filter : (elt -> bool) -> t -> t ``` `filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val filter_map : (elt -> elt option) -> t -> t ``` `filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + For example, + ```ocaml filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s ``` is the set of halves of the even elements of `s`. + If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + since 4.11 ``` val partition : (elt -> bool) -> t -> t * t ``` `partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + ``` val split : elt -> t -> t * bool * t ``` `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + ## Predicates and comparisons + ``` val is_empty : t -> bool ``` Test whether a set is empty or not. + ``` val mem : elt -> t -> bool ``` `mem x s` tests whether `x` belongs to the set `s`. + ``` val equal : t -> t -> bool ``` `equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + ``` val compare : t -> t -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. + ``` val subset : t -> t -> bool ``` `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + ``` val for_all : (elt -> bool) -> t -> bool ``` `for_all f s` checks if all elements of the set satisfy the predicate `f`. + ``` val exists : (elt -> bool) -> t -> bool ``` `exists f s` checks if at least one element of the set satisfies the predicate `f`. + + ## Converting + ``` val to_list : t -> elt list ``` `to_list s` is [`elements`](./#val-elements)` s`. + since 5.1 ``` val of_list : elt list -> t ``` `of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + since 4.02 ``` val to_seq_from : elt -> t -> elt Seq.t ``` `to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + since 4.07 ``` val to_seq : t -> elt Seq.t ``` Iterate on the whole set, in ascending order + since 4.07 ``` val to_rev_seq : t -> elt Seq.t ``` Iterate on the whole set, in descending order + since 4.12 ``` val add_seq : elt Seq.t -> t -> t ``` Add the given elements to the set, in order. + since 4.07 ``` val of_seq : elt Seq.t -> t ``` Build a set from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set-module-type-OrderedType.md b/docs/api/melange/Stdlib-Set-module-type-OrderedType.md index 38b071184..11f9d9c0d 100644 --- a/docs/api/melange/Stdlib-Set-module-type-OrderedType.md +++ b/docs/api/melange/Stdlib-Set-module-type-OrderedType.md @@ -1,10 +1,14 @@ + # Module type `Set.OrderedType` + Input signature of the functor [`Make`](./Stdlib-Set-Make.md). + ``` type t ``` The type of the set elements. + ``` val compare : t -> t -> int ``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). \ No newline at end of file +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/melange/Stdlib-Set-module-type-S.md b/docs/api/melange/Stdlib-Set-module-type-S.md index dbd3b7007..72db61d6a 100644 --- a/docs/api/melange/Stdlib-Set-module-type-S.md +++ b/docs/api/melange/Stdlib-Set-module-type-S.md @@ -1,220 +1,288 @@ + # Module type `Set.S` + Output signature of the functor [`Make`](./Stdlib-Set-Make.md). + + ## Sets + ``` type elt ``` The type of the set elements. + ``` type t ``` The type of sets. + ``` val empty : t ``` The empty set. + ``` val add : elt -> t -> t ``` `add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val singleton : elt -> t ``` `singleton x` returns the one-element set containing only `x`. + ``` val remove : elt -> t -> t ``` `remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val union : t -> t -> t ``` Set union. + ``` val inter : t -> t -> t ``` Set intersection. + ``` val disjoint : t -> t -> bool ``` Test if two sets are disjoint. + since 4.08 ``` val diff : t -> t -> t ``` Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + ``` val cardinal : t -> int ``` Return the number of elements of a set. + + ## Elements + ``` val elements : t -> elt list ``` Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-Set-Make.md). + ``` val min_elt : t -> elt ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + ``` val min_elt_opt : t -> elt option ``` Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + since 4.05 ``` val max_elt : t -> elt ``` Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + ``` val max_elt_opt : t -> elt option ``` Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + since 4.05 ``` val choose : t -> elt ``` Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + ``` val choose_opt : t -> elt option ``` Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + since 4.05 + ## Searching + ``` val find : elt -> t -> elt ``` `find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + since 4.01 ``` val find_opt : elt -> t -> elt option ``` `find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + since 4.05 ``` val find_first : (elt -> bool) -> t -> elt ``` `find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + since 4.05 ``` val find_first_opt : (elt -> bool) -> t -> elt option ``` `find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 ``` val find_last : (elt -> bool) -> t -> elt ``` `find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + since 4.05 ``` val find_last_opt : (elt -> bool) -> t -> elt option ``` `find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + since 4.05 + ## Traversing + ``` val iter : (elt -> unit) -> t -> unit ``` `iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + ``` val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc ``` `fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + ## Transforming + ``` val map : (elt -> elt) -> t -> t ``` `map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + since 4.04 ``` val filter : (elt -> bool) -> t -> t ``` `filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + before 4.03 Physical equality was not ensured. ``` val filter_map : (elt -> elt option) -> t -> t ``` `filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + For example, + ```ocaml filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s ``` is the set of halves of the even elements of `s`. + If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + since 4.11 ``` val partition : (elt -> bool) -> t -> t * t ``` `partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + ``` val split : elt -> t -> t * bool * t ``` `split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + ## Predicates and comparisons + ``` val is_empty : t -> bool ``` Test whether a set is empty or not. + ``` val mem : elt -> t -> bool ``` `mem x s` tests whether `x` belongs to the set `s`. + ``` val equal : t -> t -> bool ``` `equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + ``` val compare : t -> t -> int ``` Total ordering between sets. Can be used as the ordering function for doing sets of sets. + ``` val subset : t -> t -> bool ``` `subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + ``` val for_all : (elt -> bool) -> t -> bool ``` `for_all f s` checks if all elements of the set satisfy the predicate `f`. + ``` val exists : (elt -> bool) -> t -> bool ``` `exists f s` checks if at least one element of the set satisfies the predicate `f`. + + ## Converting + ``` val to_list : t -> elt list ``` `to_list s` is [`elements`](./#val-elements)` s`. + since 5.1 ``` val of_list : elt list -> t ``` `of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + since 4.02 ``` val to_seq_from : elt -> t -> elt Seq.t ``` `to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + since 4.07 ``` val to_seq : t -> elt Seq.t ``` Iterate on the whole set, in ascending order + since 4.07 ``` val to_rev_seq : t -> elt Seq.t ``` Iterate on the whole set, in descending order + since 4.12 ``` val add_seq : elt Seq.t -> t -> t ``` Add the given elements to the set, in order. + since 4.07 ``` val of_seq : elt Seq.t -> t ``` Build a set from the given bindings + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Set.md b/docs/api/melange/Stdlib-Set.md index 67f1c9b14..f961f9b00 100644 --- a/docs/api/melange/Stdlib-Set.md +++ b/docs/api/melange/Stdlib-Set.md @@ -1,7 +1,12 @@ + # Module `Stdlib.Set` + Sets over ordered types. + This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. + The [`Make`](./Stdlib-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: + ```ocaml module IntPairs = struct @@ -17,15 +22,18 @@ The [`Make`](./Stdlib-Set-Make.md) functor constructs implementations for any ty let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) ``` This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. + ``` module type OrderedType = sig ... end ``` Input signature of the functor [`Make`](./Stdlib-Set-Make.md). + ``` module type S = sig ... end ``` Output signature of the functor [`Make`](./Stdlib-Set-Make.md). + ``` module Make (Ord : OrderedType) : S with type elt = Ord.t ``` -Functor building an implementation of the set structure given a totally ordered type. \ No newline at end of file +Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/melange/Stdlib-Stack.md b/docs/api/melange/Stdlib-Stack.md index d6cfffb21..e02894994 100644 --- a/docs/api/melange/Stdlib-Stack.md +++ b/docs/api/melange/Stdlib-Stack.md @@ -1,85 +1,111 @@ + # Module `Stdlib.Stack` + Last-in first-out stacks. + This module implements stacks (LIFOs), with in-place modification. + **Unsynchronized accesses** + Unsynchronized accesses to a stack may lead to an invalid queue state. Thus, concurrent accesses to stacks must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + ``` type !'a t ``` The type of stacks containing elements of type `'a`. + ``` exception Empty ``` Raised when [`Stack.pop`](./#val-pop) or [`Stack.top`](./#val-top) is applied to an empty stack. + ``` val create : unit -> 'a t ``` Return a new stack, initially empty. + ``` val push : 'a -> 'a t -> unit ``` `push x s` adds the element `x` at the top of stack `s`. + ``` val pop : 'a t -> 'a ``` `pop s` removes and returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. + ``` val pop_opt : 'a t -> 'a option ``` `pop_opt s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty. + since 4.08 ``` val drop : 'a t -> unit ``` `drop s` removes the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. + since 5.1 ``` val top : 'a t -> 'a ``` `top s` returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. + ``` val top_opt : 'a t -> 'a option ``` `top_opt s` returns the topmost element in stack `s`, or `None` if the stack is empty. + since 4.08 ``` val clear : 'a t -> unit ``` Discard all elements from a stack. + ``` val copy : 'a t -> 'a t ``` Return a copy of the given stack. + ``` val is_empty : 'a t -> bool ``` Return `true` if the given stack is empty, `false` otherwise. + ``` val length : 'a t -> int ``` Return the number of elements in a stack. Time complexity O(1) + ``` val iter : ('a -> unit) -> 'a t -> unit ``` `iter f s` applies `f` in turn to all elements of `s`, from the element at the top of the stack to the element at the bottom of the stack. The stack itself is unchanged. + ``` val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc ``` `fold f accu s` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1` is the top of the stack, `x2` the second element, and `xn` the bottom element. The stack is unchanged. + since 4.03 + ## Stacks and Sequences + ``` val to_seq : 'a t -> 'a Seq.t ``` Iterate on the stack, top to bottom. It is safe to modify the stack during iteration. + since 4.07 ``` val add_seq : 'a t -> 'a Seq.t -> unit ``` Add the elements from the sequence on the top of the stack. + since 4.07 ``` val of_seq : 'a Seq.t -> 'a t ``` Create a stack from the sequence. + since 4.07 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-StdLabels.md b/docs/api/melange/Stdlib-StdLabels.md index 44581af3e..e90ae87f6 100644 --- a/docs/api/melange/Stdlib-StdLabels.md +++ b/docs/api/melange/Stdlib-StdLabels.md @@ -1,6 +1,10 @@ + # Module `Stdlib.StdLabels` + Standard labeled libraries. + This meta-module provides versions of the [`Array`](./Stdlib-ArrayLabels.md), [`Bytes`](./Stdlib-BytesLabels.md), [`List`](./Stdlib-ListLabels.md) and [`String`](./Stdlib-StringLabels.md) modules where function arguments are systematically labeled. It is intended to be opened at the top of source files, as shown below. + ```ocaml open StdLabels diff --git a/docs/api/melange/Stdlib-String.md b/docs/api/melange/Stdlib-String.md index 0e73d1b47..063536325 100644 --- a/docs/api/melange/Stdlib-String.md +++ b/docs/api/melange/Stdlib-String.md @@ -1,7 +1,12 @@ + # Module `Stdlib.String` + Strings. + A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. + The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. + ``` positions 0 1 2 3 4 n-1 n +---+---+---+---+ +-----+ @@ -11,359 +16,465 @@ positions 0 1 2 3 4 n-1 n - An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. - A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. + **Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. + **Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + + ## Strings + ``` type t = string ``` The type for strings. + ``` val make : int -> char -> string ``` `make n c` is a string of length `n` with each index holding the character `c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val init : int -> (int -> char) -> string ``` `init n f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. since 4.02 ``` val empty : string ``` The empty string. + since 4.13 ``` val length : string -> int ``` `length s` is the length (number of bytes/characters) of `s`. + ``` val get : string -> int -> char ``` `get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. ``` val of_bytes : bytes -> string ``` Return a new string that contains the same bytes as the given byte sequence. + since 4.13 ``` val to_bytes : string -> bytes ``` Return a new byte sequence that contains the same bytes as the given string. + since 4.13 ``` val blit : string -> int -> bytes -> int -> int -> unit ``` Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. + + ## Concatenating + **Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. + ``` val concat : string -> string list -> string ``` `concat sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val cat : string -> string -> string ``` `cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. since 4.13 + ## Predicates and comparisons + ``` val equal : t -> t -> bool ``` `equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. + since 4.03 (4.05 in StringLabels) ``` val compare : t -> t -> int ``` `compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. + ``` val starts_with : prefix:string -> string -> bool ``` `starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + since 4.13 ``` val ends_with : suffix:string -> string -> bool ``` `ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + since 4.13 ``` val contains_from : string -> int -> char -> bool ``` `contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. ``` val rcontains_from : string -> int -> char -> bool ``` `rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. ``` val contains : string -> char -> bool ``` `contains s c` is [`String.contains_from`](./#val-contains_from)` s 0 c`. + + ## Extracting substrings + ``` val sub : string -> int -> int -> string ``` `sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. ``` val split_on_char : char -> string -> string list ``` `split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. + The function's result is specified by the following invariants: + - The list is not empty. - Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). - No string in the result contains the `sep` character. since 4.04 (4.05 in StringLabels) + ## Transforming + ``` val map : (char -> char) -> string -> string ``` `map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. + since 4.00 ``` val mapi : (int -> char -> char) -> string -> string ``` `mapi f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. + since 4.02 ``` val fold_left : ('acc -> char -> 'acc) -> 'acc -> string -> 'acc ``` `fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. + since 4.13 ``` val fold_right : (char -> 'acc -> 'acc) -> string -> 'acc -> 'acc ``` `fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. + since 4.13 ``` val for_all : (char -> bool) -> string -> bool ``` `for_all p s` checks if all characters in `s` satisfy the predicate `p`. + since 4.13 ``` val exists : (char -> bool) -> string -> bool ``` `exists p s` checks if at least one character of `s` satisfies the predicate `p`. + since 4.13 ``` val trim : string -> string ``` `trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. + since 4.00 ``` val escaped : string -> string ``` `escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. + All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). + The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val uppercase_ascii : string -> string ``` `uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) ``` val lowercase_ascii : string -> string ``` `lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) ``` val capitalize_ascii : string -> string ``` `capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) ``` val uncapitalize_ascii : string -> string ``` `uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) + ## Traversing + ``` val iter : (char -> unit) -> string -> unit ``` `iter f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. + ``` val iteri : (int -> char -> unit) -> string -> unit ``` `iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. + since 4.00 + ## Searching + ``` val index_from : string -> int -> char -> int ``` `index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. ``` 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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. since 4.05 ``` val rindex_from : string -> int -> char -> int ``` `rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. ``` val rindex_from_opt : string -> int -> char -> int option ``` `rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. since 4.05 ``` val index : string -> char -> int ``` `index s c` is [`String.index_from`](./#val-index_from)` s 0 c`. + ``` val index_opt : string -> char -> int option ``` `index_opt s c` is [`String.index_from_opt`](./#val-index_from_opt)` s 0 c`. + since 4.05 ``` val rindex : string -> char -> int ``` `rindex s c` is [`String.rindex_from`](./#val-rindex_from)` s (length s - 1) c`. + ``` val rindex_opt : string -> char -> int option ``` `rindex_opt s c` is [`String.rindex_from_opt`](./#val-rindex_from_opt)` s (length s - 1) c`. + since 4.05 + ## Strings and Sequences + ``` val to_seq : t -> char Seq.t ``` `to_seq s` is a sequence made of the string's characters in increasing order. + since 4.07 ``` val to_seqi : t -> (int * char) Seq.t ``` `to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. + since 4.07 ``` val of_seq : char Seq.t -> t ``` `of_seq s` is a string made of the sequence's characters. + since 4.07 + ## UTF decoding and validations + since 4.14 + ### UTF-8 + ``` 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`. + ``` val is_valid_utf_8 : t -> bool ``` `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + ### UTF-16BE + ``` 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`. + ``` val is_valid_utf_16be : t -> bool ``` `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + ### UTF-16LE + ``` 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`. + ``` val is_valid_utf_16le : t -> bool ``` `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + ## Binary decoding of integers + The functions in this section binary decode integers from strings. + All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. + Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + 32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + 8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. + ``` val get_uint8 : string -> int -> int ``` `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. + since 4.13 ``` val get_int8 : string -> int -> int ``` `get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. + since 4.13 ``` val get_uint16_ne : string -> int -> int ``` `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. + since 4.13 ``` val get_uint16_be : string -> int -> int ``` `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. + since 4.13 ``` val get_uint16_le : string -> int -> int ``` `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int16_ne : string -> int -> int ``` `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int16_be : string -> int -> int ``` `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int16_le : string -> int -> int ``` `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int32_ne : string -> int -> int32 ``` `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. + since 4.13 ``` val hash : t -> int ``` An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.0 ``` val seeded_hash : int -> t -> int ``` A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.0 ``` val get_int32_be : string -> int -> int32 ``` `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. + since 4.13 ``` val get_int32_le : string -> int -> int32 ``` `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. + since 4.13 ``` val get_int64_ne : string -> int -> int64 ``` `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. + since 4.13 ``` val get_int64_be : string -> int -> int64 ``` `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. + since 4.13 ``` val get_int64_le : string -> int -> int64 ``` `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. + since 4.13 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-StringLabels.md b/docs/api/melange/Stdlib-StringLabels.md index 13fd18a72..c969a00a3 100644 --- a/docs/api/melange/Stdlib-StringLabels.md +++ b/docs/api/melange/Stdlib-StringLabels.md @@ -1,7 +1,12 @@ + # Module `Stdlib.StringLabels` + Strings. + A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. + The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. + ``` positions 0 1 2 3 4 n-1 n +---+---+---+---+ +-----+ @@ -11,48 +16,62 @@ positions 0 1 2 3 4 n-1 n - An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. - A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. + **Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. + **Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. + The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + + ## Strings + ``` type t = string ``` The type for strings. + ``` val make : int -> char -> string ``` `make n c` is a string of length `n` with each index holding the character `c`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. ``` val init : int -> f:(int -> char) -> string ``` `init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. since 4.02 ``` val empty : string ``` The empty string. + since 4.13 ``` val length : string -> int ``` `length s` is the length (number of bytes/characters) of `s`. + ``` val get : string -> int -> char ``` `get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. ``` val of_bytes : bytes -> string ``` Return a new string that contains the same bytes as the given byte sequence. + since 4.13 ``` val to_bytes : string -> bytes ``` Return a new byte sequence that contains the same bytes as the given string. + since 4.13 ``` val blit : @@ -64,312 +83,404 @@ val blit : unit ``` Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. + + ## Concatenating + **Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. + ``` val concat : sep:string -> string list -> string ``` `concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val cat : string -> string -> string ``` `cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. since 4.13 + ## Predicates and comparisons + ``` val equal : t -> t -> bool ``` `equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. + since 4.03 (4.05 in StringLabels) ``` val compare : t -> t -> int ``` `compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. + ``` val starts_with : prefix:string -> string -> bool ``` `starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + since 4.13 ``` val ends_with : suffix:string -> string -> bool ``` `ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + since 4.13 ``` val contains_from : string -> int -> char -> bool ``` `contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. ``` val rcontains_from : string -> int -> char -> bool ``` `rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. ``` val contains : string -> char -> bool ``` `contains s c` is [`String.contains_from`](./Stdlib-String.md#val-contains_from)` s 0 c`. + + ## Extracting substrings + ``` val sub : string -> pos:int -> len:int -> string ``` `sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. ``` val split_on_char : sep:char -> string -> string list ``` `split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. + The function's result is specified by the following invariants: + - The list is not empty. - Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). - No string in the result contains the `sep` character. since 4.04 (4.05 in StringLabels) + ## Transforming + ``` val map : f:(char -> char) -> string -> string ``` `map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. + since 4.00 ``` val mapi : f:(int -> char -> char) -> string -> string ``` `mapi ~f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. + since 4.02 ``` val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> string -> 'acc ``` `fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. + since 4.13 ``` val fold_right : f:(char -> 'acc -> 'acc) -> string -> init:'acc -> 'acc ``` `fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. + since 4.13 ``` val for_all : f:(char -> bool) -> string -> bool ``` `for_all p s` checks if all characters in `s` satisfy the predicate `p`. + since 4.13 ``` val exists : f:(char -> bool) -> string -> bool ``` `exists p s` checks if at least one character of `s` satisfies the predicate `p`. + since 4.13 ``` val trim : string -> string ``` `trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. + since 4.00 ``` val escaped : string -> string ``` `escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. + All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). + The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. ``` val uppercase_ascii : string -> string ``` `uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) ``` val lowercase_ascii : string -> string ``` `lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) ``` val capitalize_ascii : string -> string ``` `capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) ``` val uncapitalize_ascii : string -> string ``` `uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. + since 4.03 (4.05 in StringLabels) + ## Traversing + ``` val iter : f:(char -> unit) -> string -> unit ``` `iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. + ``` val iteri : f:(int -> char -> unit) -> string -> unit ``` `iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. + since 4.00 + ## Searching + ``` val index_from : string -> int -> char -> int ``` `index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. ``` 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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. since 4.05 ``` val rindex_from : string -> int -> char -> int ``` `rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. ``` val rindex_from_opt : string -> int -> char -> int option ``` `rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. since 4.05 ``` val index : string -> char -> int ``` `index s c` is [`String.index_from`](./Stdlib-String.md#val-index_from)` s 0 c`. + ``` val index_opt : string -> char -> int option ``` `index_opt s c` is [`String.index_from_opt`](./Stdlib-String.md#val-index_from_opt)` s 0 c`. + since 4.05 ``` val rindex : string -> char -> int ``` `rindex s c` is [`String.rindex_from`](./Stdlib-String.md#val-rindex_from)` s (length s - 1) c`. + ``` val rindex_opt : string -> char -> int option ``` `rindex_opt s c` is [`String.rindex_from_opt`](./Stdlib-String.md#val-rindex_from_opt)` s (length s - 1) c`. + since 4.05 + ## Strings and Sequences + ``` val to_seq : t -> char Seq.t ``` `to_seq s` is a sequence made of the string's characters in increasing order. + since 4.07 ``` val to_seqi : t -> (int * char) Seq.t ``` `to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. + since 4.07 ``` val of_seq : char Seq.t -> t ``` `of_seq s` is a string made of the sequence's characters. + since 4.07 + ## UTF decoding and validations + since 4.14 + ### UTF-8 + ``` 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`. + ``` val is_valid_utf_8 : t -> bool ``` `is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + ### UTF-16BE + ``` 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`. + ``` val is_valid_utf_16be : t -> bool ``` `is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + ### UTF-16LE + ``` 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`. + ``` val is_valid_utf_16le : t -> bool ``` `is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + ## Binary decoding of integers + The functions in this section binary decode integers from strings. + All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. + Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + 32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + 8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. + ``` val get_uint8 : string -> int -> int ``` `get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. + since 4.13 ``` val get_int8 : string -> int -> int ``` `get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. + since 4.13 ``` val get_uint16_ne : string -> int -> int ``` `get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. + since 4.13 ``` val get_uint16_be : string -> int -> int ``` `get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. + since 4.13 ``` val get_uint16_le : string -> int -> int ``` `get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int16_ne : string -> int -> int ``` `get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int16_be : string -> int -> int ``` `get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int16_le : string -> int -> int ``` `get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. + since 4.13 ``` val get_int32_ne : string -> int -> int32 ``` `get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. + since 4.13 ``` val hash : t -> int ``` An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.0 ``` val seeded_hash : int -> t -> int ``` A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.0 ``` val get_int32_be : string -> int -> int32 ``` `get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. + since 4.13 ``` val get_int32_le : string -> int -> int32 ``` `get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. + since 4.13 ``` val get_int64_ne : string -> int -> int64 ``` `get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. + since 4.13 ``` val get_int64_be : string -> int -> int64 ``` `get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. + since 4.13 ``` val get_int64_le : string -> int -> int64 ``` `get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. + since 4.13 \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md index de6fd038a..8c2c620d7 100644 --- a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md +++ b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md @@ -1,4 +1,6 @@ + # Parameter `Make.Immediate` + ``` type t ``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md index 7bf3d87cb..08e19ba97 100644 --- a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md +++ b/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md @@ -1,4 +1,6 @@ + # Parameter `Make.Non_immediate` + ``` type t ``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make.md b/docs/api/melange/Stdlib-Sys-Immediate64-Make.md index 8a6519de3..deef830ee 100644 --- a/docs/api/melange/Stdlib-Sys-Immediate64-Make.md +++ b/docs/api/melange/Stdlib-Sys-Immediate64-Make.md @@ -1,12 +1,18 @@ + # Module `Immediate64.Make` + + ## Parameters + ``` module Immediate : Immediate ``` ``` module Non_immediate : Non_immediate ``` + ## Signature + ``` type t ``` diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md index fafc06698..f63bbba0a 100644 --- a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md +++ b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md @@ -1,4 +1,6 @@ + # Module type `Immediate64.Immediate` + ``` type t ``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md index 44ae90f2d..d4d3814fd 100644 --- a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md +++ b/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md @@ -1,4 +1,6 @@ + # Module type `Immediate64.Non_immediate` + ``` type t ``` \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Sys-Immediate64.md b/docs/api/melange/Stdlib-Sys-Immediate64.md index f70c82e15..79e8eb8ca 100644 --- a/docs/api/melange/Stdlib-Sys-Immediate64.md +++ b/docs/api/melange/Stdlib-Sys-Immediate64.md @@ -1,5 +1,8 @@ + # Module `Sys.Immediate64` + This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. + since 4.10 ``` module type Non_immediate = sig ... end diff --git a/docs/api/melange/Stdlib-Sys.md b/docs/api/melange/Stdlib-Sys.md index 2d898a9cf..af5584b69 100644 --- a/docs/api/melange/Stdlib-Sys.md +++ b/docs/api/melange/Stdlib-Sys.md @@ -1,90 +1,114 @@ + # Module `Stdlib.Sys` + System interface. + Every function in this module raises `Sys_error` with an informative message when the underlying system call signal an error. + ``` val argv : string array ``` The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program. + ``` val executable_name : string ``` The name of the file containing the executable currently running. This name may be absolute or relative to the current directory, depending on the platform and whether the program was compiled to bytecode or a native executable. + ``` val file_exists : string -> bool ``` Test if a file with the given name exists. + ``` val is_directory : string -> bool ``` Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file. + raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. since 3.10 ``` val is_regular_file : string -> bool ``` Returns `true` if the given name refers to a regular file, `false` if it refers to another kind of file. + raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. since 5.1 ``` val remove : string -> unit ``` Remove the given file name from the file system. + ``` val rename : string -> string -> unit ``` Rename a file or directory. `rename oldpath newpath` renames the file or directory called `oldpath`, giving it `newpath` as its new name, moving it between (parent) directories if needed. If a file named `newpath` already exists, its contents will be replaced with those of `oldpath`. Depending on the operating system, the metadata (permissions, owner, etc) of `newpath` can either be preserved or be replaced by those of `oldpath`. + since 4.06 concerning the "replace existing file" behavior ``` val getenv : string -> string ``` Return the value associated to a variable in the process environment. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if the variable is unbound. ``` val getenv_opt : string -> string option ``` Return the value associated to a variable in the process environment or `None` if the variable is unbound. + since 4.05 ``` val command : string -> int ``` Execute the given shell command and return its exit code. + The argument of [`Sys.command`](./#val-command) is generally the name of a command followed by zero, one or several arguments, separated by whitespace. The given argument is interpreted by a shell: either the Windows shell `cmd.exe` for the Win32 ports of OCaml, or the POSIX shell `sh` for other ports. It can contain shell builtin commands such as `echo`, and also special characters such as file redirections `>` and `<`, which will be honored by the shell. + Conversely, whitespace or special shell characters occurring in command names or in their arguments must be quoted or escaped so that the shell does not interpret them. The quoting rules vary between the POSIX shell and the Windows shell. The [`Filename.quote_command`](./Stdlib-Filename.md#val-quote_command) performs the appropriate quoting given a command name, a list of arguments, and optional file redirections. + ``` val time : unit -> float ``` Return the processor time, in seconds, used by the program since the beginning of execution. + ``` val chdir : string -> unit ``` Change the current working directory of the process. + ``` val mkdir : string -> int -> unit ``` Create a directory with the given permissions. + since 4.12 ``` val rmdir : string -> unit ``` Remove an empty directory. + since 4.12 ``` val getcwd : unit -> string ``` Return the current working directory of the process. + ``` val readdir : string -> string array ``` Return the names of all files present in the given directory. Names denoting the current directory and the parent directory (`"."` and `".."` in Unix) are not returned. Each string in the result is a file name rather than a complete path. There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order. + ``` val interactive : bool ref ``` This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`. + alert unsynchronized\_access The interactive status is a mutable global state. ``` val os_type : string ``` Operating system currently executing the OCaml program. One of + - `"Unix"` (for all Unix versions, including Linux and Mac OS X), - `"Win32"` (for MS-Windows, OCaml compiled with MSVC++ or MinGW-w64), - `"Cygwin"` (for MS-Windows, OCaml compiled with Cygwin). @@ -104,64 +128,79 @@ type backend_type = ``` Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript. + since 4.04 ``` val backend_type : backend_type ``` Backend type currently executing the OCaml program. + since 4.04 ``` val unix : bool ``` True if `Sys.os_type = "Unix"`. + since 4.01 ``` val win32 : bool ``` True if `Sys.os_type = "Win32"`. + since 4.01 ``` val cygwin : bool ``` True if `Sys.os_type = "Cygwin"`. + since 4.01 ``` val word_size : int ``` Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64. + ``` val int_size : int ``` Size of `int`, in bits. It is 31 (resp. 63) when using OCaml on a 32-bit (resp. 64-bit) platform. It may differ for other implementations, e.g. it can be 32 bits when compiling to JavaScript. + since 4.03 ``` val big_endian : bool ``` Whether the machine currently executing the Caml program is big-endian. + since 4.00 ``` val max_string_length : int ``` Maximum length of strings and byte sequences. + ``` val max_array_length : int ``` Maximum length of a normal array (i.e. any array whose elements are not of type `float`). The maximum length of a `float array` is `max_floatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with `--disable-flat-float-array`. + ``` val max_floatarray_length : int ``` Maximum length of a floatarray. This is also the maximum length of a `float array` when OCaml is configured with `--enable-flat-float-array`. + ``` val runtime_variant : unit -> string ``` Return the name of the runtime variant the program is running on. This is normally the argument given to `-runtime-variant` at compile time, but for byte-code it can be changed after compilation. + since 4.03 ``` val runtime_parameters : unit -> string ``` Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable. + since 4.03 + ## Signal handling + ``` type signal_behavior = ``` @@ -178,6 +217,7 @@ type signal_behavior = ``` What to do when receiving a signal: + - `Signal_default`: take the default behavior (usually: abort the program) - `Signal_ignore`: ignore the signal - `Signal_handle f`: call function `f`, giving it the signal number as argument. @@ -185,147 +225,184 @@ What to do when receiving a signal: val signal : int -> signal_behavior -> signal_behavior ``` Set the behavior of the system on receipt of a given signal. The first argument is the signal number. Return the behavior previously associated with the signal. If the signal number is invalid (or not available on your system), an `Invalid_argument` exception is raised. + ``` val set_signal : int -> signal_behavior -> unit ``` Same as [`Sys.signal`](./#val-signal) but return value is ignored. + + ### Signal numbers for the standard POSIX signals. + ``` val sigabrt : int ``` Abnormal termination + ``` val sigalrm : int ``` Timeout + ``` val sigfpe : int ``` Arithmetic exception + ``` val sighup : int ``` Hangup on controlling terminal + ``` val sigill : int ``` Invalid hardware instruction + ``` val sigint : int ``` Interactive interrupt (ctrl-C) + ``` val sigkill : int ``` Termination (cannot be ignored) + ``` val sigpipe : int ``` Broken pipe + ``` val sigquit : int ``` Interactive termination + ``` val sigsegv : int ``` Invalid memory reference + ``` val sigterm : int ``` Termination + ``` val sigusr1 : int ``` Application-defined signal 1 + ``` val sigusr2 : int ``` Application-defined signal 2 + ``` val sigchld : int ``` Child process terminated + ``` val sigcont : int ``` Continue + ``` val sigstop : int ``` Stop + ``` val sigtstp : int ``` Interactive stop + ``` val sigttin : int ``` Terminal read from background process + ``` val sigttou : int ``` Terminal write from background process + ``` val sigvtalrm : int ``` Timeout in virtual time + ``` val sigprof : int ``` Profiling interrupt + ``` val sigbus : int ``` Bus error + since 4.03 ``` val sigpoll : int ``` Pollable event + since 4.03 ``` val sigsys : int ``` Bad argument to routine + since 4.03 ``` val sigtrap : int ``` Trace/breakpoint trap + since 4.03 ``` val sigurg : int ``` Urgent condition on socket + since 4.03 ``` val sigxcpu : int ``` Timeout in cpu time + since 4.03 ``` val sigxfsz : int ``` File size limit exceeded + since 4.03 ``` exception Break ``` Exception raised on interactive interrupt if [`Sys.catch_break`](./#val-catch_break) is enabled. + ``` val catch_break : bool -> unit ``` `catch_break` governs whether interactive interrupt (ctrl-C) terminates the program or raises the `Break` exception. Call `catch_break true` to enable raising `Break`, and `catch_break false` to let the system terminate the program on user interrupt. + Inside multi-threaded programs, the `Break` exception will arise in any one of the active threads, and will keep arising on further interactive interrupt until all threads are terminated. Use signal masks from `Thread.sigmask` to direct the interrupt towards a specific thread. + ``` val ocaml_version : string ``` `ocaml_version` is the version of OCaml. It is a string of the form `"major.minor[.patchlevel][(+|~)additional-info]"`, where `major`, `minor`, and `patchlevel` are integers, and `additional-info` is an arbitrary string. The `[.patchlevel]` part was absent before version 3.08.0 and became mandatory from 3.08.0 onwards. The `[(+|~)additional-info]` part may be absent. + ``` val development_version : bool ``` `true` if this is a development version, `false` otherwise. + since 4.14 ``` type extra_prefix = @@ -359,26 +436,34 @@ since 4.14 val ocaml_release : ocaml_release_info ``` `ocaml_release` is the version of OCaml. + since 4.14 ``` val enable_runtime_warnings : bool -> unit ``` Control whether the OCaml runtime system can emit warnings on stderr. Currently, the only supported warning is triggered when a channel created by `open_*` functions is finalized without being closed. Runtime warnings are disabled by default. + since 4.03 alert unsynchronized\_access The status of runtime warnings is a mutable global state. ``` val runtime_warnings_enabled : unit -> bool ``` Return whether runtime warnings are currently enabled. + since 4.03 alert unsynchronized\_access The status of runtime warnings is a mutable global state. + ## Optimization + ``` val opaque_identity : 'a -> 'a ``` For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function. + At runtime, `opaque_identity` disappears altogether. However, it does prevent the argument from being garbage collected until the location where the call would have occurred. + A typical use of this function is to prevent pure computations from being optimized away in benchmarking loops. For example: + ```ocaml for _round = 1 to 100_000 do ignore (Sys.opaque_identity (my_pure_computation ())) @@ -388,4 +473,4 @@ since 4.03 ``` module Immediate64 : sig ... end ``` -This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. \ No newline at end of file +This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. diff --git a/docs/api/melange/Stdlib-Type-Id.md b/docs/api/melange/Stdlib-Type-Id.md index 98f28171f..39402a663 100644 --- a/docs/api/melange/Stdlib-Type-Id.md +++ b/docs/api/melange/Stdlib-Type-Id.md @@ -1,28 +1,42 @@ + # Module `Type.Id` + Type identifiers. + A type identifier is a value that denotes a type. Given two type identifiers, they can be tested for [equality](./#val-provably_equal) to prove they denote the same type. Note that: + - Unequal identifiers do not imply unequal types: a given type can be denoted by more than one identifier. - Type identifiers can be marshalled, but they get a new, distinct, identity on unmarshalling, so the equalities are lost. See an [example](./#example) of use. + + ## Type identifiers + ``` type !'a t ``` The type for identifiers for type `'a`. + ``` val make : unit -> 'a t ``` `make ()` is a new type identifier. + ``` val uid : 'a t -> int ``` `uid id` is a runtime unique identifier for `id`. + ``` val provably_equal : 'a t -> 'b t -> ('a, 'b) eq option ``` `provably_equal i0 i1` is `Some Equal` if identifier `i0` is equal to `i1` and `None` otherwise. + + ## Example + The following shows how type identifiers can be used to implement a simple heterogeneous key-value dictionary. In contrast to [`Stdlib.Map`](./Stdlib-Map.md) values whose keys map to a single, homogeneous type of values, this dictionary can associate a different type of value to each key. + ```ocaml (** Heterogeneous dictionaries. *) module Dict : sig diff --git a/docs/api/melange/Stdlib-Type.md b/docs/api/melange/Stdlib-Type.md index 9b35f29fc..0a071fda8 100644 --- a/docs/api/melange/Stdlib-Type.md +++ b/docs/api/melange/Stdlib-Type.md @@ -1,7 +1,12 @@ + # Module `Stdlib.Type` + Type introspection. + since 5.1 + ## Type equality witness + ``` type (_, _) eq = ``` @@ -12,14 +17,20 @@ type (_, _) eq = ``` The purpose of `eq` is to represent type equalities that may not otherwise be known by the type checker (e.g. because they may depend on dynamic data). + A value of type `(a, b) eq` represents the fact that types `a` and `b` are equal. + If one has a value `eq : (a, b) eq` that proves types `a` and `b` are equal, one can use it to convert a value of type `a` to a value of type `b` by pattern matching on `Equal`: + ```ocaml let cast (type a) (type b) (Equal : (a, b) Type.eq) (a : a) : b = a ``` At runtime, this function simply returns its second argument unchanged. + + ## Type identifiers + ``` module Id : sig ... end ``` -Type identifiers. \ No newline at end of file +Type identifiers. diff --git a/docs/api/melange/Stdlib-Uchar.md b/docs/api/melange/Stdlib-Uchar.md index 050ef27cb..a90cfee5e 100644 --- a/docs/api/melange/Stdlib-Uchar.md +++ b/docs/api/melange/Stdlib-Uchar.md @@ -1,114 +1,144 @@ + # Module `Stdlib.Uchar` + Unicode characters. + since 4.03 ``` type t ``` The type for Unicode characters. + A value of this type represents a Unicode [scalar value](http://unicode.org/glossary/#unicode_scalar_value) which is an integer in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`. + ``` val min : t ``` `min` is U+0000. + ``` val max : t ``` `max` is U+10FFFF. + ``` val bom : t ``` `bom` is U+FEFF, the [byte order mark](http://unicode.org/glossary/#byte_order_mark) (BOM) character. + since 4.06 ``` val rep : t ``` `rep` is U+FFFD, the [replacement](http://unicode.org/glossary/#replacement_character) character. + since 4.06 ``` val succ : t -> t ``` `succ u` is the scalar value after `u` in the set of Unicode scalar values. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is max. ``` val pred : t -> t ``` `pred u` is the scalar value before `u` in the set of Unicode scalar values. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is min. ``` val is_valid : int -> bool ``` `is_valid n` is `true` if and only if `n` is a Unicode scalar value (i.e. in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`). + ``` val of_int : int -> t ``` `of_int i` is `i` as a Unicode character. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i does not satisfy is\_valid. ``` val to_int : t -> int ``` `to_int u` is `u` as an integer. + ``` val is_char : t -> bool ``` `is_char u` is `true` if and only if `u` is a latin1 OCaml character. + ``` val of_char : char -> t ``` `of_char c` is `c` as a Unicode character. + ``` val to_char : t -> char ``` `to_char u` is `u` as an OCaml latin1 character. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u does not satisfy is\_char. ``` val equal : t -> t -> bool ``` `equal u u'` is `u = u'`. + ``` val compare : t -> t -> int ``` `compare u u'` is `Stdlib.compare u u'`. + ``` val seeded_hash : int -> t -> int ``` `seeded_hash seed u` A seeded hash function with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + since 5.3 ``` val hash : t -> int ``` An unseeded hash function with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + since 5.3 + ## UTF codecs tools + since 4.14 ``` type utf_decode ``` The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt. + ``` val utf_decode_is_valid : utf_decode -> bool ``` `utf_decode_is_valid d` is `true` if and only if `d` holds a valid decode. + ``` val utf_decode_uchar : utf_decode -> t ``` `utf_decode_uchar d` is the Unicode character decoded by `d` if `utf_decode_is_valid d` is `true` and [`Uchar.rep`](./#val-rep) otherwise. + ``` val utf_decode_length : utf_decode -> int ``` `utf_decode_length d` is the number of elements from the source that were consumed by the decode `d`. This is always strictly positive and smaller or equal to `4`. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes. + ``` val utf_decode : int -> t -> utf_decode ``` `utf_decode n u` is a valid UTF decode for `u` that consumed `n` elements from the source for decoding. `n` must be positive and smaller or equal to `4` (this is not checked by the module). + ``` val utf_decode_invalid : int -> utf_decode ``` `utf_decode_invalid n` is an invalid UTF decode that consumed `n` elements from the source to error. `n` must be positive and smaller or equal to `4` (this is not checked by the module). The resulting decode has [`rep`](./#val-rep) as the decoded Unicode character. + ``` val utf_8_byte_length : t -> int ``` `utf_8_byte_length u` is the number of bytes needed to encode `u` in UTF-8. + ``` val utf_16_byte_length : t -> int ``` -`utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16. \ No newline at end of file +`utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16. diff --git a/docs/api/melange/Stdlib-Unit.md b/docs/api/melange/Stdlib-Unit.md index bdb64c57f..50428889e 100644 --- a/docs/api/melange/Stdlib-Unit.md +++ b/docs/api/melange/Stdlib-Unit.md @@ -1,7 +1,12 @@ + # Module `Stdlib.Unit` + Unit values. + since 4.08 + ## The unit type + ``` type t = unit = ``` @@ -12,16 +17,20 @@ type t = unit = ``` The unit type. + The constructor `()` is included here so that it has a path, but it is not intended to be used in user-defined data types. + ``` val equal : t -> t -> bool ``` `equal u1 u2` is `true`. + ``` val compare : t -> t -> int ``` `compare u1 u2` is `0`. + ``` val to_string : t -> string ``` -`to_string b` is `"()"`. \ No newline at end of file +`to_string b` is `"()"`. diff --git a/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md b/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md index 492b57f0f..80efdc53c 100644 --- a/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md +++ b/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md @@ -1,16 +1,21 @@ + # Parameter `Make.H` + ``` type t ``` The type of the hashtable keys. + ``` val equal : t -> t -> bool ``` The equality predicate used to compare keys. + ``` val hash : t -> int ``` A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + - (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) - (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly - (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/melange/Stdlib-Weak-Make.md b/docs/api/melange/Stdlib-Weak-Make.md index 9ba485f93..a9786f098 100644 --- a/docs/api/melange/Stdlib-Weak-Make.md +++ b/docs/api/melange/Stdlib-Weak-Make.md @@ -1,69 +1,90 @@ + # Module `Weak.Make` + Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. + + ## Parameters + ``` module H : Hashtbl.HashedType ``` + ## Signature + ``` type data = H.t ``` The type of the elements stored in the table. + ``` type t ``` The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. + ``` val create : int -> t ``` `create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. + ``` val clear : t -> unit ``` Remove all elements from the table. + ``` val merge : t -> data -> data ``` `merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. + ``` val add : t -> data -> unit ``` `add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. + ``` val remove : t -> data -> unit ``` `remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. + ``` val find : t -> data -> data ``` `find t x` returns an instance of `x` found in `t`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. ``` val find_opt : t -> data -> data option ``` `find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. + since 4.05 ``` val find_all : t -> data -> data list ``` `find_all t x` returns a list of all the instances of `x` found in `t`. + ``` val mem : t -> data -> bool ``` `mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. + ``` val iter : (data -> unit) -> t -> unit ``` `iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + ``` val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc ``` `fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + ``` val count : t -> int ``` Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. + ``` val stats : t -> int * int * int * int * int * int ``` -Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. \ No newline at end of file +Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/melange/Stdlib-Weak-module-type-S.md b/docs/api/melange/Stdlib-Weak-module-type-S.md index 526daebd0..22f814459 100644 --- a/docs/api/melange/Stdlib-Weak-module-type-S.md +++ b/docs/api/melange/Stdlib-Weak-module-type-S.md @@ -1,64 +1,81 @@ + # Module type `Weak.S` + The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). + ``` type data ``` The type of the elements stored in the table. + ``` type t ``` The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. + ``` val create : int -> t ``` `create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. + ``` val clear : t -> unit ``` Remove all elements from the table. + ``` val merge : t -> data -> data ``` `merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. + ``` val add : t -> data -> unit ``` `add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. + ``` val remove : t -> data -> unit ``` `remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. + ``` val find : t -> data -> data ``` `find t x` returns an instance of `x` found in `t`. + raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. ``` val find_opt : t -> data -> data option ``` `find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. + since 4.05 ``` val find_all : t -> data -> data list ``` `find_all t x` returns a list of all the instances of `x` found in `t`. + ``` val mem : t -> data -> bool ``` `mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. + ``` val iter : (data -> unit) -> t -> unit ``` `iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + ``` val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc ``` `fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + ``` val count : t -> int ``` Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. + ``` val stats : t -> int * int * int * int * int * int ``` -Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. \ No newline at end of file +Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/melange/Stdlib-Weak.md b/docs/api/melange/Stdlib-Weak.md index c1c3c0d4e..98afcfae4 100644 --- a/docs/api/melange/Stdlib-Weak.md +++ b/docs/api/melange/Stdlib-Weak.md @@ -1,64 +1,88 @@ + # Module `Stdlib.Weak` + Arrays of weak pointers and hash sets of weak pointers. + + ## Low-level functions + ``` type !'a t ``` The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program. Note that finalisation functions are run before the weak pointers are erased, because the finalisation functions can make values alive again (before 4.03 the finalisation functions were run after). + A weak pointer is said to be full if it points to a value, empty if the value was erased by the GC. + Notes: + - Integers are not allocated and cannot be stored in weak arrays. - Weak arrays cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) nor the functions of the [`Marshal`](./Stdlib-Marshal.md) module. ``` val create : int -> 'a t ``` `Weak.create n` returns a new weak array of length `n`. All the pointers are initially empty. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not comprised between zero and Obj.Ephemeron.max\_ephe\_length (limits included). ``` val length : 'a t -> int ``` `Weak.length ar` returns the length (number of elements) of `ar`. + ``` val set : 'a t -> int -> 'a option -> unit ``` `Weak.set ar n (Some el)` sets the `n`th cell of `ar` to be a (full) pointer to `el`; `Weak.set ar n None` sets the `n`th cell of `ar` to empty. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. ``` val get : 'a t -> int -> 'a option ``` `Weak.get ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is the value) if it is full. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. ``` val get_copy : 'a t -> int -> 'a option ``` `Weak.get_copy ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is a (shallow) copy of the value) if it is full. In addition to pitfalls with mutable values, the interesting difference with `get` is that `get_copy` does not prevent the incremental GC from erasing the value in its current cycle (`get` may delay the erasure to the next GC cycle). + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. If the element is a custom block it is not copied. + ``` val check : 'a t -> int -> bool ``` `Weak.check ar n` returns `true` if the `n`th cell of `ar` is full, `false` if it is empty. Note that even if `Weak.check ar n` returns `true`, a subsequent [`Weak.get`](./#val-get)` ar n` can return `None`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. ``` val fill : 'a t -> int -> int -> 'a option -> unit ``` `Weak.fill ar ofs len el` sets to `el` all pointers of `ar` from `ofs` to `ofs + len - 1`. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid subarray of ar. ``` val blit : 'a t -> int -> 'a t -> int -> int -> unit ``` `Weak.blit ar1 off1 ar2 off2 len` copies `len` weak pointers from `ar1` (starting at `off1`) to `ar2` (starting at `off2`). It works correctly even if `ar1` and `ar2` are the same. + raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off1 and len do not designate a valid subarray of ar1, or if off2 and len do not designate a valid subarray of ar2. + ## Weak hash sets + A weak hash set is a hashed set of values. Each value may magically disappear from the set when it is not used by the rest of the program any more. This is normally used to share data structures without inducing memory leaks. Weak hash sets are defined on values from a [`Hashtbl.HashedType`](./Stdlib-Hashtbl-module-type-HashedType.md) module; the `equal` relation and `hash` function are taken from that module. We will say that `v` is an instance of `x` if `equal x v` is `true`. + The `equal` relation must be able to work on a shallow copy of the values and give the same result as with the values themselves. + **Unsynchronized accesses** + Unsynchronized accesses to weak hash sets are a programming error. Unsynchronized accesses to a weak hash set may lead to an invalid weak hash set state. Thus, concurrent accesses to weak hash sets must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + ``` module type S = sig ... end ``` The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). + ``` module Make (H : Hashtbl.HashedType) : S with type data = H.t ``` -Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. \ No newline at end of file +Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. diff --git a/docs/api/melange/Stdlib.md b/docs/api/melange/Stdlib.md index 0a260bb84..ba13a16e8 100644 --- a/docs/api/melange/Stdlib.md +++ b/docs/api/melange/Stdlib.md @@ -1,109 +1,145 @@ + # Module `Stdlib` + The OCaml Standard library. + This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by `Stdlib`. + In particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the [standard library modules](./#modules). + + ## Exceptions + ``` val raise : exn -> 'a ``` Raise the given exception value + ``` val raise_notrace : exn -> 'a ``` A faster version `raise` which does not record the backtrace. + since 4.02 ``` val invalid_arg : string -> 'a ``` Raise exception `Invalid_argument` with the given string. + ``` val failwith : string -> 'a ``` Raise exception `Failure` with the given string. + ``` exception Exit ``` The `Exit` exception is not raised by any library function. It is provided for use in your programs. + ``` exception Match_failure of string * int * int ``` Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number). + ``` exception Assert_failure of string * int * int ``` Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number). + ``` exception Invalid_argument of string ``` Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it. + ``` exception Failure of string ``` Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure \_ instead). + ``` exception Not_found ``` Exception raised by search functions when the desired object could not be found. + ``` exception Out_of_memory ``` Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.) + ``` exception Stack_overflow ``` Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program. + Before 4.10, it was not fully implemented by the native-code compiler. + ``` exception Sys_error of string ``` Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys\_error \_ instead). + ``` exception End_of_file ``` Exception raised by input functions to signal that the end of file has been reached. + ``` exception Division_by_zero ``` Exception raised by integer division and remainder operations when their second argument is zero. + ``` exception Sys_blocked_io ``` A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel. + ``` exception Undefined_recursive_module of string * int * int ``` Exception raised when an ill-founded recursive module definition is evaluated. The arguments are the location of the definition in the source code (file name, line number, column number). + + ## Comparisons + ``` val (=) : 'a -> 'a -> bool ``` `e1 = e2` tests for structural equality of `e1` and `e2`. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises `Invalid_argument`. Equality between cyclic data structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (<>) : 'a -> 'a -> bool ``` Negation of [`Stdlib.(=)`](./#val-\(=\)). Left-associative operator, see `Ocaml_operators` for more information. + ``` val (<) : 'a -> 'a -> bool ``` See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. + ``` val (>) : 'a -> 'a -> bool ``` See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. + ``` val (<=) : 'a -> 'a -> bool ``` See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. + ``` val (>=) : 'a -> 'a -> bool ``` Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with `( = )`. As in the case of `( = )`, mutable structures are compared by contents. Comparison between functional values raises `Invalid_argument`. Comparison between cyclic structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. + ``` val compare : 'a -> 'a -> int ``` `compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. The ordering implemented by `compare` is compatible with the comparison predicates `=`, `<` and `>` defined above, with one difference on the treatment of the float value [`Stdlib.nan`](./#val-nan). Namely, the comparison predicates treat `nan` as different from any other float value, including itself; while `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. + `compare` applied to functional values may raise `Invalid_argument`. `compare` applied to cyclic structures may not terminate. + The `compare` function can be used as the comparison function required by the [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md) functors, as well as the [`List.sort`](./Stdlib-List.md#val-sort) and [`Array.sort`](./Stdlib-Array.md#val-sort) functions. + ``` val min : 'a -> 'a -> 'a ``` @@ -114,336 +150,426 @@ val max : 'a -> 'a -> 'a val (==) : 'a -> 'a -> bool ``` `e1 == e2` tests for physical equality of `e1` and `e2`. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, `e1 == e2` is true if and only if physical modification of `e1` also affects `e2`. On non-mutable types, the behavior of `( == )` is implementation-dependent; however, it is guaranteed that `e1 == e2` implies `compare e1 e2 = 0`. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (!=) : 'a -> 'a -> bool ``` Negation of [`Stdlib.(==)`](./#val-\(==\)). Left-associative operator, see `Ocaml_operators` for more information. + + ## Boolean operations + ``` val not : bool -> bool ``` The boolean negation. + ``` val (&&) : bool -> bool -> bool ``` The boolean 'and'. Evaluation is sequential, left-to-right: in `e1 && e2`, `e1` is evaluated first, and if it returns `false`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. + ``` val (||) : bool -> bool -> bool ``` The boolean 'or'. Evaluation is sequential, left-to-right: in `e1 || e2`, `e1` is evaluated first, and if it returns `true`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. + + ## Debugging + ``` val __LOC__ : string ``` `__LOC__` returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". + since 4.02 ``` val __FILE__ : string ``` `__FILE__` returns the name of the file currently being parsed by the compiler. + since 4.02 ``` val __LINE__ : int ``` `__LINE__` returns the line number at which this expression appears in the file currently being parsed by the compiler. + since 4.02 ``` val __MODULE__ : string ``` `__MODULE__` returns the module name of the file being parsed by the compiler. + since 4.02 ``` val __POS__ : string * int * int * int ``` `__POS__` returns a tuple `(file,lnum,cnum,enum)`, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. + since 4.02 ``` val __FUNCTION__ : string ``` `__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes. + since 4.12 ``` val __LOC_OF__ : 'a -> string * 'a ``` `__LOC_OF__ expr` returns a pair `(loc, expr)` where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". + since 4.02 ``` val __LINE_OF__ : 'a -> int * 'a ``` `__LINE_OF__ expr` returns a pair `(line, expr)`, where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler. + since 4.02 ``` val __POS_OF__ : 'a -> (string * int * int * int) * 'a ``` `__POS_OF__ expr` returns a pair `(loc,expr)`, where `loc` is a tuple `(file,lnum,cnum,enum)` corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. + since 4.02 + ## Composition operators + ``` val (|>) : 'a -> ('a -> 'b) -> 'b ``` Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. Left-associative operator, see `Ocaml_operators` for more information. + since 4.01 ``` val (@@) : ('a -> 'b) -> 'a -> 'b ``` Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. Right-associative operator, see `Ocaml_operators` for more information. + since 4.01 + ## Integer arithmetic + Integers are `Sys.int_size` bits wide. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. + ``` val (~-) : int -> int ``` Unary negation. You can also write `- e` instead of `~- e`. Unary operator, see `Ocaml_operators` for more information. + ``` val (~+) : int -> int ``` Unary addition. You can also write `+ e` instead of `~+ e`. Unary operator, see `Ocaml_operators` for more information. + since 3.12 ``` val succ : int -> int ``` `succ x` is `x + 1`. + ``` val pred : int -> int ``` `pred x` is `x - 1`. + ``` val (+) : int -> int -> int ``` Integer addition. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (-) : int -> int -> int ``` Integer subtraction. Left-associative operator, , see `Ocaml_operators` for more information. + ``` val (*) : int -> int -> int ``` Integer multiplication. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (/) : int -> int -> int ``` Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if `x >= 0` and `y > 0`, `x / y` is the greatest integer less than or equal to the real quotient of `x` by `y`. Moreover, `(- x) / y = x / (- y) = - (x / y)`. Left-associative operator, see `Ocaml_operators` for more information. + raises [`Division_by_zero`](./#exception-Division_by_zero) if the second argument is 0. ``` val (mod) : int -> int -> int ``` Integer remainder. If `y` is not zero, the result of `x mod y` satisfies the following properties: `x = (x / y) * y + x mod y` and `abs(x mod y) <= abs(y) - 1`. If `y = 0`, `x mod y` raises `Division_by_zero`. Note that `x mod y` is negative only if `x < 0`. Left-associative operator, see `Ocaml_operators` for more information. + raises [`Division_by_zero`](./#exception-Division_by_zero) if y is zero. ``` val abs : int -> int ``` `abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. + ``` val max_int : int ``` The greatest representable integer. + ``` val min_int : int ``` The smallest representable integer. + + ### Bitwise operations + ``` val (land) : int -> int -> int ``` Bitwise logical and. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (lor) : int -> int -> int ``` Bitwise logical or. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (lxor) : int -> int -> int ``` Bitwise logical exclusive or. Left-associative operator, see `Ocaml_operators` for more information. + ``` val lnot : int -> int ``` Bitwise logical negation. + ``` val (lsl) : int -> int -> int ``` `n lsl m` shifts `n` to the left by `m` bits. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. + ``` val (lsr) : int -> int -> int ``` `n lsr m` shifts `n` to the right by `m` bits. This is a logical shift: zeroes are inserted regardless of the sign of `n`. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. + ``` val (asr) : int -> int -> int ``` `n asr m` shifts `n` to the right by `m` bits. This is an arithmetic shift: the sign bit of `n` is replicated. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. + + ## Floating-point arithmetic + OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... + ``` val (~-.) : float -> float ``` Unary negation. You can also write `-. e` instead of `~-. e`. Unary operator, see `Ocaml_operators` for more information. + ``` val (~+.) : float -> float ``` Unary addition. You can also write `+. e` instead of `~+. e`. Unary operator, see `Ocaml_operators` for more information. + since 3.12 ``` val (+.) : float -> float -> float ``` Floating-point addition. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (-.) : float -> float -> float ``` Floating-point subtraction. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (*.) : float -> float -> float ``` Floating-point multiplication. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (/.) : float -> float -> float ``` Floating-point division. Left-associative operator, see `Ocaml_operators` for more information. + ``` val (**) : float -> float -> float ``` Exponentiation. + ``` val sqrt : float -> float ``` Square root. + ``` val exp : float -> float ``` Exponential. + ``` val log : float -> float ``` Natural logarithm. + ``` val log10 : float -> float ``` Base 10 logarithm. + ``` val expm1 : float -> float ``` `expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. + since 3.12.0 ``` val log1p : float -> float ``` `log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. + since 3.12.0 ``` val cos : float -> float ``` Cosine. Argument is in radians. + ``` val sin : float -> float ``` Sine. Argument is in radians. + ``` val tan : float -> float ``` Tangent. Argument is in radians. + ``` val acos : float -> float ``` Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. + ``` val asin : float -> float ``` Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. + ``` val atan : float -> float ``` Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. + ``` val atan2 : float -> float -> float ``` `atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. + ``` val hypot : float -> float -> float ``` `hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. + since 4.00.0 ``` val cosh : float -> float ``` Hyperbolic cosine. Argument is in radians. + ``` val sinh : float -> float ``` Hyperbolic sine. Argument is in radians. + ``` val tanh : float -> float ``` Hyperbolic tangent. Argument is in radians. + ``` val acosh : float -> float ``` Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. + since 4.13.0 ``` val asinh : float -> float ``` Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. + since 4.13.0 ``` val atanh : float -> float ``` Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. + since 4.13.0 ``` val ceil : float -> float ``` Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. + ``` val floor : float -> float ``` Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. + ``` val abs_float : float -> float ``` `abs_float f` returns the absolute value of `f`. + ``` val copysign : float -> float -> float ``` `copysign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. + since 4.00 ``` val mod_float : float -> float -> float ``` `mod_float a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. + ``` val frexp : float -> float * int ``` `frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. + ``` val ldexp : float -> int -> float ``` `ldexp x n` returns `x *. 2 ** n`. + ``` val modf : float -> float * float ``` `modf f` returns the pair of the fractional and integral part of `f`. + ``` val float : int -> float ``` Same as [`Stdlib.float_of_int`](./#val-float_of_int). + ``` val float_of_int : int -> float ``` Convert an integer to floating-point. + ``` val truncate : float -> int ``` Same as [`Stdlib.int_of_float`](./#val-int_of_float). + ``` val int_of_float : float -> int ``` Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. + ``` val infinity : float ``` Positive infinity. + ``` val neg_infinity : float ``` Negative infinity. + ``` val nan : float ``` @@ -451,14 +577,17 @@ val nan : float val max_float : float ``` The largest positive finite value of type `float`. + ``` val min_float : float ``` The smallest positive, non-zero, non-denormalized value of type `float`. + ``` val epsilon_float : float ``` The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. + ``` type fpclass = ``` @@ -466,231 +595,319 @@ type fpclass = | FP_normal ``` Normal number, none of the below + ``` | FP_subnormal ``` Number very close to 0.0, has reduced precision + ``` | FP_zero ``` Number is 0.0 or \-0.0 + ``` | FP_infinite ``` Number is positive or negative infinity + ``` | FP_nan ``` Not a number: result of an undefined operation + ``` ``` The five classes of floating-point numbers, as determined by the [`Stdlib.classify_float`](./#val-classify_float) function. + ``` val classify_float : float -> fpclass ``` + ## String operations + More string operations are provided in module [`String`](./Stdlib-String.md). + ``` val (^) : string -> string -> string ``` String concatenation. Right-associative operator, see `Ocaml_operators` for more information. + raises [`Invalid_argument`](./#exception-Invalid_argument) if the result is longer then than Sys.max\_string\_length bytes. + ## Character operations + More character operations are provided in module [`Char`](./Stdlib-Char.md). + ``` val int_of_char : char -> int ``` Return the ASCII code of the argument. + ``` val char_of_int : int -> char ``` Return the character with the given ASCII code. + raises [`Invalid_argument`](./#exception-Invalid_argument) if the argument is outside the range 0--255. + ## Unit operations + ``` val ignore : 'a -> unit ``` Discard the value of its argument and return `()`. For instance, `ignore(f x)` discards the result of the side-effecting function `f`. It is equivalent to `f x; ()`, except that the latter may generate a compiler warning; writing `ignore(f x)` instead avoids the warning. + + ## String conversion functions + ``` val string_of_bool : bool -> string ``` Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly. + ``` val bool_of_string_opt : string -> bool option ``` Convert the given string to a boolean. + Return `None` if the string is not `"true"` or `"false"`. + since 4.05 ``` val bool_of_string : string -> bool ``` Same as [`Stdlib.bool_of_string_opt`](./#val-bool_of_string_opt), but raise `Invalid_argument "bool_of_string"` instead of returning `None`. + ``` val string_of_int : int -> string ``` Return the string representation of an integer, in decimal. + ``` val int_of_string_opt : string -> int option ``` Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with `0u`), in hexadecimal (if it begins with `0x` or `0X`), in octal (if it begins with `0o` or `0O`), or in binary (if it begins with `0b` or `0B`). + The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*max_int+1]`. If the input exceeds [`max_int`](./#val-max_int) it is converted to the signed integer `min_int + input - max_int - 1`. + The `_` (underscore) character can appear anywhere in the string and is ignored. + Return `None` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int`. + since 4.05 ``` val int_of_string : string -> int ``` Same as [`Stdlib.int_of_string_opt`](./#val-int_of_string_opt), but raise `Failure "int_of_string"` instead of returning `None`. + ``` val string_of_float : float -> string ``` Return a string representation of a floating-point number. + This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). + ``` val float_of_string_opt : string -> float option ``` Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). + The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. + The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. + In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. + The `_` (underscore) character can appear anywhere in the string and is ignored. + Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. + Return `None` if the given string is not a valid representation of a float. + since 4.05 ``` val float_of_string : string -> float ``` Same as [`Stdlib.float_of_string_opt`](./#val-float_of_string_opt), but raise `Failure "float_of_string"` instead of returning `None`. + + ## Pair operations + ``` val fst : ('a * 'b) -> 'a ``` Return the first component of a pair. + ``` val snd : ('a * 'b) -> 'b ``` Return the second component of a pair. + + ## List operations + More list operations are provided in module [`List`](./Stdlib-List.md). + ``` val (@) : 'a list -> 'a list -> 'a list ``` `l0 @ l1` appends `l1` to `l0`. Same function as [`List.append`](./Stdlib-List.md#val-append). Right-associative operator, see `Ocaml_operators` for more information. + since 5.1 this function is tail-recursive. + ## Input/output + Note: all input/output functions can raise `Sys_error` when the system calls they invoke fail. + ``` type in_channel ``` The type of input channel. + ``` type out_channel ``` The type of output channel. + ``` val stdin : in_channel ``` The standard input for the process. + ``` val stdout : out_channel ``` The standard output for the process. + ``` val stderr : out_channel ``` The standard error output for the process. + + ### Output functions on standard output + ``` val print_char : char -> unit ``` Print a character on standard output. + ``` val print_string : string -> unit ``` Print a string on standard output. + ``` val print_bytes : bytes -> unit ``` Print a byte sequence on standard output. + since 4.02 ``` val print_int : int -> unit ``` Print an integer, in decimal, on standard output. + ``` val print_float : float -> unit ``` Print a floating-point number, in decimal, on standard output. + The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. + ``` val print_endline : string -> unit ``` Print a string, followed by a newline character, on standard output and flush standard output. + ``` val print_newline : unit -> unit ``` Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. + + ### Output functions on standard error + ``` val prerr_char : char -> unit ``` Print a character on standard error. + ``` val prerr_string : string -> unit ``` Print a string on standard error. + ``` val prerr_bytes : bytes -> unit ``` Print a byte sequence on standard error. + since 4.02 ``` val prerr_int : int -> unit ``` Print an integer, in decimal, on standard error. + ``` val prerr_float : float -> unit ``` Print a floating-point number, in decimal, on standard error. + The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. + ``` val prerr_endline : string -> unit ``` Print a string, followed by a newline character on standard error and flush standard error. + ``` val prerr_newline : unit -> unit ``` Print a newline character on standard error, and flush standard error. + + ### Input functions on standard input + ``` val read_line : unit -> string ``` Flush standard output, then read characters from standard input until a newline character is encountered. + Return the string of all characters read, without the newline character at the end. + raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. ``` val read_int_opt : unit -> int option ``` Flush standard output, then read one line from standard input and convert it to an integer. + Return `None` if the line read is not a valid representation of an integer. + since 4.05 ``` val read_int : unit -> int ``` Same as [`Stdlib.read_int_opt`](./#val-read_int_opt), but raise `Failure "int_of_string"` instead of returning `None`. + ``` val read_float_opt : unit -> float option ``` Flush standard output, then read one line from standard input and convert it to a floating-point number. + Return `None` if the line read is not a valid representation of a floating-point number. + since 4.05 ``` val read_float : unit -> float ``` Same as [`Stdlib.read_float_opt`](./#val-read_float_opt), but raise `Failure "float_of_string"` instead of returning `None`. + + ### General output functions + ``` type open_flag = ``` @@ -698,204 +915,257 @@ type open_flag = | Open_rdonly ``` open for reading. + ``` | Open_wronly ``` open for writing. + ``` | Open_append ``` open for appending: always write at end of file. + ``` | Open_creat ``` create the file if it does not exist. + ``` | Open_trunc ``` empty the file if it already exists. + ``` | Open_excl ``` fail if Open\_creat and the file already exists. + ``` | Open_binary ``` open in binary mode (no conversion). + ``` | Open_text ``` open in text mode (may perform conversions). + ``` | Open_nonblock ``` open in non-blocking mode. + ``` ``` Opening modes for [`Stdlib.open_out_gen`](./#val-open_out_gen) and [`Stdlib.open_in_gen`](./#val-open_in_gen). + ``` val open_out : string -> out_channel ``` Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. + ``` val open_out_bin : string -> out_channel ``` Same as [`Stdlib.open_out`](./#val-open_out), but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_out`](./#val-open_out). + ``` val open_out_gen : open_flag list -> int -> string -> out_channel ``` `open_out_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`Stdlib.open_out`](./#val-open_out) and [`Stdlib.open_out_bin`](./#val-open_out_bin) are special cases of this function. + ``` val flush : out_channel -> unit ``` Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. + ``` val flush_all : unit -> unit ``` Flush all open output channels; ignore errors. + ``` val output_char : out_channel -> char -> unit ``` Write the character on the given output channel. + ``` val output_string : out_channel -> string -> unit ``` Write the string on the given output channel. + ``` val output_bytes : out_channel -> bytes -> unit ``` Write the byte sequence on the given output channel. + since 4.02 ``` val output : out_channel -> bytes -> int -> int -> unit ``` `output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. + raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. ``` val output_substring : out_channel -> string -> int -> int -> unit ``` Same as `output` but take a string as argument instead of a byte sequence. + since 4.02 ``` val output_byte : out_channel -> int -> unit ``` Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. + ``` val output_binary_int : out_channel -> int -> unit ``` Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the [`Stdlib.input_binary_int`](./#val-input_binary_int) function. The format is compatible across all machines for a given version of OCaml. + ``` val output_value : out_channel -> 'a -> unit ``` Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function [`Stdlib.input_value`](./#val-input_value). See the description of module [`Marshal`](./Stdlib-Marshal.md) for more information. [`Stdlib.output_value`](./#val-output_value) is equivalent to [`Marshal.to_channel`](./Stdlib-Marshal.md#val-to_channel) with an empty list of flags. + ``` val seek_out : out_channel -> int -> unit ``` `seek_out chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. + ``` val pos_out : out_channel -> int ``` Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_out`, then going back to this position using `seek_out` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + ``` val out_channel_length : out_channel -> int ``` Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. + ``` val close_out : out_channel -> unit ``` Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except `close_out` and `flush`, which do nothing when applied to an already closed channel. Note that `close_out` may raise `Sys_error` if the operating system signals an error when flushing or closing. + ``` val close_out_noerr : out_channel -> unit ``` Same as `close_out`, but ignore all errors. + ``` val set_binary_mode_out : out_channel -> bool -> unit ``` `set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. `set_binary_mode_out oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. + + ### General input functions + ``` val open_in : string -> in_channel ``` Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. + ``` val open_in_bin : string -> in_channel ``` Same as [`Stdlib.open_in`](./#val-open_in), but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_in`](./#val-open_in). + ``` val open_in_gen : open_flag list -> int -> string -> in_channel ``` `open_in_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`Stdlib.open_in`](./#val-open_in) and [`Stdlib.open_in_bin`](./#val-open_in_bin) are special cases of this function. + ``` val input_char : in_channel -> char ``` Read one character from the given input channel. + raises [`End_of_file`](./#exception-End_of_file) if there are no more characters to read. ``` val input_line : in_channel -> string ``` Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. + raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. ``` val input : in_channel -> bytes -> int -> int -> int ``` `input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and `len` exclusive means that not all requested `len` characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; `input` must be called again to read the remaining characters, if desired. (See also [`Stdlib.really_input`](./#val-really_input) for reading exactly `len` characters.) Exception `Invalid_argument "input"` is raised if `pos` and `len` do not designate a valid range of `buf`. + ``` val really_input : in_channel -> bytes -> int -> int -> unit ``` `really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. + raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. ``` val really_input_string : in_channel -> int -> string ``` `really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. + raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. since 4.02 ``` val input_byte : in_channel -> int ``` Same as [`Stdlib.input_char`](./#val-input_char), but return the 8-bit integer representing the character. + raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached. ``` val input_binary_int : in_channel -> int ``` Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See [`Stdlib.output_binary_int`](./#val-output_binary_int). + raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached while reading the integer. ``` val input_value : in_channel -> 'a ``` Read the representation of a structured value, as produced by [`Stdlib.output_value`](./#val-output_value), and return the corresponding value. This function is identical to [`Marshal.from_channel`](./Stdlib-Marshal.md#val-from_channel); see the description of module [`Marshal`](./Stdlib-Marshal.md) for more information, in particular concerning the lack of type safety. + ``` val seek_in : in_channel -> int -> unit ``` `seek_in chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. + ``` val pos_in : in_channel -> int ``` Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_in`, then going back to this position using `seek_in` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + ``` val in_channel_length : in_channel -> int ``` Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. + ``` val close_in : in_channel -> unit ``` Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except `close_in`, which does nothing when applied to an already closed channel. + ``` val close_in_noerr : in_channel -> unit ``` Same as `close_in`, but ignore all errors. + ``` val set_binary_mode_in : in_channel -> bool -> unit ``` `set_binary_mode_in ic true` sets the channel `ic` to binary mode: no translations take place during input. `set_binary_mode_out ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. + + ### Operations on large files + ``` module LargeFile : sig ... end ``` Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. + + ## References + ``` type 'a ref = { ``` @@ -904,27 +1174,35 @@ type 'a ref = { } ``` The type of references (mutable indirection cells) containing a value of type `'a`. + ``` val ref : 'a -> 'a ref ``` Return a fresh reference containing the given value. + ``` val (!) : 'a ref -> 'a ``` `!r` returns the current contents of reference `r`. Equivalent to `fun r -> r.contents`. Unary operator, see `Ocaml_operators` for more information. + ``` val (:=) : 'a ref -> 'a -> unit ``` `r := a` stores the value of `a` in reference `r`. Equivalent to `fun r v -> r.contents <- v`. Right-associative operator, see `Ocaml_operators` for more information. + ``` val incr : int ref -> unit ``` Increment the integer contained in the given reference. Equivalent to `fun r -> r := succ !r`. + ``` val decr : int ref -> unit ``` Decrement the integer contained in the given reference. Equivalent to `fun r -> r := pred !r`. + + ## Result type + ``` type ('a, 'b) result = ``` @@ -938,19 +1216,28 @@ type ('a, 'b) result = ``` since 4.03 + ## Operations on format strings + Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module [`Scanf`](./Stdlib-Scanf.md) and to print data with formatted output functions from modules [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). + Format strings are made of three kinds of entities: + - *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print, - *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument, - *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output. There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`. + For more information about conversion specifications and formatting indications available, read the documentation of modules [`Scanf`](./Stdlib-Scanf.md), [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). + Format strings have a general and highly polymorphic type `('a, 'b, 'c, 'd, 'e, 'f) format6`. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml. + The meaning of format string type parameters is as follows: + - `'a` is the type of the parameters of the format for formatted output functions (`printf`\-style functions); `'a` is the type of the values read by the format for formatted input functions (`scanf`\-style functions). - `'b` is the type of input source for formatted input functions and the type of output target for formatted output functions. For `printf`\-style functions from module [`Printf`](./Stdlib-Printf.md), `'b` is typically `out_channel`; for `printf`\-style functions from module [`Format`](./Stdlib-Format.md), `'b` is typically [`Format.formatter`](./Stdlib-Format.md#type-formatter); for `scanf`\-style functions from module [`Scanf`](./Stdlib-Scanf.md), `'b` is typically [`Scanf.Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). Type argument `'b` is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion. + - `'c` is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf`\-style functions or to the `kscanf`\-style functions. - `'d` is the type of parameters for the `scanf`\-style functions. - `'e` is the type of the receiver function for the `scanf`\-style functions. @@ -969,12 +1256,14 @@ type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string ``` Converts a format string into a string. + ``` val format_of_string : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> ('a, 'b, 'c, 'd, 'e, 'f) format6 ``` `format_of_string s` returns a format string read from the string literal `s`. Note: `format_of_string` can not convert a string argument that is not a literal. If you need this functionality, use the more general [`Scanf.format_from_string`](./Stdlib-Scanf.md#val-format_from_string) function. + ``` val (^^) : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> @@ -982,64 +1271,83 @@ val (^^) : ('a, 'b, 'c, 'd, 'g, 'h) format6 ``` `f1 ^^ f2` catenates format strings `f1` and `f2`. The result is a format string that behaves as the concatenation of format strings `f1` and `f2`: in case of formatted output, it accepts arguments from `f1`, then arguments from `f2`; in case of formatted input, it returns results from `f1`, then results from `f2`. Right-associative operator, see `Ocaml_operators` for more information. + + ## Program termination + ``` val exit : int -> 'a ``` Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with [`Domain.at_exit`](./Stdlib-Domain.md#val-at_exit) are called followed by those registered with [`Stdlib.at_exit`](./#val-at_exit). + An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception. + ``` val at_exit : (unit -> unit) -> unit ``` Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following: + - executes [`Stdlib.exit`](./#val-exit) - terminates, either normally or because of an uncaught exception - executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. + ## Standard library modules + ``` module Arg : sig ... end ``` Parsing of command line arguments. + ``` module Array : sig ... end ``` Array operations. + ``` module ArrayLabels : sig ... end ``` Array operations. + ``` module Atomic : sig ... end ``` Atomic references. + ``` module Bool : sig ... end ``` Boolean values. + ``` module Buffer : sig ... end ``` Extensible buffers. + ``` module Bytes : sig ... end ``` Byte sequence operations. + ``` module BytesLabels : sig ... end ``` Byte sequence operations. + ``` module Char : sig ... end ``` Character operations. + ``` module Complex : sig ... end ``` Complex numbers. + ``` module Digest : sig ... end ``` Message digest. + ``` module Domain : sig ... end ``` @@ -1047,6 +1355,7 @@ module Domain : sig ... end module Dynarray : sig ... end ``` Dynamic arrays. + ``` module Effect : sig ... end ``` @@ -1054,163 +1363,203 @@ module Effect : sig ... end module Either : sig ... end ``` Either type. + ``` module Filename : sig ... end ``` Operations on file names. + ``` module Float : sig ... end ``` Floating-point arithmetic. + ``` module Format : sig ... end ``` Pretty-printing. + ``` module Fun : sig ... end ``` Function manipulation. + ``` module Gc : sig ... end ``` Memory management control and statistics; finalised values. + ``` module Hashtbl : sig ... end ``` Hash tables and hash functions. + ``` module In_channel : sig ... end ``` Input channels. + ``` module Int : sig ... end ``` Integer values. + ``` module Int32 : sig ... end ``` 32-bit integers. + ``` module Int64 : sig ... end ``` 64-bit integers. + ``` module Lazy : sig ... end ``` Deferred computations. + ``` module Lexing : sig ... end ``` The run-time library for lexers generated by `ocamllex`. + ``` module List : sig ... end ``` List operations. + ``` module ListLabels : sig ... end ``` List operations. + ``` module Map : sig ... end ``` Association tables over ordered types. + ``` module Marshal : sig ... end ``` Marshaling of data structures. + ``` module MoreLabels : sig ... end ``` Extra labeled libraries. + ``` module Mutex : sig ... end ``` Locks for mutual exclusion. + ``` module Obj : sig ... end ``` Operations on internal representations of values. + ``` module Oo : sig ... end ``` Operations on objects + ``` module Option : sig ... end ``` Option values. + ``` module Out_channel : sig ... end ``` Output channels. + ``` module Parsing : sig ... end ``` The run-time library for parsers generated by `ocamlyacc`. + ``` module Printexc : sig ... end ``` Facilities for printing exceptions and inspecting current call stack. + ``` module Printf : sig ... end ``` Formatted output functions. + ``` module Queue : sig ... end ``` First-in first-out queues. + ``` module Random : sig ... end ``` Pseudo-random number generators (PRNG). + ``` module Result : sig ... end ``` Result values. + ``` module Scanf : sig ... end ``` Formatted input functions. + ``` module Seq : sig ... end ``` Sequences. + ``` module Set : sig ... end ``` Sets over ordered types. + ``` module Stack : sig ... end ``` Last-in first-out stacks. + ``` module StdLabels : sig ... end ``` Standard labeled libraries. + ``` module String : sig ... end ``` Strings. + ``` module StringLabels : sig ... end ``` Strings. + ``` module Sys : sig ... end ``` System interface. + ``` module Type : sig ... end ``` Type introspection. + ``` module Uchar : sig ... end ``` Unicode characters. + ``` module Unit : sig ... end ``` Unit values. + ``` module Weak : sig ... end ``` -Arrays of weak pointers and hash sets of weak pointers. \ No newline at end of file +Arrays of weak pointers and hash sets of weak pointers. From 2730b8b5440c5f8c715f38e77db0d855127c3cfd Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Sat, 3 May 2025 15:23:55 +0100 Subject: [PATCH 07/19] Try on CI --- .github/workflows/deploy-docs.yml | 10 ++-------- Makefile | 20 ++++++++++++++------ 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index ca13cd7e3..22e61a812 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -23,14 +23,8 @@ jobs: dune-cache: false # can cause trouble when generating melange docs in step below: https://github.com/ocaml/dune/issues/7720 - name: Install all deps run: make install - - name: Generate melange docs in ml syntax - run: opam reinstall -y melange --with-doc - - name: Copy melange docs in ml syntax - run: cp -r _opam/.opam-switch/build/melange.dev/_build/default/_doc/_html docs/public/api/ml - - name: Generate melange docs in re syntax - run: ODOC_SYNTAX="re" opam reinstall -y melange --with-doc - - name: Copy melange docs in re syntax - run: cp -r _opam/.opam-switch/build/melange.dev/_build/default/_doc/_html docs/public/api/re + - name: Generate melange library docs + run: make pull-melange-docs - name: Run canonical script run: opam exec -- dune exec add_canonical docs/public/api - name: Check Reason syntax diff --git a/Makefile b/Makefile index 0981c53d6..ec0a30cf6 100644 --- a/Makefile +++ b/Makefile @@ -89,10 +89,18 @@ pull-melange-docs: ## Pull melange docs opam source melange; \ fi cd melange.dev - dune build @docs + dune build @doc cd .. - odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/stdlib.odocl - odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/js.odocl - odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/belt.odocl - odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/dom.odocl - odoc markdown-generate -o docs/api ./_build/default/_doc/_odocls/melange/node.odocl + odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/stdlib.odocl + odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/js.odocl + odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/belt.odocl + odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/dom.odocl + odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/node.odocl + cd melange.dev + ODOC_SYNTAX="re" dune build @doc + cd .. + odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/stdlib.odocl + odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/js.odocl + odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/belt.odocl + odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/dom.odocl + odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/node.odocl From d8f3e638ef4fbd1030c243b46bb46af0db204c6a Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Sat, 3 May 2025 15:25:09 +0100 Subject: [PATCH 08/19] Keep all generated stuff --- .gitignore | 4 - docs/api/{ => ml}/melange/Belt-Array.md | 0 docs/api/{ => ml}/melange/Belt-Float.md | 0 docs/api/{ => ml}/melange/Belt-HashMap-Int.md | 0 .../{ => ml}/melange/Belt-HashMap-String.md | 0 docs/api/{ => ml}/melange/Belt-HashMap.md | 0 docs/api/{ => ml}/melange/Belt-HashSet-Int.md | 0 .../{ => ml}/melange/Belt-HashSet-String.md | 0 docs/api/{ => ml}/melange/Belt-HashSet.md | 0 .../Belt-Id-MakeComparable-argument-1-M.md | 0 .../melange/Belt-Id-MakeComparable.md | 0 .../Belt-Id-MakeComparableU-argument-1-M.md | 0 .../melange/Belt-Id-MakeComparableU.md | 0 .../Belt-Id-MakeHashable-argument-1-M.md | 0 .../{ => ml}/melange/Belt-Id-MakeHashable.md | 0 .../Belt-Id-MakeHashableU-argument-1-M.md | 0 .../{ => ml}/melange/Belt-Id-MakeHashableU.md | 0 .../melange/Belt-Id-module-type-Comparable.md | 0 .../melange/Belt-Id-module-type-Hashable.md | 0 docs/api/{ => ml}/melange/Belt-Id.md | 0 docs/api/{ => ml}/melange/Belt-Int.md | 0 docs/api/{ => ml}/melange/Belt-List.md | 0 docs/api/{ => ml}/melange/Belt-Map-Dict.md | 0 docs/api/{ => ml}/melange/Belt-Map-Int.md | 0 docs/api/{ => ml}/melange/Belt-Map-String.md | 0 docs/api/{ => ml}/melange/Belt-Map.md | 0 .../{ => ml}/melange/Belt-MutableMap-Int.md | 0 .../melange/Belt-MutableMap-String.md | 0 docs/api/{ => ml}/melange/Belt-MutableMap.md | 0 .../api/{ => ml}/melange/Belt-MutableQueue.md | 0 .../{ => ml}/melange/Belt-MutableSet-Int.md | 0 .../melange/Belt-MutableSet-String.md | 0 docs/api/{ => ml}/melange/Belt-MutableSet.md | 0 .../api/{ => ml}/melange/Belt-MutableStack.md | 0 docs/api/{ => ml}/melange/Belt-Option.md | 0 docs/api/{ => ml}/melange/Belt-Range.md | 0 docs/api/{ => ml}/melange/Belt-Result.md | 0 docs/api/{ => ml}/melange/Belt-Set-Dict.md | 0 docs/api/{ => ml}/melange/Belt-Set-Int.md | 0 docs/api/{ => ml}/melange/Belt-Set-String.md | 0 docs/api/{ => ml}/melange/Belt-Set.md | 0 .../{ => ml}/melange/Belt-SortArray-Int.md | 0 .../{ => ml}/melange/Belt-SortArray-String.md | 0 docs/api/{ => ml}/melange/Belt-SortArray.md | 0 docs/api/{ => ml}/melange/Belt.md | 0 docs/api/{ => ml}/melange/Dom-Storage.md | 0 docs/api/{ => ml}/melange/Dom.md | 0 docs/api/{ => ml}/melange/Js-Array.md | 0 docs/api/{ => ml}/melange/Js-Bigint.md | 0 docs/api/{ => ml}/melange/Js-Blob.md | 0 docs/api/{ => ml}/melange/Js-Console.md | 0 docs/api/{ => ml}/melange/Js-Date.md | 0 docs/api/{ => ml}/melange/Js-Dict.md | 0 docs/api/{ => ml}/melange/Js-Exn.md | 0 docs/api/{ => ml}/melange/Js-File.md | 0 docs/api/{ => ml}/melange/Js-Float.md | 0 docs/api/{ => ml}/melange/Js-FormData.md | 0 docs/api/{ => ml}/melange/Js-Global.md | 0 docs/api/{ => ml}/melange/Js-Int.md | 0 docs/api/{ => ml}/melange/Js-Iterator.md | 0 docs/api/{ => ml}/melange/Js-Json.md | 0 docs/api/{ => ml}/melange/Js-Map.md | 0 docs/api/{ => ml}/melange/Js-Math.md | 0 docs/api/{ => ml}/melange/Js-Null.md | 0 docs/api/{ => ml}/melange/Js-Nullable.md | 0 docs/api/{ => ml}/melange/Js-Obj.md | 0 docs/api/{ => ml}/melange/Js-Promise.md | 0 docs/api/{ => ml}/melange/Js-Re.md | 0 docs/api/{ => ml}/melange/Js-Set.md | 0 docs/api/{ => ml}/melange/Js-String.md | 0 .../melange/Js-Typed_array-ArrayBuffer.md | 0 .../melange/Js-Typed_array-DataView.md | 0 .../melange/Js-Typed_array-Float32Array.md | 0 .../melange/Js-Typed_array-Float64Array.md | 0 .../melange/Js-Typed_array-Int16Array.md | 0 .../melange/Js-Typed_array-Int32Array.md | 0 .../melange/Js-Typed_array-Int8Array.md | 0 .../melange/Js-Typed_array-Uint16Array.md | 0 .../melange/Js-Typed_array-Uint32Array.md | 0 .../melange/Js-Typed_array-Uint8Array.md | 0 .../Js-Typed_array-Uint8ClampedArray.md | 0 docs/api/{ => ml}/melange/Js-Typed_array.md | 0 docs/api/{ => ml}/melange/Js-Types.md | 0 docs/api/{ => ml}/melange/Js-Undefined.md | 0 docs/api/{ => ml}/melange/Js-WeakMap.md | 0 docs/api/{ => ml}/melange/Js-WeakSet.md | 0 docs/api/{ => ml}/melange/Js.md | 0 docs/api/{ => ml}/melange/Node-Buffer.md | 0 .../{ => ml}/melange/Node-Child_process.md | 0 docs/api/{ => ml}/melange/Node-Fs-Watch.md | 0 docs/api/{ => ml}/melange/Node-Fs.md | 0 docs/api/{ => ml}/melange/Node-Module.md | 0 docs/api/{ => ml}/melange/Node-Path.md | 0 docs/api/{ => ml}/melange/Node-Process.md | 0 docs/api/{ => ml}/melange/Node.md | 0 docs/api/{ => ml}/melange/Stdlib-Arg.md | 0 docs/api/{ => ml}/melange/Stdlib-Array.md | 0 .../{ => ml}/melange/Stdlib-ArrayLabels.md | 0 docs/api/{ => ml}/melange/Stdlib-Atomic.md | 0 docs/api/{ => ml}/melange/Stdlib-Bool.md | 0 docs/api/{ => ml}/melange/Stdlib-Buffer.md | 0 docs/api/{ => ml}/melange/Stdlib-Bytes.md | 0 .../{ => ml}/melange/Stdlib-BytesLabels.md | 0 docs/api/{ => ml}/melange/Stdlib-Char.md | 0 docs/api/{ => ml}/melange/Stdlib-Complex.md | 0 .../melange/Stdlib-Digest-BLAKE128.md | 0 .../melange/Stdlib-Digest-BLAKE256.md | 0 .../melange/Stdlib-Digest-BLAKE512.md | 0 .../api/{ => ml}/melange/Stdlib-Digest-MD5.md | 0 .../melange/Stdlib-Digest-module-type-S.md | 0 docs/api/{ => ml}/melange/Stdlib-Digest.md | 0 .../api/{ => ml}/melange/Stdlib-Domain-DLS.md | 0 docs/api/{ => ml}/melange/Stdlib-Domain.md | 0 docs/api/{ => ml}/melange/Stdlib-Dynarray.md | 0 docs/api/{ => ml}/melange/Stdlib-Either.md | 0 docs/api/{ => ml}/melange/Stdlib-Filename.md | 0 .../{ => ml}/melange/Stdlib-Float-Array.md | 0 docs/api/{ => ml}/melange/Stdlib-Float.md | 0 docs/api/{ => ml}/melange/Stdlib-Format.md | 0 docs/api/{ => ml}/melange/Stdlib-Fun.md | 0 .../api/{ => ml}/melange/Stdlib-Gc-Memprof.md | 0 docs/api/{ => ml}/melange/Stdlib-Gc.md | 0 .../Stdlib-Hashtbl-Make-argument-1-H.md | 0 .../{ => ml}/melange/Stdlib-Hashtbl-Make.md | 0 .../Stdlib-Hashtbl-MakeSeeded-argument-1-H.md | 0 .../melange/Stdlib-Hashtbl-MakeSeeded.md | 0 .../Stdlib-Hashtbl-module-type-HashedType.md | 0 .../melange/Stdlib-Hashtbl-module-type-S.md | 0 ...ib-Hashtbl-module-type-SeededHashedType.md | 0 .../Stdlib-Hashtbl-module-type-SeededS.md | 0 docs/api/{ => ml}/melange/Stdlib-Hashtbl.md | 0 .../api/{ => ml}/melange/Stdlib-In_channel.md | 0 docs/api/{ => ml}/melange/Stdlib-Int.md | 0 docs/api/{ => ml}/melange/Stdlib-Int32.md | 0 docs/api/{ => ml}/melange/Stdlib-Int64.md | 0 docs/api/{ => ml}/melange/Stdlib-LargeFile.md | 0 docs/api/{ => ml}/melange/Stdlib-Lazy.md | 0 docs/api/{ => ml}/melange/Stdlib-Lexing.md | 0 docs/api/{ => ml}/melange/Stdlib-List.md | 0 .../api/{ => ml}/melange/Stdlib-ListLabels.md | 0 .../melange/Stdlib-Map-Make-argument-1-Ord.md | 0 docs/api/{ => ml}/melange/Stdlib-Map-Make.md | 0 .../Stdlib-Map-module-type-OrderedType.md | 0 .../melange/Stdlib-Map-module-type-S.md | 0 docs/api/{ => ml}/melange/Stdlib-Map.md | 0 docs/api/{ => ml}/melange/Stdlib-Marshal.md | 0 ...ib-MoreLabels-Hashtbl-Make-argument-1-H.md | 0 .../melange/Stdlib-MoreLabels-Hashtbl-Make.md | 0 ...eLabels-Hashtbl-MakeSeeded-argument-1-H.md | 0 .../Stdlib-MoreLabels-Hashtbl-MakeSeeded.md | 0 ...reLabels-Hashtbl-module-type-HashedType.md | 0 ...Stdlib-MoreLabels-Hashtbl-module-type-S.md | 0 ...ls-Hashtbl-module-type-SeededHashedType.md | 0 ...-MoreLabels-Hashtbl-module-type-SeededS.md | 0 .../melange/Stdlib-MoreLabels-Hashtbl.md | 0 ...dlib-MoreLabels-Map-Make-argument-1-Ord.md | 0 .../melange/Stdlib-MoreLabels-Map-Make.md | 0 ...-MoreLabels-Map-module-type-OrderedType.md | 0 .../Stdlib-MoreLabels-Map-module-type-S.md | 0 .../{ => ml}/melange/Stdlib-MoreLabels-Map.md | 0 ...dlib-MoreLabels-Set-Make-argument-1-Ord.md | 0 .../melange/Stdlib-MoreLabels-Set-Make.md | 0 ...-MoreLabels-Set-module-type-OrderedType.md | 0 .../Stdlib-MoreLabels-Set-module-type-S.md | 0 .../{ => ml}/melange/Stdlib-MoreLabels-Set.md | 0 .../api/{ => ml}/melange/Stdlib-MoreLabels.md | 0 docs/api/{ => ml}/melange/Stdlib-Mutex.md | 0 .../{ => ml}/melange/Stdlib-Obj-Ephemeron.md | 0 .../Stdlib-Obj-Extension_constructor.md | 0 docs/api/{ => ml}/melange/Stdlib-Obj.md | 0 docs/api/{ => ml}/melange/Stdlib-Oo.md | 0 docs/api/{ => ml}/melange/Stdlib-Option.md | 0 .../{ => ml}/melange/Stdlib-Out_channel.md | 0 docs/api/{ => ml}/melange/Stdlib-Parsing.md | 0 .../{ => ml}/melange/Stdlib-Printexc-Slot.md | 0 docs/api/{ => ml}/melange/Stdlib-Printexc.md | 0 docs/api/{ => ml}/melange/Stdlib-Printf.md | 0 docs/api/{ => ml}/melange/Stdlib-Queue.md | 0 .../{ => ml}/melange/Stdlib-Random-State.md | 0 docs/api/{ => ml}/melange/Stdlib-Random.md | 0 docs/api/{ => ml}/melange/Stdlib-Result.md | 0 .../{ => ml}/melange/Stdlib-Scanf-Scanning.md | 0 docs/api/{ => ml}/melange/Stdlib-Scanf.md | 0 docs/api/{ => ml}/melange/Stdlib-Seq.md | 0 .../melange/Stdlib-Set-Make-argument-1-Ord.md | 0 docs/api/{ => ml}/melange/Stdlib-Set-Make.md | 0 .../Stdlib-Set-module-type-OrderedType.md | 0 .../melange/Stdlib-Set-module-type-S.md | 0 docs/api/{ => ml}/melange/Stdlib-Set.md | 0 docs/api/{ => ml}/melange/Stdlib-Stack.md | 0 docs/api/{ => ml}/melange/Stdlib-StdLabels.md | 0 docs/api/{ => ml}/melange/Stdlib-String.md | 0 .../{ => ml}/melange/Stdlib-StringLabels.md | 0 ...s-Immediate64-Make-argument-1-Immediate.md | 0 ...mediate64-Make-argument-2-Non_immediate.md | 0 .../melange/Stdlib-Sys-Immediate64-Make.md | 0 ...b-Sys-Immediate64-module-type-Immediate.md | 0 ...s-Immediate64-module-type-Non_immediate.md | 0 .../melange/Stdlib-Sys-Immediate64.md | 0 docs/api/{ => ml}/melange/Stdlib-Sys.md | 0 docs/api/{ => ml}/melange/Stdlib-Type-Id.md | 0 docs/api/{ => ml}/melange/Stdlib-Type.md | 0 docs/api/{ => ml}/melange/Stdlib-Uchar.md | 0 docs/api/{ => ml}/melange/Stdlib-Unit.md | 0 .../melange/Stdlib-Weak-Make-argument-1-H.md | 0 docs/api/{ => ml}/melange/Stdlib-Weak-Make.md | 0 .../melange/Stdlib-Weak-module-type-S.md | 0 docs/api/{ => ml}/melange/Stdlib-Weak.md | 0 docs/api/{ => ml}/melange/Stdlib.md | 0 docs/api/re/melange/Belt-Array.md | 654 +++++++ docs/api/re/melange/Belt-Float.md | 29 + docs/api/re/melange/Belt-HashMap-Int.md | 79 + docs/api/re/melange/Belt-HashMap-String.md | 79 + docs/api/re/melange/Belt-HashMap.md | 165 ++ docs/api/re/melange/Belt-HashSet-Int.md | 68 + docs/api/re/melange/Belt-HashSet-String.md | 68 + docs/api/re/melange/Belt-HashSet.md | 124 ++ .../Belt-Id-MakeComparable-argument-1-M.md | 9 + docs/api/re/melange/Belt-Id-MakeComparable.md | 21 + .../Belt-Id-MakeComparableU-argument-1-M.md | 9 + .../api/re/melange/Belt-Id-MakeComparableU.md | 21 + .../Belt-Id-MakeHashable-argument-1-M.md | 12 + docs/api/re/melange/Belt-Id-MakeHashable.md | 24 + .../Belt-Id-MakeHashableU-argument-1-M.md | 12 + docs/api/re/melange/Belt-Id-MakeHashableU.md | 24 + .../melange/Belt-Id-module-type-Comparable.md | 12 + .../melange/Belt-Id-module-type-Hashable.md | 15 + docs/api/re/melange/Belt-Id.md | 113 ++ docs/api/re/melange/Belt-Int.md | 29 + docs/api/re/melange/Belt-List.md | 680 +++++++ docs/api/re/melange/Belt-Map-Dict.md | 281 +++ docs/api/re/melange/Belt-Map-Int.md | 217 +++ docs/api/re/melange/Belt-Map-String.md | 217 +++ docs/api/re/melange/Belt-Map.md | 460 +++++ docs/api/re/melange/Belt-MutableMap-Int.md | 165 ++ docs/api/re/melange/Belt-MutableMap-String.md | 165 ++ docs/api/re/melange/Belt-MutableMap.md | 206 +++ docs/api/re/melange/Belt-MutableQueue.md | 114 ++ docs/api/re/melange/Belt-MutableSet-Int.md | 166 ++ docs/api/re/melange/Belt-MutableSet-String.md | 166 ++ docs/api/re/melange/Belt-MutableSet.md | 189 ++ docs/api/re/melange/Belt-MutableStack.md | 62 + docs/api/re/melange/Belt-Option.md | 200 +++ docs/api/re/melange/Belt-Range.md | 62 + docs/api/re/melange/Belt-Result.md | 165 ++ docs/api/re/melange/Belt-Set-Dict.md | 197 +++ docs/api/re/melange/Belt-Set-Int.md | 163 ++ docs/api/re/melange/Belt-Set-String.md | 163 ++ docs/api/re/melange/Belt-Set.md | 377 ++++ docs/api/re/melange/Belt-SortArray-Int.md | 39 + docs/api/re/melange/Belt-SortArray-String.md | 39 + docs/api/re/melange/Belt-SortArray.md | 81 + docs/api/re/melange/Belt.md | 168 ++ docs/api/re/melange/Dom-Storage.md | 30 + docs/api/re/melange/Dom.md | 841 +++++++++ docs/api/re/melange/Js-Array.md | 179 ++ docs/api/re/melange/Js-Bigint.md | 71 + docs/api/re/melange/Js-Blob.md | 54 + docs/api/re/melange/Js-Console.md | 72 + docs/api/re/melange/Js-Date.md | 319 ++++ docs/api/re/melange/Js-Dict.md | 74 + docs/api/re/melange/Js-Exn.md | 78 + docs/api/re/melange/Js-File.md | 72 + docs/api/re/melange/Js-Float.md | 140 ++ docs/api/re/melange/Js-FormData.md | 90 + docs/api/re/melange/Js-Global.md | 150 ++ docs/api/re/melange/Js-Int.md | 79 + docs/api/re/melange/Js-Iterator.md | 25 + docs/api/re/melange/Js-Json.md | 285 +++ docs/api/re/melange/Js-Map.md | 49 + docs/api/re/melange/Js-Math.md | 299 ++++ docs/api/re/melange/Js-Null.md | 74 + docs/api/re/melange/Js-Nullable.md | 79 + docs/api/re/melange/Js-Obj.md | 19 + docs/api/re/melange/Js-Promise.md | 57 + docs/api/re/melange/Js-Re.md | 178 ++ docs/api/re/melange/Js-Set.md | 43 + docs/api/re/melange/Js-String.md | 464 +++++ .../re/melange/Js-Typed_array-ArrayBuffer.md | 20 + .../api/re/melange/Js-Typed_array-DataView.md | 108 ++ .../re/melange/Js-Typed_array-Float32Array.md | 165 ++ .../re/melange/Js-Typed_array-Float64Array.md | 165 ++ .../re/melange/Js-Typed_array-Int16Array.md | 165 ++ .../re/melange/Js-Typed_array-Int32Array.md | 165 ++ .../re/melange/Js-Typed_array-Int8Array.md | 165 ++ .../re/melange/Js-Typed_array-Uint16Array.md | 165 ++ .../re/melange/Js-Typed_array-Uint32Array.md | 165 ++ .../re/melange/Js-Typed_array-Uint8Array.md | 165 ++ .../Js-Typed_array-Uint8ClampedArray.md | 165 ++ docs/api/re/melange/Js-Typed_array.md | 44 + docs/api/re/melange/Js-Types.md | 109 ++ docs/api/re/melange/Js-Undefined.md | 79 + docs/api/re/melange/Js-WeakMap.md | 25 + docs/api/re/melange/Js-WeakSet.md | 22 + docs/api/re/melange/Js.md | 320 ++++ docs/api/re/melange/Node-Buffer.md | 56 + docs/api/re/melange/Node-Child_process.md | 30 + docs/api/re/melange/Node-Fs-Watch.md | 33 + docs/api/re/melange/Node-Fs.md | 110 ++ docs/api/re/melange/Node-Module.md | 8 + docs/api/re/melange/Node-Path.md | 56 + docs/api/re/melange/Node-Process.md | 38 + docs/api/re/melange/Node.md | 73 + docs/api/re/melange/Stdlib-Arg.md | 261 +++ docs/api/re/melange/Stdlib-Array.md | 373 ++++ docs/api/re/melange/Stdlib-ArrayLabels.md | 383 ++++ docs/api/re/melange/Stdlib-Atomic.md | 144 ++ docs/api/re/melange/Stdlib-Bool.md | 83 + docs/api/re/melange/Stdlib-Buffer.md | 282 +++ docs/api/re/melange/Stdlib-Bytes.md | 683 +++++++ docs/api/re/melange/Stdlib-BytesLabels.md | 695 ++++++++ docs/api/re/melange/Stdlib-Char.md | 61 + docs/api/re/melange/Stdlib-Complex.md | 106 ++ docs/api/re/melange/Stdlib-Digest-BLAKE128.md | 78 + docs/api/re/melange/Stdlib-Digest-BLAKE256.md | 78 + docs/api/re/melange/Stdlib-Digest-BLAKE512.md | 78 + docs/api/re/melange/Stdlib-Digest-MD5.md | 78 + .../re/melange/Stdlib-Digest-module-type-S.md | 78 + docs/api/re/melange/Stdlib-Digest.md | 120 ++ docs/api/re/melange/Stdlib-Domain-DLS.md | 45 + docs/api/re/melange/Stdlib-Domain.md | 89 + docs/api/re/melange/Stdlib-Dynarray.md | 582 ++++++ docs/api/re/melange/Stdlib-Either.md | 115 ++ docs/api/re/melange/Stdlib-Filename.md | 167 ++ docs/api/re/melange/Stdlib-Float-Array.md | 330 ++++ docs/api/re/melange/Stdlib-Float.md | 482 +++++ docs/api/re/melange/Stdlib-Format.md | 1401 +++++++++++++++ docs/api/re/melange/Stdlib-Fun.md | 51 + docs/api/re/melange/Stdlib-Gc-Memprof.md | 113 ++ docs/api/re/melange/Stdlib-Gc.md | 295 ++++ .../Stdlib-Hashtbl-Make-argument-1-H.md | 21 + docs/api/re/melange/Stdlib-Hashtbl-Make.md | 96 + .../Stdlib-Hashtbl-MakeSeeded-argument-1-H.md | 17 + .../re/melange/Stdlib-Hashtbl-MakeSeeded.md | 95 + .../Stdlib-Hashtbl-module-type-HashedType.md | 23 + .../melange/Stdlib-Hashtbl-module-type-S.md | 87 + ...ib-Hashtbl-module-type-SeededHashedType.md | 20 + .../Stdlib-Hashtbl-module-type-SeededS.md | 86 + docs/api/re/melange/Stdlib-Hashtbl.md | 388 ++++ docs/api/re/melange/Stdlib-In_channel.md | 238 +++ docs/api/re/melange/Stdlib-Int.md | 176 ++ docs/api/re/melange/Stdlib-Int32.md | 237 +++ docs/api/re/melange/Stdlib-Int64.md | 257 +++ docs/api/re/melange/Stdlib-LargeFile.md | 23 + docs/api/re/melange/Stdlib-Lazy.md | 95 + docs/api/re/melange/Stdlib-Lexing.md | 136 ++ docs/api/re/melange/Stdlib-List.md | 482 +++++ docs/api/re/melange/Stdlib-ListLabels.md | 482 +++++ .../melange/Stdlib-Map-Make-argument-1-Ord.md | 12 + docs/api/re/melange/Stdlib-Map-Make.md | 315 ++++ .../Stdlib-Map-module-type-OrderedType.md | 14 + .../re/melange/Stdlib-Map-module-type-S.md | 306 ++++ docs/api/re/melange/Stdlib-Map.md | 39 + docs/api/re/melange/Stdlib-Marshal.md | 106 ++ ...ib-MoreLabels-Hashtbl-Make-argument-1-H.md | 21 + .../melange/Stdlib-MoreLabels-Hashtbl-Make.md | 96 + ...eLabels-Hashtbl-MakeSeeded-argument-1-H.md | 17 + .../Stdlib-MoreLabels-Hashtbl-MakeSeeded.md | 95 + ...reLabels-Hashtbl-module-type-HashedType.md | 23 + ...Stdlib-MoreLabels-Hashtbl-module-type-S.md | 87 + ...ls-Hashtbl-module-type-SeededHashedType.md | 20 + ...-MoreLabels-Hashtbl-module-type-SeededS.md | 86 + .../re/melange/Stdlib-MoreLabels-Hashtbl.md | 399 +++++ ...dlib-MoreLabels-Map-Make-argument-1-Ord.md | 12 + .../re/melange/Stdlib-MoreLabels-Map-Make.md | 315 ++++ ...-MoreLabels-Map-module-type-OrderedType.md | 14 + .../Stdlib-MoreLabels-Map-module-type-S.md | 306 ++++ docs/api/re/melange/Stdlib-MoreLabels-Map.md | 41 + ...dlib-MoreLabels-Set-Make-argument-1-Ord.md | 12 + .../re/melange/Stdlib-MoreLabels-Set-Make.md | 297 ++++ ...-MoreLabels-Set-module-type-OrderedType.md | 14 + .../Stdlib-MoreLabels-Set-module-type-S.md | 288 +++ docs/api/re/melange/Stdlib-MoreLabels-Set.md | 41 + docs/api/re/melange/Stdlib-MoreLabels.md | 30 + docs/api/re/melange/Stdlib-Mutex.md | 49 + docs/api/re/melange/Stdlib-Obj-Ephemeron.md | 65 + .../Stdlib-Obj-Extension_constructor.md | 15 + docs/api/re/melange/Stdlib-Obj.md | 139 ++ docs/api/re/melange/Stdlib-Oo.md | 15 + docs/api/re/melange/Stdlib-Option.md | 111 ++ docs/api/re/melange/Stdlib-Out_channel.md | 239 +++ docs/api/re/melange/Stdlib-Parsing.md | 61 + docs/api/re/melange/Stdlib-Printexc-Slot.md | 45 + docs/api/re/melange/Stdlib-Printexc.md | 280 +++ docs/api/re/melange/Stdlib-Printf.md | 144 ++ docs/api/re/melange/Stdlib-Queue.md | 225 +++ docs/api/re/melange/Stdlib-Random-State.md | 50 + docs/api/re/melange/Stdlib-Random.md | 103 ++ docs/api/re/melange/Stdlib-Result.md | 137 ++ docs/api/re/melange/Stdlib-Scanf-Scanning.md | 95 + docs/api/re/melange/Stdlib-Scanf.md | 265 +++ docs/api/re/melange/Stdlib-Seq.md | 624 +++++++ .../melange/Stdlib-Set-Make-argument-1-Ord.md | 12 + docs/api/re/melange/Stdlib-Set-Make.md | 297 ++++ .../Stdlib-Set-module-type-OrderedType.md | 14 + .../re/melange/Stdlib-Set-module-type-S.md | 288 +++ docs/api/re/melange/Stdlib-Set.md | 39 + docs/api/re/melange/Stdlib-Stack.md | 111 ++ docs/api/re/melange/Stdlib-StdLabels.md | 26 + docs/api/re/melange/Stdlib-String.md | 480 +++++ docs/api/re/melange/Stdlib-StringLabels.md | 486 +++++ ...s-Immediate64-Make-argument-1-Immediate.md | 6 + ...mediate64-Make-argument-2-Non_immediate.md | 6 + .../re/melange/Stdlib-Sys-Immediate64-Make.md | 33 + ...b-Sys-Immediate64-module-type-Immediate.md | 6 + ...s-Immediate64-module-type-Non_immediate.md | 6 + docs/api/re/melange/Stdlib-Sys-Immediate64.md | 18 + docs/api/re/melange/Stdlib-Sys.md | 476 +++++ docs/api/re/melange/Stdlib-Type-Id.md | 80 + docs/api/re/melange/Stdlib-Type.md | 36 + docs/api/re/melange/Stdlib-Uchar.md | 144 ++ docs/api/re/melange/Stdlib-Unit.md | 36 + .../melange/Stdlib-Weak-Make-argument-1-H.md | 21 + docs/api/re/melange/Stdlib-Weak-Make.md | 90 + .../re/melange/Stdlib-Weak-module-type-S.md | 81 + docs/api/re/melange/Stdlib-Weak.md | 88 + docs/api/re/melange/Stdlib.md | 1565 +++++++++++++++++ docs/public/api/.gitkeep | 0 418 files changed, 33069 insertions(+), 4 deletions(-) rename docs/api/{ => ml}/melange/Belt-Array.md (100%) rename docs/api/{ => ml}/melange/Belt-Float.md (100%) rename docs/api/{ => ml}/melange/Belt-HashMap-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-HashMap-String.md (100%) rename docs/api/{ => ml}/melange/Belt-HashMap.md (100%) rename docs/api/{ => ml}/melange/Belt-HashSet-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-HashSet-String.md (100%) rename docs/api/{ => ml}/melange/Belt-HashSet.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeComparable-argument-1-M.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeComparable.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeComparableU-argument-1-M.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeComparableU.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeHashable-argument-1-M.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeHashable.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeHashableU-argument-1-M.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-MakeHashableU.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-module-type-Comparable.md (100%) rename docs/api/{ => ml}/melange/Belt-Id-module-type-Hashable.md (100%) rename docs/api/{ => ml}/melange/Belt-Id.md (100%) rename docs/api/{ => ml}/melange/Belt-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-List.md (100%) rename docs/api/{ => ml}/melange/Belt-Map-Dict.md (100%) rename docs/api/{ => ml}/melange/Belt-Map-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-Map-String.md (100%) rename docs/api/{ => ml}/melange/Belt-Map.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableMap-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableMap-String.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableMap.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableQueue.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableSet-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableSet-String.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableSet.md (100%) rename docs/api/{ => ml}/melange/Belt-MutableStack.md (100%) rename docs/api/{ => ml}/melange/Belt-Option.md (100%) rename docs/api/{ => ml}/melange/Belt-Range.md (100%) rename docs/api/{ => ml}/melange/Belt-Result.md (100%) rename docs/api/{ => ml}/melange/Belt-Set-Dict.md (100%) rename docs/api/{ => ml}/melange/Belt-Set-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-Set-String.md (100%) rename docs/api/{ => ml}/melange/Belt-Set.md (100%) rename docs/api/{ => ml}/melange/Belt-SortArray-Int.md (100%) rename docs/api/{ => ml}/melange/Belt-SortArray-String.md (100%) rename docs/api/{ => ml}/melange/Belt-SortArray.md (100%) rename docs/api/{ => ml}/melange/Belt.md (100%) rename docs/api/{ => ml}/melange/Dom-Storage.md (100%) rename docs/api/{ => ml}/melange/Dom.md (100%) rename docs/api/{ => ml}/melange/Js-Array.md (100%) rename docs/api/{ => ml}/melange/Js-Bigint.md (100%) rename docs/api/{ => ml}/melange/Js-Blob.md (100%) rename docs/api/{ => ml}/melange/Js-Console.md (100%) rename docs/api/{ => ml}/melange/Js-Date.md (100%) rename docs/api/{ => ml}/melange/Js-Dict.md (100%) rename docs/api/{ => ml}/melange/Js-Exn.md (100%) rename docs/api/{ => ml}/melange/Js-File.md (100%) rename docs/api/{ => ml}/melange/Js-Float.md (100%) rename docs/api/{ => ml}/melange/Js-FormData.md (100%) rename docs/api/{ => ml}/melange/Js-Global.md (100%) rename docs/api/{ => ml}/melange/Js-Int.md (100%) rename docs/api/{ => ml}/melange/Js-Iterator.md (100%) rename docs/api/{ => ml}/melange/Js-Json.md (100%) rename docs/api/{ => ml}/melange/Js-Map.md (100%) rename docs/api/{ => ml}/melange/Js-Math.md (100%) rename docs/api/{ => ml}/melange/Js-Null.md (100%) rename docs/api/{ => ml}/melange/Js-Nullable.md (100%) rename docs/api/{ => ml}/melange/Js-Obj.md (100%) rename docs/api/{ => ml}/melange/Js-Promise.md (100%) rename docs/api/{ => ml}/melange/Js-Re.md (100%) rename docs/api/{ => ml}/melange/Js-Set.md (100%) rename docs/api/{ => ml}/melange/Js-String.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-ArrayBuffer.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-DataView.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Float32Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Float64Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Int16Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Int32Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Int8Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Uint16Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Uint32Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Uint8Array.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array-Uint8ClampedArray.md (100%) rename docs/api/{ => ml}/melange/Js-Typed_array.md (100%) rename docs/api/{ => ml}/melange/Js-Types.md (100%) rename docs/api/{ => ml}/melange/Js-Undefined.md (100%) rename docs/api/{ => ml}/melange/Js-WeakMap.md (100%) rename docs/api/{ => ml}/melange/Js-WeakSet.md (100%) rename docs/api/{ => ml}/melange/Js.md (100%) rename docs/api/{ => ml}/melange/Node-Buffer.md (100%) rename docs/api/{ => ml}/melange/Node-Child_process.md (100%) rename docs/api/{ => ml}/melange/Node-Fs-Watch.md (100%) rename docs/api/{ => ml}/melange/Node-Fs.md (100%) rename docs/api/{ => ml}/melange/Node-Module.md (100%) rename docs/api/{ => ml}/melange/Node-Path.md (100%) rename docs/api/{ => ml}/melange/Node-Process.md (100%) rename docs/api/{ => ml}/melange/Node.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Arg.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Array.md (100%) rename docs/api/{ => ml}/melange/Stdlib-ArrayLabels.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Atomic.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Bool.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Buffer.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Bytes.md (100%) rename docs/api/{ => ml}/melange/Stdlib-BytesLabels.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Char.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Complex.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Digest-BLAKE128.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Digest-BLAKE256.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Digest-BLAKE512.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Digest-MD5.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Digest-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Digest.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Domain-DLS.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Domain.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Dynarray.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Either.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Filename.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Float-Array.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Float.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Format.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Fun.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Gc-Memprof.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Gc.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-Make-argument-1-H.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-MakeSeeded.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-module-type-HashedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl-module-type-SeededS.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Hashtbl.md (100%) rename docs/api/{ => ml}/melange/Stdlib-In_channel.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Int.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Int32.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Int64.md (100%) rename docs/api/{ => ml}/melange/Stdlib-LargeFile.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Lazy.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Lexing.md (100%) rename docs/api/{ => ml}/melange/Stdlib-List.md (100%) rename docs/api/{ => ml}/melange/Stdlib-ListLabels.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Map-Make-argument-1-Ord.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Map-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Map-module-type-OrderedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Map-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Map.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Marshal.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Hashtbl.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Map-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Map-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Map.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Set-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Set-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels-Set.md (100%) rename docs/api/{ => ml}/melange/Stdlib-MoreLabels.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Mutex.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Obj-Ephemeron.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Obj-Extension_constructor.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Obj.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Oo.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Option.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Out_channel.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Parsing.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Printexc-Slot.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Printexc.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Printf.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Queue.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Random-State.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Random.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Result.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Scanf-Scanning.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Scanf.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Seq.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Set-Make-argument-1-Ord.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Set-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Set-module-type-OrderedType.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Set-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Set.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Stack.md (100%) rename docs/api/{ => ml}/melange/Stdlib-StdLabels.md (100%) rename docs/api/{ => ml}/melange/Stdlib-String.md (100%) rename docs/api/{ => ml}/melange/Stdlib-StringLabels.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Sys-Immediate64-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Sys-Immediate64.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Sys.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Type-Id.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Type.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Uchar.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Unit.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Weak-Make-argument-1-H.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Weak-Make.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Weak-module-type-S.md (100%) rename docs/api/{ => ml}/melange/Stdlib-Weak.md (100%) rename docs/api/{ => ml}/melange/Stdlib.md (100%) create mode 100644 docs/api/re/melange/Belt-Array.md create mode 100644 docs/api/re/melange/Belt-Float.md create mode 100644 docs/api/re/melange/Belt-HashMap-Int.md create mode 100644 docs/api/re/melange/Belt-HashMap-String.md create mode 100644 docs/api/re/melange/Belt-HashMap.md create mode 100644 docs/api/re/melange/Belt-HashSet-Int.md create mode 100644 docs/api/re/melange/Belt-HashSet-String.md create mode 100644 docs/api/re/melange/Belt-HashSet.md create mode 100644 docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md create mode 100644 docs/api/re/melange/Belt-Id-MakeComparable.md create mode 100644 docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md create mode 100644 docs/api/re/melange/Belt-Id-MakeComparableU.md create mode 100644 docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md create mode 100644 docs/api/re/melange/Belt-Id-MakeHashable.md create mode 100644 docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md create mode 100644 docs/api/re/melange/Belt-Id-MakeHashableU.md create mode 100644 docs/api/re/melange/Belt-Id-module-type-Comparable.md create mode 100644 docs/api/re/melange/Belt-Id-module-type-Hashable.md create mode 100644 docs/api/re/melange/Belt-Id.md create mode 100644 docs/api/re/melange/Belt-Int.md create mode 100644 docs/api/re/melange/Belt-List.md create mode 100644 docs/api/re/melange/Belt-Map-Dict.md create mode 100644 docs/api/re/melange/Belt-Map-Int.md create mode 100644 docs/api/re/melange/Belt-Map-String.md create mode 100644 docs/api/re/melange/Belt-Map.md create mode 100644 docs/api/re/melange/Belt-MutableMap-Int.md create mode 100644 docs/api/re/melange/Belt-MutableMap-String.md create mode 100644 docs/api/re/melange/Belt-MutableMap.md create mode 100644 docs/api/re/melange/Belt-MutableQueue.md create mode 100644 docs/api/re/melange/Belt-MutableSet-Int.md create mode 100644 docs/api/re/melange/Belt-MutableSet-String.md create mode 100644 docs/api/re/melange/Belt-MutableSet.md create mode 100644 docs/api/re/melange/Belt-MutableStack.md create mode 100644 docs/api/re/melange/Belt-Option.md create mode 100644 docs/api/re/melange/Belt-Range.md create mode 100644 docs/api/re/melange/Belt-Result.md create mode 100644 docs/api/re/melange/Belt-Set-Dict.md create mode 100644 docs/api/re/melange/Belt-Set-Int.md create mode 100644 docs/api/re/melange/Belt-Set-String.md create mode 100644 docs/api/re/melange/Belt-Set.md create mode 100644 docs/api/re/melange/Belt-SortArray-Int.md create mode 100644 docs/api/re/melange/Belt-SortArray-String.md create mode 100644 docs/api/re/melange/Belt-SortArray.md create mode 100644 docs/api/re/melange/Belt.md create mode 100644 docs/api/re/melange/Dom-Storage.md create mode 100644 docs/api/re/melange/Dom.md create mode 100644 docs/api/re/melange/Js-Array.md create mode 100644 docs/api/re/melange/Js-Bigint.md create mode 100644 docs/api/re/melange/Js-Blob.md create mode 100644 docs/api/re/melange/Js-Console.md create mode 100644 docs/api/re/melange/Js-Date.md create mode 100644 docs/api/re/melange/Js-Dict.md create mode 100644 docs/api/re/melange/Js-Exn.md create mode 100644 docs/api/re/melange/Js-File.md create mode 100644 docs/api/re/melange/Js-Float.md create mode 100644 docs/api/re/melange/Js-FormData.md create mode 100644 docs/api/re/melange/Js-Global.md create mode 100644 docs/api/re/melange/Js-Int.md create mode 100644 docs/api/re/melange/Js-Iterator.md create mode 100644 docs/api/re/melange/Js-Json.md create mode 100644 docs/api/re/melange/Js-Map.md create mode 100644 docs/api/re/melange/Js-Math.md create mode 100644 docs/api/re/melange/Js-Null.md create mode 100644 docs/api/re/melange/Js-Nullable.md create mode 100644 docs/api/re/melange/Js-Obj.md create mode 100644 docs/api/re/melange/Js-Promise.md create mode 100644 docs/api/re/melange/Js-Re.md create mode 100644 docs/api/re/melange/Js-Set.md create mode 100644 docs/api/re/melange/Js-String.md create mode 100644 docs/api/re/melange/Js-Typed_array-ArrayBuffer.md create mode 100644 docs/api/re/melange/Js-Typed_array-DataView.md create mode 100644 docs/api/re/melange/Js-Typed_array-Float32Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Float64Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Int16Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Int32Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Int8Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Uint16Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Uint32Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Uint8Array.md create mode 100644 docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md create mode 100644 docs/api/re/melange/Js-Typed_array.md create mode 100644 docs/api/re/melange/Js-Types.md create mode 100644 docs/api/re/melange/Js-Undefined.md create mode 100644 docs/api/re/melange/Js-WeakMap.md create mode 100644 docs/api/re/melange/Js-WeakSet.md create mode 100644 docs/api/re/melange/Js.md create mode 100644 docs/api/re/melange/Node-Buffer.md create mode 100644 docs/api/re/melange/Node-Child_process.md create mode 100644 docs/api/re/melange/Node-Fs-Watch.md create mode 100644 docs/api/re/melange/Node-Fs.md create mode 100644 docs/api/re/melange/Node-Module.md create mode 100644 docs/api/re/melange/Node-Path.md create mode 100644 docs/api/re/melange/Node-Process.md create mode 100644 docs/api/re/melange/Node.md create mode 100644 docs/api/re/melange/Stdlib-Arg.md create mode 100644 docs/api/re/melange/Stdlib-Array.md create mode 100644 docs/api/re/melange/Stdlib-ArrayLabels.md create mode 100644 docs/api/re/melange/Stdlib-Atomic.md create mode 100644 docs/api/re/melange/Stdlib-Bool.md create mode 100644 docs/api/re/melange/Stdlib-Buffer.md create mode 100644 docs/api/re/melange/Stdlib-Bytes.md create mode 100644 docs/api/re/melange/Stdlib-BytesLabels.md create mode 100644 docs/api/re/melange/Stdlib-Char.md create mode 100644 docs/api/re/melange/Stdlib-Complex.md create mode 100644 docs/api/re/melange/Stdlib-Digest-BLAKE128.md create mode 100644 docs/api/re/melange/Stdlib-Digest-BLAKE256.md create mode 100644 docs/api/re/melange/Stdlib-Digest-BLAKE512.md create mode 100644 docs/api/re/melange/Stdlib-Digest-MD5.md create mode 100644 docs/api/re/melange/Stdlib-Digest-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-Digest.md create mode 100644 docs/api/re/melange/Stdlib-Domain-DLS.md create mode 100644 docs/api/re/melange/Stdlib-Domain.md create mode 100644 docs/api/re/melange/Stdlib-Dynarray.md create mode 100644 docs/api/re/melange/Stdlib-Either.md create mode 100644 docs/api/re/melange/Stdlib-Filename.md create mode 100644 docs/api/re/melange/Stdlib-Float-Array.md create mode 100644 docs/api/re/melange/Stdlib-Float.md create mode 100644 docs/api/re/melange/Stdlib-Format.md create mode 100644 docs/api/re/melange/Stdlib-Fun.md create mode 100644 docs/api/re/melange/Stdlib-Gc-Memprof.md create mode 100644 docs/api/re/melange/Stdlib-Gc.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-Make.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md create mode 100644 docs/api/re/melange/Stdlib-Hashtbl.md create mode 100644 docs/api/re/melange/Stdlib-In_channel.md create mode 100644 docs/api/re/melange/Stdlib-Int.md create mode 100644 docs/api/re/melange/Stdlib-Int32.md create mode 100644 docs/api/re/melange/Stdlib-Int64.md create mode 100644 docs/api/re/melange/Stdlib-LargeFile.md create mode 100644 docs/api/re/melange/Stdlib-Lazy.md create mode 100644 docs/api/re/melange/Stdlib-Lexing.md create mode 100644 docs/api/re/melange/Stdlib-List.md create mode 100644 docs/api/re/melange/Stdlib-ListLabels.md create mode 100644 docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md create mode 100644 docs/api/re/melange/Stdlib-Map-Make.md create mode 100644 docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md create mode 100644 docs/api/re/melange/Stdlib-Map-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-Map.md create mode 100644 docs/api/re/melange/Stdlib-Marshal.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set.md create mode 100644 docs/api/re/melange/Stdlib-MoreLabels.md create mode 100644 docs/api/re/melange/Stdlib-Mutex.md create mode 100644 docs/api/re/melange/Stdlib-Obj-Ephemeron.md create mode 100644 docs/api/re/melange/Stdlib-Obj-Extension_constructor.md create mode 100644 docs/api/re/melange/Stdlib-Obj.md create mode 100644 docs/api/re/melange/Stdlib-Oo.md create mode 100644 docs/api/re/melange/Stdlib-Option.md create mode 100644 docs/api/re/melange/Stdlib-Out_channel.md create mode 100644 docs/api/re/melange/Stdlib-Parsing.md create mode 100644 docs/api/re/melange/Stdlib-Printexc-Slot.md create mode 100644 docs/api/re/melange/Stdlib-Printexc.md create mode 100644 docs/api/re/melange/Stdlib-Printf.md create mode 100644 docs/api/re/melange/Stdlib-Queue.md create mode 100644 docs/api/re/melange/Stdlib-Random-State.md create mode 100644 docs/api/re/melange/Stdlib-Random.md create mode 100644 docs/api/re/melange/Stdlib-Result.md create mode 100644 docs/api/re/melange/Stdlib-Scanf-Scanning.md create mode 100644 docs/api/re/melange/Stdlib-Scanf.md create mode 100644 docs/api/re/melange/Stdlib-Seq.md create mode 100644 docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md create mode 100644 docs/api/re/melange/Stdlib-Set-Make.md create mode 100644 docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md create mode 100644 docs/api/re/melange/Stdlib-Set-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-Set.md create mode 100644 docs/api/re/melange/Stdlib-Stack.md create mode 100644 docs/api/re/melange/Stdlib-StdLabels.md create mode 100644 docs/api/re/melange/Stdlib-String.md create mode 100644 docs/api/re/melange/Stdlib-StringLabels.md create mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md create mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md create mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md create mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md create mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md create mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64.md create mode 100644 docs/api/re/melange/Stdlib-Sys.md create mode 100644 docs/api/re/melange/Stdlib-Type-Id.md create mode 100644 docs/api/re/melange/Stdlib-Type.md create mode 100644 docs/api/re/melange/Stdlib-Uchar.md create mode 100644 docs/api/re/melange/Stdlib-Unit.md create mode 100644 docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md create mode 100644 docs/api/re/melange/Stdlib-Weak-Make.md create mode 100644 docs/api/re/melange/Stdlib-Weak-module-type-S.md create mode 100644 docs/api/re/melange/Stdlib-Weak.md create mode 100644 docs/api/re/melange/Stdlib.md delete mode 100644 docs/public/api/.gitkeep diff --git a/.gitignore b/.gitignore index e5108f192..b70010a93 100644 --- a/.gitignore +++ b/.gitignore @@ -7,9 +7,5 @@ node_modules docs/.vitepress/cache docs/.vitepress/dist docs/public/playground -docs/public/api/ml -docs/public/api/re -docs/api/ml -docs/api/re melange.dev diff --git a/docs/api/melange/Belt-Array.md b/docs/api/ml/melange/Belt-Array.md similarity index 100% rename from docs/api/melange/Belt-Array.md rename to docs/api/ml/melange/Belt-Array.md diff --git a/docs/api/melange/Belt-Float.md b/docs/api/ml/melange/Belt-Float.md similarity index 100% rename from docs/api/melange/Belt-Float.md rename to docs/api/ml/melange/Belt-Float.md diff --git a/docs/api/melange/Belt-HashMap-Int.md b/docs/api/ml/melange/Belt-HashMap-Int.md similarity index 100% rename from docs/api/melange/Belt-HashMap-Int.md rename to docs/api/ml/melange/Belt-HashMap-Int.md diff --git a/docs/api/melange/Belt-HashMap-String.md b/docs/api/ml/melange/Belt-HashMap-String.md similarity index 100% rename from docs/api/melange/Belt-HashMap-String.md rename to docs/api/ml/melange/Belt-HashMap-String.md diff --git a/docs/api/melange/Belt-HashMap.md b/docs/api/ml/melange/Belt-HashMap.md similarity index 100% rename from docs/api/melange/Belt-HashMap.md rename to docs/api/ml/melange/Belt-HashMap.md diff --git a/docs/api/melange/Belt-HashSet-Int.md b/docs/api/ml/melange/Belt-HashSet-Int.md similarity index 100% rename from docs/api/melange/Belt-HashSet-Int.md rename to docs/api/ml/melange/Belt-HashSet-Int.md diff --git a/docs/api/melange/Belt-HashSet-String.md b/docs/api/ml/melange/Belt-HashSet-String.md similarity index 100% rename from docs/api/melange/Belt-HashSet-String.md rename to docs/api/ml/melange/Belt-HashSet-String.md diff --git a/docs/api/melange/Belt-HashSet.md b/docs/api/ml/melange/Belt-HashSet.md similarity index 100% rename from docs/api/melange/Belt-HashSet.md rename to docs/api/ml/melange/Belt-HashSet.md diff --git a/docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeComparable-argument-1-M.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeComparable-argument-1-M.md rename to docs/api/ml/melange/Belt-Id-MakeComparable-argument-1-M.md diff --git a/docs/api/melange/Belt-Id-MakeComparable.md b/docs/api/ml/melange/Belt-Id-MakeComparable.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeComparable.md rename to docs/api/ml/melange/Belt-Id-MakeComparable.md diff --git a/docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeComparableU-argument-1-M.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeComparableU-argument-1-M.md rename to docs/api/ml/melange/Belt-Id-MakeComparableU-argument-1-M.md diff --git a/docs/api/melange/Belt-Id-MakeComparableU.md b/docs/api/ml/melange/Belt-Id-MakeComparableU.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeComparableU.md rename to docs/api/ml/melange/Belt-Id-MakeComparableU.md diff --git a/docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeHashable-argument-1-M.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeHashable-argument-1-M.md rename to docs/api/ml/melange/Belt-Id-MakeHashable-argument-1-M.md diff --git a/docs/api/melange/Belt-Id-MakeHashable.md b/docs/api/ml/melange/Belt-Id-MakeHashable.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeHashable.md rename to docs/api/ml/melange/Belt-Id-MakeHashable.md diff --git a/docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeHashableU-argument-1-M.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeHashableU-argument-1-M.md rename to docs/api/ml/melange/Belt-Id-MakeHashableU-argument-1-M.md diff --git a/docs/api/melange/Belt-Id-MakeHashableU.md b/docs/api/ml/melange/Belt-Id-MakeHashableU.md similarity index 100% rename from docs/api/melange/Belt-Id-MakeHashableU.md rename to docs/api/ml/melange/Belt-Id-MakeHashableU.md diff --git a/docs/api/melange/Belt-Id-module-type-Comparable.md b/docs/api/ml/melange/Belt-Id-module-type-Comparable.md similarity index 100% rename from docs/api/melange/Belt-Id-module-type-Comparable.md rename to docs/api/ml/melange/Belt-Id-module-type-Comparable.md diff --git a/docs/api/melange/Belt-Id-module-type-Hashable.md b/docs/api/ml/melange/Belt-Id-module-type-Hashable.md similarity index 100% rename from docs/api/melange/Belt-Id-module-type-Hashable.md rename to docs/api/ml/melange/Belt-Id-module-type-Hashable.md diff --git a/docs/api/melange/Belt-Id.md b/docs/api/ml/melange/Belt-Id.md similarity index 100% rename from docs/api/melange/Belt-Id.md rename to docs/api/ml/melange/Belt-Id.md diff --git a/docs/api/melange/Belt-Int.md b/docs/api/ml/melange/Belt-Int.md similarity index 100% rename from docs/api/melange/Belt-Int.md rename to docs/api/ml/melange/Belt-Int.md diff --git a/docs/api/melange/Belt-List.md b/docs/api/ml/melange/Belt-List.md similarity index 100% rename from docs/api/melange/Belt-List.md rename to docs/api/ml/melange/Belt-List.md diff --git a/docs/api/melange/Belt-Map-Dict.md b/docs/api/ml/melange/Belt-Map-Dict.md similarity index 100% rename from docs/api/melange/Belt-Map-Dict.md rename to docs/api/ml/melange/Belt-Map-Dict.md diff --git a/docs/api/melange/Belt-Map-Int.md b/docs/api/ml/melange/Belt-Map-Int.md similarity index 100% rename from docs/api/melange/Belt-Map-Int.md rename to docs/api/ml/melange/Belt-Map-Int.md diff --git a/docs/api/melange/Belt-Map-String.md b/docs/api/ml/melange/Belt-Map-String.md similarity index 100% rename from docs/api/melange/Belt-Map-String.md rename to docs/api/ml/melange/Belt-Map-String.md diff --git a/docs/api/melange/Belt-Map.md b/docs/api/ml/melange/Belt-Map.md similarity index 100% rename from docs/api/melange/Belt-Map.md rename to docs/api/ml/melange/Belt-Map.md diff --git a/docs/api/melange/Belt-MutableMap-Int.md b/docs/api/ml/melange/Belt-MutableMap-Int.md similarity index 100% rename from docs/api/melange/Belt-MutableMap-Int.md rename to docs/api/ml/melange/Belt-MutableMap-Int.md diff --git a/docs/api/melange/Belt-MutableMap-String.md b/docs/api/ml/melange/Belt-MutableMap-String.md similarity index 100% rename from docs/api/melange/Belt-MutableMap-String.md rename to docs/api/ml/melange/Belt-MutableMap-String.md diff --git a/docs/api/melange/Belt-MutableMap.md b/docs/api/ml/melange/Belt-MutableMap.md similarity index 100% rename from docs/api/melange/Belt-MutableMap.md rename to docs/api/ml/melange/Belt-MutableMap.md diff --git a/docs/api/melange/Belt-MutableQueue.md b/docs/api/ml/melange/Belt-MutableQueue.md similarity index 100% rename from docs/api/melange/Belt-MutableQueue.md rename to docs/api/ml/melange/Belt-MutableQueue.md diff --git a/docs/api/melange/Belt-MutableSet-Int.md b/docs/api/ml/melange/Belt-MutableSet-Int.md similarity index 100% rename from docs/api/melange/Belt-MutableSet-Int.md rename to docs/api/ml/melange/Belt-MutableSet-Int.md diff --git a/docs/api/melange/Belt-MutableSet-String.md b/docs/api/ml/melange/Belt-MutableSet-String.md similarity index 100% rename from docs/api/melange/Belt-MutableSet-String.md rename to docs/api/ml/melange/Belt-MutableSet-String.md diff --git a/docs/api/melange/Belt-MutableSet.md b/docs/api/ml/melange/Belt-MutableSet.md similarity index 100% rename from docs/api/melange/Belt-MutableSet.md rename to docs/api/ml/melange/Belt-MutableSet.md diff --git a/docs/api/melange/Belt-MutableStack.md b/docs/api/ml/melange/Belt-MutableStack.md similarity index 100% rename from docs/api/melange/Belt-MutableStack.md rename to docs/api/ml/melange/Belt-MutableStack.md diff --git a/docs/api/melange/Belt-Option.md b/docs/api/ml/melange/Belt-Option.md similarity index 100% rename from docs/api/melange/Belt-Option.md rename to docs/api/ml/melange/Belt-Option.md diff --git a/docs/api/melange/Belt-Range.md b/docs/api/ml/melange/Belt-Range.md similarity index 100% rename from docs/api/melange/Belt-Range.md rename to docs/api/ml/melange/Belt-Range.md diff --git a/docs/api/melange/Belt-Result.md b/docs/api/ml/melange/Belt-Result.md similarity index 100% rename from docs/api/melange/Belt-Result.md rename to docs/api/ml/melange/Belt-Result.md diff --git a/docs/api/melange/Belt-Set-Dict.md b/docs/api/ml/melange/Belt-Set-Dict.md similarity index 100% rename from docs/api/melange/Belt-Set-Dict.md rename to docs/api/ml/melange/Belt-Set-Dict.md diff --git a/docs/api/melange/Belt-Set-Int.md b/docs/api/ml/melange/Belt-Set-Int.md similarity index 100% rename from docs/api/melange/Belt-Set-Int.md rename to docs/api/ml/melange/Belt-Set-Int.md diff --git a/docs/api/melange/Belt-Set-String.md b/docs/api/ml/melange/Belt-Set-String.md similarity index 100% rename from docs/api/melange/Belt-Set-String.md rename to docs/api/ml/melange/Belt-Set-String.md diff --git a/docs/api/melange/Belt-Set.md b/docs/api/ml/melange/Belt-Set.md similarity index 100% rename from docs/api/melange/Belt-Set.md rename to docs/api/ml/melange/Belt-Set.md diff --git a/docs/api/melange/Belt-SortArray-Int.md b/docs/api/ml/melange/Belt-SortArray-Int.md similarity index 100% rename from docs/api/melange/Belt-SortArray-Int.md rename to docs/api/ml/melange/Belt-SortArray-Int.md diff --git a/docs/api/melange/Belt-SortArray-String.md b/docs/api/ml/melange/Belt-SortArray-String.md similarity index 100% rename from docs/api/melange/Belt-SortArray-String.md rename to docs/api/ml/melange/Belt-SortArray-String.md diff --git a/docs/api/melange/Belt-SortArray.md b/docs/api/ml/melange/Belt-SortArray.md similarity index 100% rename from docs/api/melange/Belt-SortArray.md rename to docs/api/ml/melange/Belt-SortArray.md diff --git a/docs/api/melange/Belt.md b/docs/api/ml/melange/Belt.md similarity index 100% rename from docs/api/melange/Belt.md rename to docs/api/ml/melange/Belt.md diff --git a/docs/api/melange/Dom-Storage.md b/docs/api/ml/melange/Dom-Storage.md similarity index 100% rename from docs/api/melange/Dom-Storage.md rename to docs/api/ml/melange/Dom-Storage.md diff --git a/docs/api/melange/Dom.md b/docs/api/ml/melange/Dom.md similarity index 100% rename from docs/api/melange/Dom.md rename to docs/api/ml/melange/Dom.md diff --git a/docs/api/melange/Js-Array.md b/docs/api/ml/melange/Js-Array.md similarity index 100% rename from docs/api/melange/Js-Array.md rename to docs/api/ml/melange/Js-Array.md diff --git a/docs/api/melange/Js-Bigint.md b/docs/api/ml/melange/Js-Bigint.md similarity index 100% rename from docs/api/melange/Js-Bigint.md rename to docs/api/ml/melange/Js-Bigint.md diff --git a/docs/api/melange/Js-Blob.md b/docs/api/ml/melange/Js-Blob.md similarity index 100% rename from docs/api/melange/Js-Blob.md rename to docs/api/ml/melange/Js-Blob.md diff --git a/docs/api/melange/Js-Console.md b/docs/api/ml/melange/Js-Console.md similarity index 100% rename from docs/api/melange/Js-Console.md rename to docs/api/ml/melange/Js-Console.md diff --git a/docs/api/melange/Js-Date.md b/docs/api/ml/melange/Js-Date.md similarity index 100% rename from docs/api/melange/Js-Date.md rename to docs/api/ml/melange/Js-Date.md diff --git a/docs/api/melange/Js-Dict.md b/docs/api/ml/melange/Js-Dict.md similarity index 100% rename from docs/api/melange/Js-Dict.md rename to docs/api/ml/melange/Js-Dict.md diff --git a/docs/api/melange/Js-Exn.md b/docs/api/ml/melange/Js-Exn.md similarity index 100% rename from docs/api/melange/Js-Exn.md rename to docs/api/ml/melange/Js-Exn.md diff --git a/docs/api/melange/Js-File.md b/docs/api/ml/melange/Js-File.md similarity index 100% rename from docs/api/melange/Js-File.md rename to docs/api/ml/melange/Js-File.md diff --git a/docs/api/melange/Js-Float.md b/docs/api/ml/melange/Js-Float.md similarity index 100% rename from docs/api/melange/Js-Float.md rename to docs/api/ml/melange/Js-Float.md diff --git a/docs/api/melange/Js-FormData.md b/docs/api/ml/melange/Js-FormData.md similarity index 100% rename from docs/api/melange/Js-FormData.md rename to docs/api/ml/melange/Js-FormData.md diff --git a/docs/api/melange/Js-Global.md b/docs/api/ml/melange/Js-Global.md similarity index 100% rename from docs/api/melange/Js-Global.md rename to docs/api/ml/melange/Js-Global.md diff --git a/docs/api/melange/Js-Int.md b/docs/api/ml/melange/Js-Int.md similarity index 100% rename from docs/api/melange/Js-Int.md rename to docs/api/ml/melange/Js-Int.md diff --git a/docs/api/melange/Js-Iterator.md b/docs/api/ml/melange/Js-Iterator.md similarity index 100% rename from docs/api/melange/Js-Iterator.md rename to docs/api/ml/melange/Js-Iterator.md diff --git a/docs/api/melange/Js-Json.md b/docs/api/ml/melange/Js-Json.md similarity index 100% rename from docs/api/melange/Js-Json.md rename to docs/api/ml/melange/Js-Json.md diff --git a/docs/api/melange/Js-Map.md b/docs/api/ml/melange/Js-Map.md similarity index 100% rename from docs/api/melange/Js-Map.md rename to docs/api/ml/melange/Js-Map.md diff --git a/docs/api/melange/Js-Math.md b/docs/api/ml/melange/Js-Math.md similarity index 100% rename from docs/api/melange/Js-Math.md rename to docs/api/ml/melange/Js-Math.md diff --git a/docs/api/melange/Js-Null.md b/docs/api/ml/melange/Js-Null.md similarity index 100% rename from docs/api/melange/Js-Null.md rename to docs/api/ml/melange/Js-Null.md diff --git a/docs/api/melange/Js-Nullable.md b/docs/api/ml/melange/Js-Nullable.md similarity index 100% rename from docs/api/melange/Js-Nullable.md rename to docs/api/ml/melange/Js-Nullable.md diff --git a/docs/api/melange/Js-Obj.md b/docs/api/ml/melange/Js-Obj.md similarity index 100% rename from docs/api/melange/Js-Obj.md rename to docs/api/ml/melange/Js-Obj.md diff --git a/docs/api/melange/Js-Promise.md b/docs/api/ml/melange/Js-Promise.md similarity index 100% rename from docs/api/melange/Js-Promise.md rename to docs/api/ml/melange/Js-Promise.md diff --git a/docs/api/melange/Js-Re.md b/docs/api/ml/melange/Js-Re.md similarity index 100% rename from docs/api/melange/Js-Re.md rename to docs/api/ml/melange/Js-Re.md diff --git a/docs/api/melange/Js-Set.md b/docs/api/ml/melange/Js-Set.md similarity index 100% rename from docs/api/melange/Js-Set.md rename to docs/api/ml/melange/Js-Set.md diff --git a/docs/api/melange/Js-String.md b/docs/api/ml/melange/Js-String.md similarity index 100% rename from docs/api/melange/Js-String.md rename to docs/api/ml/melange/Js-String.md diff --git a/docs/api/melange/Js-Typed_array-ArrayBuffer.md b/docs/api/ml/melange/Js-Typed_array-ArrayBuffer.md similarity index 100% rename from docs/api/melange/Js-Typed_array-ArrayBuffer.md rename to docs/api/ml/melange/Js-Typed_array-ArrayBuffer.md diff --git a/docs/api/melange/Js-Typed_array-DataView.md b/docs/api/ml/melange/Js-Typed_array-DataView.md similarity index 100% rename from docs/api/melange/Js-Typed_array-DataView.md rename to docs/api/ml/melange/Js-Typed_array-DataView.md diff --git a/docs/api/melange/Js-Typed_array-Float32Array.md b/docs/api/ml/melange/Js-Typed_array-Float32Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Float32Array.md rename to docs/api/ml/melange/Js-Typed_array-Float32Array.md diff --git a/docs/api/melange/Js-Typed_array-Float64Array.md b/docs/api/ml/melange/Js-Typed_array-Float64Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Float64Array.md rename to docs/api/ml/melange/Js-Typed_array-Float64Array.md diff --git a/docs/api/melange/Js-Typed_array-Int16Array.md b/docs/api/ml/melange/Js-Typed_array-Int16Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Int16Array.md rename to docs/api/ml/melange/Js-Typed_array-Int16Array.md diff --git a/docs/api/melange/Js-Typed_array-Int32Array.md b/docs/api/ml/melange/Js-Typed_array-Int32Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Int32Array.md rename to docs/api/ml/melange/Js-Typed_array-Int32Array.md diff --git a/docs/api/melange/Js-Typed_array-Int8Array.md b/docs/api/ml/melange/Js-Typed_array-Int8Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Int8Array.md rename to docs/api/ml/melange/Js-Typed_array-Int8Array.md diff --git a/docs/api/melange/Js-Typed_array-Uint16Array.md b/docs/api/ml/melange/Js-Typed_array-Uint16Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Uint16Array.md rename to docs/api/ml/melange/Js-Typed_array-Uint16Array.md diff --git a/docs/api/melange/Js-Typed_array-Uint32Array.md b/docs/api/ml/melange/Js-Typed_array-Uint32Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Uint32Array.md rename to docs/api/ml/melange/Js-Typed_array-Uint32Array.md diff --git a/docs/api/melange/Js-Typed_array-Uint8Array.md b/docs/api/ml/melange/Js-Typed_array-Uint8Array.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Uint8Array.md rename to docs/api/ml/melange/Js-Typed_array-Uint8Array.md diff --git a/docs/api/melange/Js-Typed_array-Uint8ClampedArray.md b/docs/api/ml/melange/Js-Typed_array-Uint8ClampedArray.md similarity index 100% rename from docs/api/melange/Js-Typed_array-Uint8ClampedArray.md rename to docs/api/ml/melange/Js-Typed_array-Uint8ClampedArray.md diff --git a/docs/api/melange/Js-Typed_array.md b/docs/api/ml/melange/Js-Typed_array.md similarity index 100% rename from docs/api/melange/Js-Typed_array.md rename to docs/api/ml/melange/Js-Typed_array.md diff --git a/docs/api/melange/Js-Types.md b/docs/api/ml/melange/Js-Types.md similarity index 100% rename from docs/api/melange/Js-Types.md rename to docs/api/ml/melange/Js-Types.md diff --git a/docs/api/melange/Js-Undefined.md b/docs/api/ml/melange/Js-Undefined.md similarity index 100% rename from docs/api/melange/Js-Undefined.md rename to docs/api/ml/melange/Js-Undefined.md diff --git a/docs/api/melange/Js-WeakMap.md b/docs/api/ml/melange/Js-WeakMap.md similarity index 100% rename from docs/api/melange/Js-WeakMap.md rename to docs/api/ml/melange/Js-WeakMap.md diff --git a/docs/api/melange/Js-WeakSet.md b/docs/api/ml/melange/Js-WeakSet.md similarity index 100% rename from docs/api/melange/Js-WeakSet.md rename to docs/api/ml/melange/Js-WeakSet.md diff --git a/docs/api/melange/Js.md b/docs/api/ml/melange/Js.md similarity index 100% rename from docs/api/melange/Js.md rename to docs/api/ml/melange/Js.md diff --git a/docs/api/melange/Node-Buffer.md b/docs/api/ml/melange/Node-Buffer.md similarity index 100% rename from docs/api/melange/Node-Buffer.md rename to docs/api/ml/melange/Node-Buffer.md diff --git a/docs/api/melange/Node-Child_process.md b/docs/api/ml/melange/Node-Child_process.md similarity index 100% rename from docs/api/melange/Node-Child_process.md rename to docs/api/ml/melange/Node-Child_process.md diff --git a/docs/api/melange/Node-Fs-Watch.md b/docs/api/ml/melange/Node-Fs-Watch.md similarity index 100% rename from docs/api/melange/Node-Fs-Watch.md rename to docs/api/ml/melange/Node-Fs-Watch.md diff --git a/docs/api/melange/Node-Fs.md b/docs/api/ml/melange/Node-Fs.md similarity index 100% rename from docs/api/melange/Node-Fs.md rename to docs/api/ml/melange/Node-Fs.md diff --git a/docs/api/melange/Node-Module.md b/docs/api/ml/melange/Node-Module.md similarity index 100% rename from docs/api/melange/Node-Module.md rename to docs/api/ml/melange/Node-Module.md diff --git a/docs/api/melange/Node-Path.md b/docs/api/ml/melange/Node-Path.md similarity index 100% rename from docs/api/melange/Node-Path.md rename to docs/api/ml/melange/Node-Path.md diff --git a/docs/api/melange/Node-Process.md b/docs/api/ml/melange/Node-Process.md similarity index 100% rename from docs/api/melange/Node-Process.md rename to docs/api/ml/melange/Node-Process.md diff --git a/docs/api/melange/Node.md b/docs/api/ml/melange/Node.md similarity index 100% rename from docs/api/melange/Node.md rename to docs/api/ml/melange/Node.md diff --git a/docs/api/melange/Stdlib-Arg.md b/docs/api/ml/melange/Stdlib-Arg.md similarity index 100% rename from docs/api/melange/Stdlib-Arg.md rename to docs/api/ml/melange/Stdlib-Arg.md diff --git a/docs/api/melange/Stdlib-Array.md b/docs/api/ml/melange/Stdlib-Array.md similarity index 100% rename from docs/api/melange/Stdlib-Array.md rename to docs/api/ml/melange/Stdlib-Array.md diff --git a/docs/api/melange/Stdlib-ArrayLabels.md b/docs/api/ml/melange/Stdlib-ArrayLabels.md similarity index 100% rename from docs/api/melange/Stdlib-ArrayLabels.md rename to docs/api/ml/melange/Stdlib-ArrayLabels.md diff --git a/docs/api/melange/Stdlib-Atomic.md b/docs/api/ml/melange/Stdlib-Atomic.md similarity index 100% rename from docs/api/melange/Stdlib-Atomic.md rename to docs/api/ml/melange/Stdlib-Atomic.md diff --git a/docs/api/melange/Stdlib-Bool.md b/docs/api/ml/melange/Stdlib-Bool.md similarity index 100% rename from docs/api/melange/Stdlib-Bool.md rename to docs/api/ml/melange/Stdlib-Bool.md diff --git a/docs/api/melange/Stdlib-Buffer.md b/docs/api/ml/melange/Stdlib-Buffer.md similarity index 100% rename from docs/api/melange/Stdlib-Buffer.md rename to docs/api/ml/melange/Stdlib-Buffer.md diff --git a/docs/api/melange/Stdlib-Bytes.md b/docs/api/ml/melange/Stdlib-Bytes.md similarity index 100% rename from docs/api/melange/Stdlib-Bytes.md rename to docs/api/ml/melange/Stdlib-Bytes.md diff --git a/docs/api/melange/Stdlib-BytesLabels.md b/docs/api/ml/melange/Stdlib-BytesLabels.md similarity index 100% rename from docs/api/melange/Stdlib-BytesLabels.md rename to docs/api/ml/melange/Stdlib-BytesLabels.md diff --git a/docs/api/melange/Stdlib-Char.md b/docs/api/ml/melange/Stdlib-Char.md similarity index 100% rename from docs/api/melange/Stdlib-Char.md rename to docs/api/ml/melange/Stdlib-Char.md diff --git a/docs/api/melange/Stdlib-Complex.md b/docs/api/ml/melange/Stdlib-Complex.md similarity index 100% rename from docs/api/melange/Stdlib-Complex.md rename to docs/api/ml/melange/Stdlib-Complex.md diff --git a/docs/api/melange/Stdlib-Digest-BLAKE128.md b/docs/api/ml/melange/Stdlib-Digest-BLAKE128.md similarity index 100% rename from docs/api/melange/Stdlib-Digest-BLAKE128.md rename to docs/api/ml/melange/Stdlib-Digest-BLAKE128.md diff --git a/docs/api/melange/Stdlib-Digest-BLAKE256.md b/docs/api/ml/melange/Stdlib-Digest-BLAKE256.md similarity index 100% rename from docs/api/melange/Stdlib-Digest-BLAKE256.md rename to docs/api/ml/melange/Stdlib-Digest-BLAKE256.md diff --git a/docs/api/melange/Stdlib-Digest-BLAKE512.md b/docs/api/ml/melange/Stdlib-Digest-BLAKE512.md similarity index 100% rename from docs/api/melange/Stdlib-Digest-BLAKE512.md rename to docs/api/ml/melange/Stdlib-Digest-BLAKE512.md diff --git a/docs/api/melange/Stdlib-Digest-MD5.md b/docs/api/ml/melange/Stdlib-Digest-MD5.md similarity index 100% rename from docs/api/melange/Stdlib-Digest-MD5.md rename to docs/api/ml/melange/Stdlib-Digest-MD5.md diff --git a/docs/api/melange/Stdlib-Digest-module-type-S.md b/docs/api/ml/melange/Stdlib-Digest-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-Digest-module-type-S.md rename to docs/api/ml/melange/Stdlib-Digest-module-type-S.md diff --git a/docs/api/melange/Stdlib-Digest.md b/docs/api/ml/melange/Stdlib-Digest.md similarity index 100% rename from docs/api/melange/Stdlib-Digest.md rename to docs/api/ml/melange/Stdlib-Digest.md diff --git a/docs/api/melange/Stdlib-Domain-DLS.md b/docs/api/ml/melange/Stdlib-Domain-DLS.md similarity index 100% rename from docs/api/melange/Stdlib-Domain-DLS.md rename to docs/api/ml/melange/Stdlib-Domain-DLS.md diff --git a/docs/api/melange/Stdlib-Domain.md b/docs/api/ml/melange/Stdlib-Domain.md similarity index 100% rename from docs/api/melange/Stdlib-Domain.md rename to docs/api/ml/melange/Stdlib-Domain.md diff --git a/docs/api/melange/Stdlib-Dynarray.md b/docs/api/ml/melange/Stdlib-Dynarray.md similarity index 100% rename from docs/api/melange/Stdlib-Dynarray.md rename to docs/api/ml/melange/Stdlib-Dynarray.md diff --git a/docs/api/melange/Stdlib-Either.md b/docs/api/ml/melange/Stdlib-Either.md similarity index 100% rename from docs/api/melange/Stdlib-Either.md rename to docs/api/ml/melange/Stdlib-Either.md diff --git a/docs/api/melange/Stdlib-Filename.md b/docs/api/ml/melange/Stdlib-Filename.md similarity index 100% rename from docs/api/melange/Stdlib-Filename.md rename to docs/api/ml/melange/Stdlib-Filename.md diff --git a/docs/api/melange/Stdlib-Float-Array.md b/docs/api/ml/melange/Stdlib-Float-Array.md similarity index 100% rename from docs/api/melange/Stdlib-Float-Array.md rename to docs/api/ml/melange/Stdlib-Float-Array.md diff --git a/docs/api/melange/Stdlib-Float.md b/docs/api/ml/melange/Stdlib-Float.md similarity index 100% rename from docs/api/melange/Stdlib-Float.md rename to docs/api/ml/melange/Stdlib-Float.md diff --git a/docs/api/melange/Stdlib-Format.md b/docs/api/ml/melange/Stdlib-Format.md similarity index 100% rename from docs/api/melange/Stdlib-Format.md rename to docs/api/ml/melange/Stdlib-Format.md diff --git a/docs/api/melange/Stdlib-Fun.md b/docs/api/ml/melange/Stdlib-Fun.md similarity index 100% rename from docs/api/melange/Stdlib-Fun.md rename to docs/api/ml/melange/Stdlib-Fun.md diff --git a/docs/api/melange/Stdlib-Gc-Memprof.md b/docs/api/ml/melange/Stdlib-Gc-Memprof.md similarity index 100% rename from docs/api/melange/Stdlib-Gc-Memprof.md rename to docs/api/ml/melange/Stdlib-Gc-Memprof.md diff --git a/docs/api/melange/Stdlib-Gc.md b/docs/api/ml/melange/Stdlib-Gc.md similarity index 100% rename from docs/api/melange/Stdlib-Gc.md rename to docs/api/ml/melange/Stdlib-Gc.md diff --git a/docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md b/docs/api/ml/melange/Stdlib-Hashtbl-Make-argument-1-H.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-Make-argument-1-H.md rename to docs/api/ml/melange/Stdlib-Hashtbl-Make-argument-1-H.md diff --git a/docs/api/melange/Stdlib-Hashtbl-Make.md b/docs/api/ml/melange/Stdlib-Hashtbl-Make.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-Make.md rename to docs/api/ml/melange/Stdlib-Hashtbl-Make.md diff --git a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md rename to docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md diff --git a/docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md b/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-MakeSeeded.md rename to docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded.md diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-HashedType.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-module-type-HashedType.md rename to docs/api/ml/melange/Stdlib-Hashtbl-module-type-HashedType.md diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-S.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-module-type-S.md rename to docs/api/ml/melange/Stdlib-Hashtbl-module-type-S.md diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md rename to docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md diff --git a/docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededS.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl-module-type-SeededS.md rename to docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededS.md diff --git a/docs/api/melange/Stdlib-Hashtbl.md b/docs/api/ml/melange/Stdlib-Hashtbl.md similarity index 100% rename from docs/api/melange/Stdlib-Hashtbl.md rename to docs/api/ml/melange/Stdlib-Hashtbl.md diff --git a/docs/api/melange/Stdlib-In_channel.md b/docs/api/ml/melange/Stdlib-In_channel.md similarity index 100% rename from docs/api/melange/Stdlib-In_channel.md rename to docs/api/ml/melange/Stdlib-In_channel.md diff --git a/docs/api/melange/Stdlib-Int.md b/docs/api/ml/melange/Stdlib-Int.md similarity index 100% rename from docs/api/melange/Stdlib-Int.md rename to docs/api/ml/melange/Stdlib-Int.md diff --git a/docs/api/melange/Stdlib-Int32.md b/docs/api/ml/melange/Stdlib-Int32.md similarity index 100% rename from docs/api/melange/Stdlib-Int32.md rename to docs/api/ml/melange/Stdlib-Int32.md diff --git a/docs/api/melange/Stdlib-Int64.md b/docs/api/ml/melange/Stdlib-Int64.md similarity index 100% rename from docs/api/melange/Stdlib-Int64.md rename to docs/api/ml/melange/Stdlib-Int64.md diff --git a/docs/api/melange/Stdlib-LargeFile.md b/docs/api/ml/melange/Stdlib-LargeFile.md similarity index 100% rename from docs/api/melange/Stdlib-LargeFile.md rename to docs/api/ml/melange/Stdlib-LargeFile.md diff --git a/docs/api/melange/Stdlib-Lazy.md b/docs/api/ml/melange/Stdlib-Lazy.md similarity index 100% rename from docs/api/melange/Stdlib-Lazy.md rename to docs/api/ml/melange/Stdlib-Lazy.md diff --git a/docs/api/melange/Stdlib-Lexing.md b/docs/api/ml/melange/Stdlib-Lexing.md similarity index 100% rename from docs/api/melange/Stdlib-Lexing.md rename to docs/api/ml/melange/Stdlib-Lexing.md diff --git a/docs/api/melange/Stdlib-List.md b/docs/api/ml/melange/Stdlib-List.md similarity index 100% rename from docs/api/melange/Stdlib-List.md rename to docs/api/ml/melange/Stdlib-List.md diff --git a/docs/api/melange/Stdlib-ListLabels.md b/docs/api/ml/melange/Stdlib-ListLabels.md similarity index 100% rename from docs/api/melange/Stdlib-ListLabels.md rename to docs/api/ml/melange/Stdlib-ListLabels.md diff --git a/docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-Map-Make-argument-1-Ord.md similarity index 100% rename from docs/api/melange/Stdlib-Map-Make-argument-1-Ord.md rename to docs/api/ml/melange/Stdlib-Map-Make-argument-1-Ord.md diff --git a/docs/api/melange/Stdlib-Map-Make.md b/docs/api/ml/melange/Stdlib-Map-Make.md similarity index 100% rename from docs/api/melange/Stdlib-Map-Make.md rename to docs/api/ml/melange/Stdlib-Map-Make.md diff --git a/docs/api/melange/Stdlib-Map-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-Map-module-type-OrderedType.md similarity index 100% rename from docs/api/melange/Stdlib-Map-module-type-OrderedType.md rename to docs/api/ml/melange/Stdlib-Map-module-type-OrderedType.md diff --git a/docs/api/melange/Stdlib-Map-module-type-S.md b/docs/api/ml/melange/Stdlib-Map-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-Map-module-type-S.md rename to docs/api/ml/melange/Stdlib-Map-module-type-S.md diff --git a/docs/api/melange/Stdlib-Map.md b/docs/api/ml/melange/Stdlib-Map.md similarity index 100% rename from docs/api/melange/Stdlib-Map.md rename to docs/api/ml/melange/Stdlib-Map.md diff --git a/docs/api/melange/Stdlib-Marshal.md b/docs/api/ml/melange/Stdlib-Marshal.md similarity index 100% rename from docs/api/melange/Stdlib-Marshal.md rename to docs/api/ml/melange/Stdlib-Marshal.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-Make.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Hashtbl.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Hashtbl.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-Make.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Map-Make.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Map-Make.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Map-module-type-S.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-S.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Map.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Map.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Map.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-Make.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Set-Make.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Set-Make.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Set-module-type-S.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-S.md diff --git a/docs/api/melange/Stdlib-MoreLabels-Set.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels-Set.md rename to docs/api/ml/melange/Stdlib-MoreLabels-Set.md diff --git a/docs/api/melange/Stdlib-MoreLabels.md b/docs/api/ml/melange/Stdlib-MoreLabels.md similarity index 100% rename from docs/api/melange/Stdlib-MoreLabels.md rename to docs/api/ml/melange/Stdlib-MoreLabels.md diff --git a/docs/api/melange/Stdlib-Mutex.md b/docs/api/ml/melange/Stdlib-Mutex.md similarity index 100% rename from docs/api/melange/Stdlib-Mutex.md rename to docs/api/ml/melange/Stdlib-Mutex.md diff --git a/docs/api/melange/Stdlib-Obj-Ephemeron.md b/docs/api/ml/melange/Stdlib-Obj-Ephemeron.md similarity index 100% rename from docs/api/melange/Stdlib-Obj-Ephemeron.md rename to docs/api/ml/melange/Stdlib-Obj-Ephemeron.md diff --git a/docs/api/melange/Stdlib-Obj-Extension_constructor.md b/docs/api/ml/melange/Stdlib-Obj-Extension_constructor.md similarity index 100% rename from docs/api/melange/Stdlib-Obj-Extension_constructor.md rename to docs/api/ml/melange/Stdlib-Obj-Extension_constructor.md diff --git a/docs/api/melange/Stdlib-Obj.md b/docs/api/ml/melange/Stdlib-Obj.md similarity index 100% rename from docs/api/melange/Stdlib-Obj.md rename to docs/api/ml/melange/Stdlib-Obj.md diff --git a/docs/api/melange/Stdlib-Oo.md b/docs/api/ml/melange/Stdlib-Oo.md similarity index 100% rename from docs/api/melange/Stdlib-Oo.md rename to docs/api/ml/melange/Stdlib-Oo.md diff --git a/docs/api/melange/Stdlib-Option.md b/docs/api/ml/melange/Stdlib-Option.md similarity index 100% rename from docs/api/melange/Stdlib-Option.md rename to docs/api/ml/melange/Stdlib-Option.md diff --git a/docs/api/melange/Stdlib-Out_channel.md b/docs/api/ml/melange/Stdlib-Out_channel.md similarity index 100% rename from docs/api/melange/Stdlib-Out_channel.md rename to docs/api/ml/melange/Stdlib-Out_channel.md diff --git a/docs/api/melange/Stdlib-Parsing.md b/docs/api/ml/melange/Stdlib-Parsing.md similarity index 100% rename from docs/api/melange/Stdlib-Parsing.md rename to docs/api/ml/melange/Stdlib-Parsing.md diff --git a/docs/api/melange/Stdlib-Printexc-Slot.md b/docs/api/ml/melange/Stdlib-Printexc-Slot.md similarity index 100% rename from docs/api/melange/Stdlib-Printexc-Slot.md rename to docs/api/ml/melange/Stdlib-Printexc-Slot.md diff --git a/docs/api/melange/Stdlib-Printexc.md b/docs/api/ml/melange/Stdlib-Printexc.md similarity index 100% rename from docs/api/melange/Stdlib-Printexc.md rename to docs/api/ml/melange/Stdlib-Printexc.md diff --git a/docs/api/melange/Stdlib-Printf.md b/docs/api/ml/melange/Stdlib-Printf.md similarity index 100% rename from docs/api/melange/Stdlib-Printf.md rename to docs/api/ml/melange/Stdlib-Printf.md diff --git a/docs/api/melange/Stdlib-Queue.md b/docs/api/ml/melange/Stdlib-Queue.md similarity index 100% rename from docs/api/melange/Stdlib-Queue.md rename to docs/api/ml/melange/Stdlib-Queue.md diff --git a/docs/api/melange/Stdlib-Random-State.md b/docs/api/ml/melange/Stdlib-Random-State.md similarity index 100% rename from docs/api/melange/Stdlib-Random-State.md rename to docs/api/ml/melange/Stdlib-Random-State.md diff --git a/docs/api/melange/Stdlib-Random.md b/docs/api/ml/melange/Stdlib-Random.md similarity index 100% rename from docs/api/melange/Stdlib-Random.md rename to docs/api/ml/melange/Stdlib-Random.md diff --git a/docs/api/melange/Stdlib-Result.md b/docs/api/ml/melange/Stdlib-Result.md similarity index 100% rename from docs/api/melange/Stdlib-Result.md rename to docs/api/ml/melange/Stdlib-Result.md diff --git a/docs/api/melange/Stdlib-Scanf-Scanning.md b/docs/api/ml/melange/Stdlib-Scanf-Scanning.md similarity index 100% rename from docs/api/melange/Stdlib-Scanf-Scanning.md rename to docs/api/ml/melange/Stdlib-Scanf-Scanning.md diff --git a/docs/api/melange/Stdlib-Scanf.md b/docs/api/ml/melange/Stdlib-Scanf.md similarity index 100% rename from docs/api/melange/Stdlib-Scanf.md rename to docs/api/ml/melange/Stdlib-Scanf.md diff --git a/docs/api/melange/Stdlib-Seq.md b/docs/api/ml/melange/Stdlib-Seq.md similarity index 100% rename from docs/api/melange/Stdlib-Seq.md rename to docs/api/ml/melange/Stdlib-Seq.md diff --git a/docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-Set-Make-argument-1-Ord.md similarity index 100% rename from docs/api/melange/Stdlib-Set-Make-argument-1-Ord.md rename to docs/api/ml/melange/Stdlib-Set-Make-argument-1-Ord.md diff --git a/docs/api/melange/Stdlib-Set-Make.md b/docs/api/ml/melange/Stdlib-Set-Make.md similarity index 100% rename from docs/api/melange/Stdlib-Set-Make.md rename to docs/api/ml/melange/Stdlib-Set-Make.md diff --git a/docs/api/melange/Stdlib-Set-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-Set-module-type-OrderedType.md similarity index 100% rename from docs/api/melange/Stdlib-Set-module-type-OrderedType.md rename to docs/api/ml/melange/Stdlib-Set-module-type-OrderedType.md diff --git a/docs/api/melange/Stdlib-Set-module-type-S.md b/docs/api/ml/melange/Stdlib-Set-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-Set-module-type-S.md rename to docs/api/ml/melange/Stdlib-Set-module-type-S.md diff --git a/docs/api/melange/Stdlib-Set.md b/docs/api/ml/melange/Stdlib-Set.md similarity index 100% rename from docs/api/melange/Stdlib-Set.md rename to docs/api/ml/melange/Stdlib-Set.md diff --git a/docs/api/melange/Stdlib-Stack.md b/docs/api/ml/melange/Stdlib-Stack.md similarity index 100% rename from docs/api/melange/Stdlib-Stack.md rename to docs/api/ml/melange/Stdlib-Stack.md diff --git a/docs/api/melange/Stdlib-StdLabels.md b/docs/api/ml/melange/Stdlib-StdLabels.md similarity index 100% rename from docs/api/melange/Stdlib-StdLabels.md rename to docs/api/ml/melange/Stdlib-StdLabels.md diff --git a/docs/api/melange/Stdlib-String.md b/docs/api/ml/melange/Stdlib-String.md similarity index 100% rename from docs/api/melange/Stdlib-String.md rename to docs/api/ml/melange/Stdlib-String.md diff --git a/docs/api/melange/Stdlib-StringLabels.md b/docs/api/ml/melange/Stdlib-StringLabels.md similarity index 100% rename from docs/api/melange/Stdlib-StringLabels.md rename to docs/api/ml/melange/Stdlib-StringLabels.md diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md similarity index 100% rename from docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md rename to docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md similarity index 100% rename from docs/api/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md rename to docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-Make.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make.md similarity index 100% rename from docs/api/melange/Stdlib-Sys-Immediate64-Make.md rename to docs/api/ml/melange/Stdlib-Sys-Immediate64-Make.md diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md similarity index 100% rename from docs/api/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md rename to docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md diff --git a/docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md similarity index 100% rename from docs/api/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md rename to docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md diff --git a/docs/api/melange/Stdlib-Sys-Immediate64.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64.md similarity index 100% rename from docs/api/melange/Stdlib-Sys-Immediate64.md rename to docs/api/ml/melange/Stdlib-Sys-Immediate64.md diff --git a/docs/api/melange/Stdlib-Sys.md b/docs/api/ml/melange/Stdlib-Sys.md similarity index 100% rename from docs/api/melange/Stdlib-Sys.md rename to docs/api/ml/melange/Stdlib-Sys.md diff --git a/docs/api/melange/Stdlib-Type-Id.md b/docs/api/ml/melange/Stdlib-Type-Id.md similarity index 100% rename from docs/api/melange/Stdlib-Type-Id.md rename to docs/api/ml/melange/Stdlib-Type-Id.md diff --git a/docs/api/melange/Stdlib-Type.md b/docs/api/ml/melange/Stdlib-Type.md similarity index 100% rename from docs/api/melange/Stdlib-Type.md rename to docs/api/ml/melange/Stdlib-Type.md diff --git a/docs/api/melange/Stdlib-Uchar.md b/docs/api/ml/melange/Stdlib-Uchar.md similarity index 100% rename from docs/api/melange/Stdlib-Uchar.md rename to docs/api/ml/melange/Stdlib-Uchar.md diff --git a/docs/api/melange/Stdlib-Unit.md b/docs/api/ml/melange/Stdlib-Unit.md similarity index 100% rename from docs/api/melange/Stdlib-Unit.md rename to docs/api/ml/melange/Stdlib-Unit.md diff --git a/docs/api/melange/Stdlib-Weak-Make-argument-1-H.md b/docs/api/ml/melange/Stdlib-Weak-Make-argument-1-H.md similarity index 100% rename from docs/api/melange/Stdlib-Weak-Make-argument-1-H.md rename to docs/api/ml/melange/Stdlib-Weak-Make-argument-1-H.md diff --git a/docs/api/melange/Stdlib-Weak-Make.md b/docs/api/ml/melange/Stdlib-Weak-Make.md similarity index 100% rename from docs/api/melange/Stdlib-Weak-Make.md rename to docs/api/ml/melange/Stdlib-Weak-Make.md diff --git a/docs/api/melange/Stdlib-Weak-module-type-S.md b/docs/api/ml/melange/Stdlib-Weak-module-type-S.md similarity index 100% rename from docs/api/melange/Stdlib-Weak-module-type-S.md rename to docs/api/ml/melange/Stdlib-Weak-module-type-S.md diff --git a/docs/api/melange/Stdlib-Weak.md b/docs/api/ml/melange/Stdlib-Weak.md similarity index 100% rename from docs/api/melange/Stdlib-Weak.md rename to docs/api/ml/melange/Stdlib-Weak.md diff --git a/docs/api/melange/Stdlib.md b/docs/api/ml/melange/Stdlib.md similarity index 100% rename from docs/api/melange/Stdlib.md rename to docs/api/ml/melange/Stdlib.md diff --git a/docs/api/re/melange/Belt-Array.md b/docs/api/re/melange/Belt-Array.md new file mode 100644 index 000000000..31970e565 --- /dev/null +++ b/docs/api/re/melange/Belt-Array.md @@ -0,0 +1,654 @@ + +# Module `Belt.Array` + +[`Belt.Array`](#) + +**mutable array**: Utilities functions + +[`Belt.Array`](#) Utililites for Array functions + +``` +type 'a t = 'a array +``` +``` +val length : 'a t -> int +``` +`length xs` return the size of the array + +``` +val size : 'a t -> int +``` +**See** [`length`](./#val-length) + +``` +val get : 'a t -> int -> 'a option +``` +`get arr i` + +If `i <= 0 <= length arr`;returns `Some value` where `value` is the item at index `i` If `i` is out of range;returns `None` + +```ocaml + Belt.Array.get [|"a";"b";"c"|] 0 = Some "a";; + Belt.Array.get [|"a";"b";"c"|] 3 = None;; + Belt.Array.get [|"a";"b";"c"|] (-1) = None;; +``` +``` +val getExn : 'a t -> int -> 'a +``` +`getExn arr i` + +**raise** an exception if `i` is out of range;otherwise return the value at index `i` in `arr` + +``` +val getUnsafe : 'a t -> int -> 'a +``` +`getUnsafe arr i` + +**Unsafe** + +no bounds checking;this would cause type error if `i` does not stay within range + +``` +val getUndefined : 'a t -> int -> 'a Js.undefined +``` +`getUndefined arr i` + +It does the samething in the runtime as [`getUnsafe`](./#val-getUnsafe); it is *type safe* since the return type still track whether it is in range or not + +``` +val set : 'a t -> int -> 'a -> bool +``` +`set arr n x` modifies `arr` in place; it replaces the nth element of `arr` with `x` + +returns false means not updated due to out of range +``` +val setExn : 'a t -> int -> 'a -> unit +``` +`setExn arr i x` **raise** an exception if `i` is out of range + +``` +val setUnsafe : 'a t -> int -> 'a -> unit +``` +``` +val shuffleInPlace : 'a t -> unit +``` +`shuffleInPlace arr` randomly re-orders the items in `arr` + +``` +val shuffle : 'a t -> 'a t +``` +`shuffle xs` + +returns a fresh array with items in original array randomly shuffled +``` +val reverseInPlace : 'a t -> unit +``` +`reverseInPlace arr` reverses items in `arr` in place + +```ocaml + let arr = [|10;11;12;13;14|];; + let () = reverseInPlace arr;; + arr = [|14;13;12;11;10|];; +``` +``` +val reverse : 'a t -> 'a t +``` +`reverse arr` + +returns a fresh array with items in arr in reverse order +```ocaml + reverse [|10;11;12;13;14|] = [|14;13;12;11;10|];; +``` +``` +val makeUninitialized : int -> 'a Js.undefined array +``` +`makeUninitialized n` creates an array of length `n` filled with the undefined value. You must specify the type of data that will eventually fill the array. + +```ocaml + let arr: string Js.undefined array = makeUninitialized 5;; + getExn arr 0 = Js.undefined;; +``` +``` +val makeUninitializedUnsafe : int -> 'a t +``` +\`makeUninitializedUnsafe n\` + +**Unsafe** + +```ocaml +let arr = Belt.Array.makeUninitializedUnsafe 5;; +let () = Js.log(Belt.Array.getExn arr 0);; (* undefined *) +Belt.Array.setExn arr 0 "example";; +let () = Js.log(Belt.Array.getExn arr 0 = "example");; +``` +``` +val make : int -> 'a -> 'a t +``` +`make n e` return an array of size `n` filled with value `e` + +returns an empty array when n is negative. +``` +val range : int -> int -> int t +``` +`range start finish` create an inclusive array + +```ocaml + range 0 3 = [|0;1;2;3|];; + range 3 0 = [||] ;; + range 3 3 = [|3|];; +``` +``` +val rangeBy : int -> int -> step:int -> int t +``` +`rangeBy start finish ~step` + +returns empty array when step is 0 or negative it also return empty array when start \> finish +```ocaml + rangeBy 0 10 ~step:3 = [|0;3;6;9|];; + rangeBy 0 12 ~step:3 = [|0;3;6;9;12|];; + rangeBy 33 0 ~step:1 = [||];; + rangeBy 33 0 ~step:(-1) = [||];; + rangeBy 3 12 ~step:(-1) = [||];; + rangeBy 3 3 ~step:0 = [||] ;; + rangeBy 3 3 ~step:(1) = [|3|] ;; +``` +``` +val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val makeBy : int -> (int -> 'a) -> 'a t +``` +`makeBy n f` + +return an empty array when `n` is negative return an array of size `n` populated by `f i` start from `0` to `n - 1` + +```ocaml + makeBy 5 (fun i -> i) = [|0;1;2;3;4|];; + makeBy 5 (fun i -> i * i) = [|0;1;4;9;16|] +``` +``` +val makeByAndShuffleU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val makeByAndShuffle : int -> (int -> 'a) -> 'a t +``` +`makeByAndShuffle n f` + +Equivalent to `shuffle (makeBy n f)` + +``` +val zip : 'a t -> 'b array -> ('a * 'b) array +``` +`zip a b` + +Create an array of pairs from corresponding elements of `a` and `b`. Stop with the shorter array + +```ocaml + zip [|1;2|] [|3;4;5|] = [|(1, 3);(2, 4)|] +``` +``` +val zipByU : 'a t -> 'b array -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c array +``` +``` +val zipBy : 'a t -> 'b array -> ('a -> 'b -> 'c) -> 'c array +``` +`zipBy xs ys f` + +Create an array by applying `f` to corresponding elements of `xs` and `ys` Stops with shorter array + +Equivalent to `map (zip xs ys) (fun (a,b) -> f a b) ` + +```ocaml + zipBy [|1;2;3|] [|4;5|] (fun a b -> 2 * a + b) = [|6;9|];; +``` +``` +val unzip : ('a * 'b) array -> 'a t * 'b array +``` +`unzip a` takes an array of pairs and creates a pair of arrays. The first array contains all the first items of the pairs; the second array contains all the second items. + +```ocaml + unzip [|(1,2) ; (3,4)|] = ([|1;3|], [|2;4|]);; + unzip [|(1,2) ; (3,4) ; (5,6) ; (7,8)|] = ([|1;3;5;7|], [|2;4;6;8|]);; +``` +``` +val concat : 'a t -> 'a t -> 'a t +``` +`concat xs ys` + +returns a fresh array containing the concatenation of the arrays v1 and v2;so even if v1 or v2 is empty;it can not be shared +```ocaml + concat [|1;2;3|] [|4;5|] = [|1;2;3;4;5|];; + concat [| |] [|"a";"b";"c"|] = [|"a";"b";"c"|];; +``` +``` +val concatMany : 'a t t -> 'a t +``` +`concatMany xss` + +returns a fresh array as the concatenation of xss (an array of arrays) +```ocaml + concatMany [| [|1;2;3|]; [|4;5;6|]; [|7;8|] |] = [|1;2;3;4;5;6;7;8|];; +``` +``` +val slice : 'a t -> offset:int -> len:int -> 'a t +``` +`slice xs offset len` creates a new array with the `len` elements of `xs` starting at `offset` for + +`offset` can be negative;and is evaluated as `length xs - offset` `slice xs -1 1` means get the last element as a singleton array + +`slice xs (-len) len` will return a copy of the array + +if the array does not have enough data;`slice` extracts through the end of sequence. + +if `len` is negative;returns the empty array. + +```ocaml + slice [|10;11;12;13;14;15;16|] ~offset: 2 ~len: 3 = [|12;13;14|];; + slice [|10;11;12;13;14;15;16|] ~offset: (-4) ~len: 3 = [|13;14;15|];; + slice [|10;11;12;13;14;15;16|] ~offset:4 ~len:9 = [|14;15;16|];; +``` +``` +val sliceToEnd : 'a t -> int -> 'a t +``` +`sliceToEnd xs offset` creates a new array with the elements of `xs` starting at `offset` + +`offset` can be negative;and is evaluated as `length xs - offset` `sliceToEnd xs -1` means get the last element as a singleton array + +`sliceToEnd xs 0` will return a copy of the array + +```ocaml + sliceToEnd [|10;11;12;13;14;15;16|] 2 = [|12;13;14;15;16|];; + sliceToEnd [|10;11;12;13;14;15;16|] (-4) = [|13;14;15;16|];; +``` +``` +val copy : 'a t -> 'a t +``` +`copy a` + +returns a copy of a;that is;a fresh array containing the same elements as a. +``` +val fill : 'a t -> offset:int -> len:int -> 'a -> unit +``` +`fill arr ~offset ~len x` + +Modifies `arr` in place, storing `x` in elements number `offset` to `offset + len - 1`. + +`offset` can be negative;and is evaluated as `length arr - offset` + +`fill arr ~offset:(-1) ~len:1` means fill the last element, if the array does not have enough data;`fill` will ignore it + +```ocaml + + let arr = makeBy 5 (fun i -> i) ;; + fill arr ~offset:2 ~len:2 9 ;; + arr = [|0;1;9;9;4|];; + fill arr ~offset:7 ~len:2 8;; + arr = [|0;1;9;9;4|];; +``` +``` +val blit : + src:'a t -> + srcOffset:int -> + dst:'a t -> + dstOffset:int -> + len:int -> + unit +``` +`blit ~src:v1 ~srcOffset:o1 ~dst:v2 ~dstOffset:o2 ~len` + +copies `len` elements from array `v1`;starting at element number `o1`;to array `v2`, starting at element number `o2`. + +It works correctly even if `v1` and `v2` are the same array;and the source and destination chunks overlap. + +`offset` can be negative;`-1` means `len - 1`;if `len + offset` is still negative;it will be set as 0 + +For each of the examples;presume that `v1 = [|10;11;12;13;14;15;16;17|]` and `v2 = [|20;21;22;23;24;25;26;27|]`. The result shown is the content of the destination array. + +```ocaml + Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v2 ~dstOffset: 2 ~len: 3 |. + [|20;21;14;15;16;25;26;27|] + Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v1 ~dstOffset: 2 ~len: 3 |. + [|10;11;14;15;16;15;16;17|] +``` +``` +val blitUnsafe : + src:'a t -> + srcOffset:int -> + dst:'a t -> + dstOffset:int -> + len:int -> + unit +``` +**Unsafe** blit without bounds checking + +``` +val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> unit) -> unit +``` +`forEach xs f` + +Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`;so no new array is created. Use `forEach` when you are primarily concerned with repetitively creating side effects. + +```ocaml + forEach [|"a";"b";"c"|] (fun x -> Js.log("Item: " ^ x));; + (* prints: + Item: a + Item: b + Item: c + *) + + let total = ref 0;; + forEach [|1;2;3;4|] (fun x -> total := !total + x);; + !total = 1 + 2 + 3 + 4;; + +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b array +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b array +``` +`map xs f ` + +returns a new array by calling f for each element of xs from the beginning to end +```ocaml + map [|1;2|] (fun x-> x + 10) = [|11;12|] +``` +``` +val flatMapU : 'a t -> ('a -> 'b t) Js.Fn.arity1 -> 'b t +``` +``` +val flatMap : 'a t -> ('a -> 'b t) -> 'b t +``` +`flatMap xs f` \*\*return\*\* a new array by calling \`f\` for each element of \`xs\` from the beginning to end, and then concatenating the results \``` flatMap `|1;2|` (fun x-\> `|x + 10;x + 20|`) \= `|11;21;12;22|` \``` + +``` +val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option +``` +``` +val getBy : 'a t -> ('a -> bool) -> 'a option +``` +`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. + +```ocaml + getBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 4 + getBy [|15;13;11|] (fun x -> x mod 2 = 0) = None +``` +``` +val getIndexByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> int option +``` +``` +val getIndexBy : 'a t -> ('a -> bool) -> int option +``` +`getIndexBy xs p` returns `Some index` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. + +```ocaml + getIndexBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 1 + getIndexBy [|15;13;11|] (fun x -> x mod 2 = 0) = None +``` +``` +val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t +``` +``` +val keep : 'a t -> ('a -> bool) -> 'a t +``` +`keep xs p ` + +returns a new array that keeps all elements satisfying p +```ocaml + keep [|1;2;3|] (fun x -> x mod 2 = 0) = [|2|] +``` +``` +val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t +``` +``` +val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t +``` +`keepWithIndex xs p ` + +returns a new array that keeps all elements satisfying p. The predicate p takes two arguments: the element from xs and the index starting from 0. +```ocaml + keepWithIndex [|1;2;3|] (fun _x i -> i = 1) = [|2|] +``` +``` +val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b array +``` +``` +val keepMap : 'a t -> ('a -> 'b option) -> 'b array +``` +`keepMap xs p` + +returns a new array that keeps all elements that return a non-None when applied to p +```ocaml + keepMap [|1;2;3|] (fun x -> if x mod 2 = 0 then Some x else None) + = [| 2 |] +``` +``` +val forEachWithIndexU : 'a t -> (int -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEachWithIndex : 'a t -> (int -> 'a -> unit) -> unit +``` +`forEachWithIndex xs f` + +The same as [`forEach`](./#val-forEach); except that `f` is supplied with two arguments: the index starting from 0 and the element from `xs` + +```ocaml + + forEachWithIndex [|"a";"b";"c"|] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; + (* prints: + Item 0 is a + Item 1 is b + Item 2 is c + *) + + let total = ref 0 ;; + forEachWithIndex [|10;11;12;13|] (fun i x -> total := !total + x + i);; + !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; +``` +``` +val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t +``` +`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. + +```ocaml + mapWithIndex [|1;2;3|] (fun i x -> i + x) = + [|0 + 1; 1 + 2; 2 + 3|] +``` +``` +val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t +``` +``` +val partition : 'a t -> ('a -> bool) -> 'a t * 'a t +``` +`partition f a` split array into tuple of two arrays based on predicate f; first of tuple where predicate cause true, second where predicate cause false + +```ocaml + partition [|1;2;3;4;5|] (fun x -> x mod 2 = 0 ) = ([|2;4|], [|1;2;3|]);; + partition [|1;2;3;4;5|] (fun x -> x mod 2 <> 0 ) = ([|1;2;3|], [|2;4|]);; +``` +``` +val reduceU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a +``` +`reduce xs init f` + +Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”;which starts with a value of `init`. `reduce` returns the final value of the accumulator. + +```ocaml + reduce [|2;3;4|] 1 (+) = 10;; + reduce [|"a";"b";"c";"d"|] "" (^) = "abcd";; +``` +``` +val reduceReverseU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduceReverse : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a +``` +`reduceReverse xs init f` + +Works like [`reduce`](./#val-reduce);except that function `f` is applied to each item of `xs` from the last back to the first. + +```ocaml + reduceReverse [|"a";"b";"c";"d"|] "" (^) = "dcba";; +``` +``` +val reduceReverse2U : + 'a t -> + 'b array -> + 'c -> + ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> + 'c +``` +``` +val reduceReverse2 : 'a t -> 'b array -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c +``` +`reduceReverse2 xs ys init f` Reduces two arrays `xs` and `ys`;taking items starting at `min (length xs) (length ys)` down to and including zero. + +```ocaml + reduceReverse2 [|1;2;3|] [|1;2|] 0 (fun acc x y -> acc + x + y) = 6 +``` +``` +val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b +``` +`reduceWithIndex xs f` + +Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the array and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. + +```ocaml + reduceWithIndex [|1;2;3;4|] 0 (fun acc x i -> acc + x + i) = 16; +``` +``` +val joinWithU : 'a t -> string -> ('a -> string) Js.Fn.arity1 -> string +``` +``` +val joinWith : 'a t -> string -> ('a -> string) -> string +``` +`joinWith xs sep toString` + +Concatenates all the elements of `xs` converted to string with `toString`, each separated by `sep`, the string given as the second argument, into a single string. If the array has only one element, then that element will be returned without using the separator. If the array is empty, the empty string will be returned. + +```ocaml + joinWith [|0; 1|] ", " string_of_int = "0, 1" + joinWith [||] " " string_of_int = "" + joinWith [|1|] " " string_of_int = "1" +``` +``` +val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : 'a t -> ('a -> bool) -> bool +``` +`some xs p` + +returns true if at least one of the elements in xs satifies p;where p is a predicate: a function taking an element and returning a bool. +```ocaml + some [|2; 3; 4|] (fun x -> x mod 2 = 1) = true;; + some [|-1; -3; -5|] (fun x -> x > 0) = false;; +``` +``` +val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : 'a t -> ('a -> bool) -> bool +``` +`every xs p` + +returns true if all elements satisfy p;where p is a predicate: a function taking an element and returning a bool. +```ocaml + every [|1; 3; 5|] (fun x -> x mod 2 = 1) = true;; + every [|1; -3; 5|] (fun x -> x > 0) = false;; +``` +``` +val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`every2 xs ys p` returns true if `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + +```ocaml + every2 [|1;2;3|] [|0;1|] (>) = true;; + every2 [||] [|1|] (fun x y -> x > y) = true;; + every2 [|2;3|] [|1|] (fun x y -> x > y) = true;; + every2 [|0;1|] [|5;0|] (fun x y -> x > y) = false; +``` +``` +val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + +```ocaml + some2 [|0;2|] [|1;0;3|] (>) = true ;; + (some2 [||] [|1|] (fun x y -> x > y)) = false;; + (some2 [|2;3|] [|1;4|] (fun x y -> x > y)) = true;; +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +`cmp xs ys f` + +- Compared by length if `length xs <> length ys`;returning \-1 if`length xs < length ys` or 1 if `length xs > length ys` +- Otherwise compare one by one `f x y`. `f` returns +- a negative number if `x` is “less than” `y` +- zero if `x` is “equal to” `y` +- a positive number if `x` is “greater than” `y` +- The comparison returns the first non-zero result of `f`;or zero if `f` returns zero for all `x` and `y`. +```ocaml + cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; + cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; + cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; +``` +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq xs ys` + +- return false if length is not the same +- otherwise compare items one by one using `f xi yi`;and return true if all results are true;false otherwise +```ocaml + eq [|1; 2; 3|] [|-1; -2; -3|] (fun a b -> abs a = abs b) = true +``` +``` +val truncateToLengthUnsafe : 'a t -> int -> unit +``` +**Unsafe** `truncateToLengthUnsafe xs n` sets length of array `xs` to `n`. + +If `n` is greater than the length of `xs`;the extra elements are set to `Js.Null_undefined.null` + +If `n` is less than zero;raises a `RangeError`. + +```ocaml + let arr = [|"ant";"bee";"cat";"dog";"elk"|];; + let () = truncateToLengthUnsafe arr 3;; + arr = [|"ant";"bee";"cat"|];; +``` +``` +val initU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val init : int -> (int -> 'a) -> 'a t +``` +``` +val push : 'a t -> 'a -> unit +``` +`arr->push(item)` push element \`item\` into the array diff --git a/docs/api/re/melange/Belt-Float.md b/docs/api/re/melange/Belt-Float.md new file mode 100644 index 000000000..a05b382d7 --- /dev/null +++ b/docs/api/re/melange/Belt-Float.md @@ -0,0 +1,29 @@ + +# Module `Belt.Float` + +[`Belt.Float`](#) Utililites for Float + +``` +val toInt : float -> int +``` +``` +val fromInt : int -> float +``` +``` +val fromString : string -> float option +``` +``` +val toString : float -> string +``` +``` +val (+) : float -> float -> float +``` +``` +val (-) : float -> float -> float +``` +``` +val (*) : float -> float -> float +``` +``` +val (/) : float -> float -> float +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashMap-Int.md b/docs/api/re/melange/Belt-HashMap-Int.md new file mode 100644 index 000000000..46c1f54f7 --- /dev/null +++ b/docs/api/re/melange/Belt-HashMap-Int.md @@ -0,0 +1,79 @@ + +# Module `HashMap.Int` + +Specalized when key type is `int`, more efficient than the generic type + +``` +type key = int +``` +``` +type 'b t +``` +``` +val make : hintSize:int -> 'b t +``` +``` +val clear : 'b t -> unit +``` +``` +val isEmpty : _ t -> bool +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` + +``` +val copy : 'a t -> 'a t +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val has : 'b t -> key -> bool +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'b t -> (key -> 'b -> unit) -> unit +``` +``` +val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c +``` +``` +val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c +``` +``` +val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit +``` +``` +val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit +``` +``` +val size : _ t -> int +``` +``` +val toArray : 'a t -> (key * 'a) array +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val mergeMany : 'a t -> (key * 'a) array -> unit +``` +``` +val getBucketHistogram : _ t -> int array +``` +``` +val logStats : _ t -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashMap-String.md b/docs/api/re/melange/Belt-HashMap-String.md new file mode 100644 index 000000000..dc5e0eab3 --- /dev/null +++ b/docs/api/re/melange/Belt-HashMap-String.md @@ -0,0 +1,79 @@ + +# Module `HashMap.String` + +Specalized when key type is `string`, more efficient than the generic type + +``` +type key = string +``` +``` +type 'b t +``` +``` +val make : hintSize:int -> 'b t +``` +``` +val clear : 'b t -> unit +``` +``` +val isEmpty : _ t -> bool +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` + +``` +val copy : 'a t -> 'a t +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val has : 'b t -> key -> bool +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'b t -> (key -> 'b -> unit) -> unit +``` +``` +val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c +``` +``` +val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c +``` +``` +val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit +``` +``` +val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit +``` +``` +val size : _ t -> int +``` +``` +val toArray : 'a t -> (key * 'a) array +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val mergeMany : 'a t -> (key * 'a) array -> unit +``` +``` +val getBucketHistogram : _ t -> int array +``` +``` +val logStats : _ t -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashMap.md b/docs/api/re/melange/Belt-HashMap.md new file mode 100644 index 000000000..0c0c8533e --- /dev/null +++ b/docs/api/re/melange/Belt-HashMap.md @@ -0,0 +1,165 @@ + +# Module `Belt.HashMap` + +[`Belt.HashMap`](#) + +The top level provides generic **mutable** hash map operations. + +It also has two specialized inner modules [`Belt.HashMap.Int`](./Belt-HashMap-Int.md) and [`Belt.HashMap.String`](./Belt-HashMap-String.md) + +A **mutable** Hash map which allows customized hash behavior. + +All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashMaps of ints* initialized with different *hash* functions will have different type. + +For example: + +```ocaml + type t = int + module I0 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s0 : (_, string,_) t = make ~hintSize:40 ~id:(module I0) + module I1 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s1 : (_, string,_) t = make ~hintSize:40 ~id:(module I1) +``` +The invariant must be held: for two elements who are *equal*, their hashed value should be the same + +Here the compiler would infer `s0` and `s1` having different type so that it would not mix. + +```ocaml + val s0 : (int, I0.identity) t + val s1 : (int, I1.identity) t +``` +We can add elements to the collection: + +```ocaml + + let () = + add s1 0 "3"; + add s1 1 "3" +``` +Since this is an mutable data strucure, `s1` will contain two pairs. + +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type + +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type + +``` +type ('key, 'value, 'id) t +``` +The type of hash tables from type `'key` to type `'value`. + +``` +type ('a, 'id) id = + (module Belt__.Belt_Id.Hashable + with type identity = 'id + and type t = 'a) +``` +``` +val make : hintSize:int -> id:('key, 'id) id -> ('key, 'value, 'id) t +``` +``` +val clear : ('key, 'value, 'id) t -> unit +``` +Empty a hash table. + +``` +val isEmpty : (_, _, _) t -> bool +``` +``` +val set : ('key, 'value, 'id) t -> 'key -> 'value -> unit +``` +`set tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` + +``` +val copy : ('key, 'value, 'id) t -> ('key, 'value, 'id) t +``` +``` +val get : ('key, 'value, 'id) t -> 'key -> 'value option +``` +``` +val has : ('key, 'value, 'id) t -> 'key -> bool +``` +`has tbl x` checks if `x` is bound in `tbl`. + +``` +val remove : ('key, 'value, 'id) t -> 'key -> unit +``` +``` +val forEachU : + ('key, 'value, 'id) t -> + ('key -> 'value -> unit) Js.Fn.arity2 -> + unit +``` +``` +val forEach : ('key, 'value, 'id) t -> ('key -> 'value -> unit) -> unit +``` +`forEach tbl f` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. + +``` +val reduceU : + ('key, 'value, 'id) t -> + 'c -> + ('c -> 'key -> 'value -> 'c) Js.Fn.arity3 -> + 'c +``` +``` +val reduce : ('key, 'value, 'id) t -> 'c -> ('c -> 'key -> 'value -> 'c) -> 'c +``` +`reduce tbl init f` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. + +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + +``` +val keepMapInPlaceU : + ('key, 'value, 'id) t -> + ('key -> 'value -> 'value option) Js.Fn.arity2 -> + unit +``` +``` +val keepMapInPlace : + ('key, 'value, 'id) t -> + ('key -> 'value -> 'value option) -> + unit +``` +``` +val size : (_, _, _) t -> int +``` +`size tbl` returns the number of bindings in `tbl`. It takes constant time. + +``` +val toArray : ('key, 'value, 'id) t -> ('key * 'value) array +``` +``` +val keysToArray : ('key, _, _) t -> 'key array +``` +``` +val valuesToArray : (_, 'value, _) t -> 'value array +``` +``` +val fromArray : + ('key * 'value) array -> + id:('key, 'id) id -> + ('key, 'value, 'id) t +``` +``` +val mergeMany : ('key, 'value, 'id) t -> ('key * 'value) array -> unit +``` +``` +val getBucketHistogram : (_, _, _) t -> int array +``` +``` +val logStats : (_, _, _) t -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashSet-Int.md b/docs/api/re/melange/Belt-HashSet-Int.md new file mode 100644 index 000000000..e674b95e9 --- /dev/null +++ b/docs/api/re/melange/Belt-HashSet-Int.md @@ -0,0 +1,68 @@ + +# Module `HashSet.Int` + +Specalized when key type is `int`, more efficient than the generic type + +This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. + +It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + +**See** [`Belt.HashSet`](./Belt-HashSet.md) + +``` +type key = int +``` +``` +type t +``` +``` +val make : hintSize:int -> t +``` +``` +val clear : t -> unit +``` +``` +val isEmpty : t -> bool +``` +``` +val add : t -> key -> unit +``` +``` +val copy : t -> t +``` +``` +val has : t -> key -> bool +``` +``` +val remove : t -> key -> unit +``` +``` +val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (key -> unit) -> unit +``` +``` +val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c +``` +``` +val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c +``` +``` +val size : t -> int +``` +``` +val logStats : t -> unit +``` +``` +val toArray : t -> key array +``` +``` +val fromArray : key array -> t +``` +``` +val mergeMany : t -> key array -> unit +``` +``` +val getBucketHistogram : t -> int array +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashSet-String.md b/docs/api/re/melange/Belt-HashSet-String.md new file mode 100644 index 000000000..299cc480d --- /dev/null +++ b/docs/api/re/melange/Belt-HashSet-String.md @@ -0,0 +1,68 @@ + +# Module `HashSet.String` + +Specalized when key type is `string`, more efficient than the generic type + +This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. + +It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + +**See** [`Belt.HashSet`](./Belt-HashSet.md) + +``` +type key = string +``` +``` +type t +``` +``` +val make : hintSize:int -> t +``` +``` +val clear : t -> unit +``` +``` +val isEmpty : t -> bool +``` +``` +val add : t -> key -> unit +``` +``` +val copy : t -> t +``` +``` +val has : t -> key -> bool +``` +``` +val remove : t -> key -> unit +``` +``` +val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (key -> unit) -> unit +``` +``` +val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c +``` +``` +val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c +``` +``` +val size : t -> int +``` +``` +val logStats : t -> unit +``` +``` +val toArray : t -> key array +``` +``` +val fromArray : key array -> t +``` +``` +val mergeMany : t -> key array -> unit +``` +``` +val getBucketHistogram : t -> int array +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashSet.md b/docs/api/re/melange/Belt-HashSet.md new file mode 100644 index 000000000..1f8647d50 --- /dev/null +++ b/docs/api/re/melange/Belt-HashSet.md @@ -0,0 +1,124 @@ + +# Module `Belt.HashSet` + +[`Belt.HashSet`](#) + +The top level provides generic **mutable** hash set operations. + +It also has two specialized inner modules [`Belt.HashSet.Int`](./Belt-HashSet-Int.md) and [`Belt.HashSet.String`](./Belt-HashSet-String.md) + +A **mutable** Hash set which allows customized hash behavior. + +All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashSets of ints* initialized with different *hash* functions will have different type. + +For example: + +```ocaml + type t = int + module I0 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s0 = make ~id:(module I0) ~hintSize:40 + module I1 = + (val Belt.Id.hashableU + ~hash:(fun[\@u] (a : t) -> a & 0xff) + ~eq:(fun[\@u] a b -> a = b) + ) + let s1 = make ~id:(module I1) ~hintSize:40 +``` +The invariant must be held: for two elements who are *equal*, their hashed value should be the same + +Here the compiler would infer `s0` and `s1` having different type so that it would not mix. + +```ocaml + val s0 : (int, I0.identity) t + val s1 : (int, I1.identity) t +``` +We can add elements to the collection: + +```ocaml + + let () = + add s1 0; + add s1 1 +``` +Since this is an mutable data strucure, `s1` will contain two pairs. + +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type + +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type + +``` +type ('a, 'id) t +``` +The type of hash tables from type `'a` to type `'b`. + +``` +type ('a, 'id) id = + (module Belt__.Belt_Id.Hashable + with type identity = 'id + and type t = 'a) +``` +``` +val make : hintSize:int -> id:('a, 'id) id -> ('a, 'id) t +``` +``` +val clear : ('a, 'id) t -> unit +``` +``` +val isEmpty : (_, _) t -> bool +``` +``` +val add : ('a, 'id) t -> 'a -> unit +``` +``` +val copy : ('a, 'id) t -> ('a, 'id) t +``` +``` +val has : ('a, 'id) t -> 'a -> bool +``` +``` +val remove : ('a, 'id) t -> 'a -> unit +``` +``` +val forEachU : ('a, 'id) t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('a, 'id) t -> ('a -> unit) -> unit +``` +Order unspecified. + +``` +val reduceU : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) Js.Fn.arity2 -> 'c +``` +``` +val reduce : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) -> 'c +``` +Order unspecified. + +``` +val size : ('a, 'id) t -> int +``` +``` +val logStats : (_, _) t -> unit +``` +``` +val toArray : ('a, 'id) t -> 'a array +``` +``` +val fromArray : 'a array -> id:('a, 'id) id -> ('a, 'id) t +``` +``` +val mergeMany : ('a, 'id) t -> 'a array -> unit +``` +``` +val getBucketHistogram : (_, _) t -> int array +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md new file mode 100644 index 000000000..7cdbeba8e --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md @@ -0,0 +1,9 @@ + +# Parameter `MakeComparable.M` + +``` +type t +``` +``` +val cmp : t -> t -> int +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparable.md b/docs/api/re/melange/Belt-Id-MakeComparable.md new file mode 100644 index 000000000..a4e124a8e --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeComparable.md @@ -0,0 +1,21 @@ + +# Module `Id.MakeComparable` + + +## Parameters + +``` +module M : sig ... end +``` + +## Signature + +``` +type identity +``` +``` +type t = M.t +``` +``` +val cmp : (t, identity) cmp +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md new file mode 100644 index 000000000..94b48d88a --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md @@ -0,0 +1,9 @@ + +# Parameter `MakeComparableU.M` + +``` +type t +``` +``` +val cmp : (t -> t -> int) Js.Fn.arity2 +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparableU.md b/docs/api/re/melange/Belt-Id-MakeComparableU.md new file mode 100644 index 000000000..6ade5dd1d --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeComparableU.md @@ -0,0 +1,21 @@ + +# Module `Id.MakeComparableU` + + +## Parameters + +``` +module M : sig ... end +``` + +## Signature + +``` +type identity +``` +``` +type t = M.t +``` +``` +val cmp : (t, identity) cmp +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md new file mode 100644 index 000000000..2ad08437b --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md @@ -0,0 +1,12 @@ + +# Parameter `MakeHashable.M` + +``` +type t +``` +``` +val hash : t -> int +``` +``` +val eq : t -> t -> bool +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashable.md b/docs/api/re/melange/Belt-Id-MakeHashable.md new file mode 100644 index 000000000..15f31e6d6 --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeHashable.md @@ -0,0 +1,24 @@ + +# Module `Id.MakeHashable` + + +## Parameters + +``` +module M : sig ... end +``` + +## Signature + +``` +type identity +``` +``` +type t = M.t +``` +``` +val hash : (t, identity) hash +``` +``` +val eq : (t, identity) eq +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md new file mode 100644 index 000000000..eb5a430a2 --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md @@ -0,0 +1,12 @@ + +# Parameter `MakeHashableU.M` + +``` +type t +``` +``` +val hash : (t -> int) Js.Fn.arity1 +``` +``` +val eq : (t -> t -> bool) Js.Fn.arity2 +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashableU.md b/docs/api/re/melange/Belt-Id-MakeHashableU.md new file mode 100644 index 000000000..a8834245f --- /dev/null +++ b/docs/api/re/melange/Belt-Id-MakeHashableU.md @@ -0,0 +1,24 @@ + +# Module `Id.MakeHashableU` + + +## Parameters + +``` +module M : sig ... end +``` + +## Signature + +``` +type identity +``` +``` +type t = M.t +``` +``` +val hash : (t, identity) hash +``` +``` +val eq : (t, identity) eq +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-module-type-Comparable.md b/docs/api/re/melange/Belt-Id-module-type-Comparable.md new file mode 100644 index 000000000..8f8f4244d --- /dev/null +++ b/docs/api/re/melange/Belt-Id-module-type-Comparable.md @@ -0,0 +1,12 @@ + +# Module type `Id.Comparable` + +``` +type identity +``` +``` +type t +``` +``` +val cmp : (t, identity) cmp +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-module-type-Hashable.md b/docs/api/re/melange/Belt-Id-module-type-Hashable.md new file mode 100644 index 000000000..9758efeeb --- /dev/null +++ b/docs/api/re/melange/Belt-Id-module-type-Hashable.md @@ -0,0 +1,15 @@ + +# Module type `Id.Hashable` + +``` +type identity +``` +``` +type t +``` +``` +val hash : (t, identity) hash +``` +``` +val eq : (t, identity) eq +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id.md b/docs/api/re/melange/Belt-Id.md new file mode 100644 index 000000000..d9072b719 --- /dev/null +++ b/docs/api/re/melange/Belt-Id.md @@ -0,0 +1,113 @@ + +# Module `Belt.Id` + +[`Belt.Id`](#) + +Provide utilities to create identified comparators or hashes for data structures used below. + +It create a unique identifier per module of functions so that different data structures with slightly different comparison functions won't mix + +[`Belt.Id`](#) + +Provide utiliites to create identified comparators or hashes for data structures used below. + +It create a unique identifer per module of functions so that different data structures with slightly different comparison functions won't mix. + +``` +type ('a, 'id) hash +``` +`('a, 'id) hash` + +Its runtime represenation is a `hash` function, but signed with a type parameter, so that different hash functions type mismatch + +``` +type ('a, 'id) eq +``` +`('a, 'id) eq` + +Its runtime represenation is an `eq` function, but signed with a type parameter, so that different hash functions type mismatch + +``` +type ('a, 'id) cmp +``` +`('a,'id) cmp` + +Its runtime representation is a `cmp` function, but signed with a type parameter, so that different hash functions type mismatch + +``` +module type Comparable = sig ... end +``` +``` +type ('key, 'id) comparable = + (module Comparable + with type identity = 'id + and type t = 'key) +``` +`('key, 'id) cmparable` is a module of functions, here it only includes `cmp`. + +Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). + +It can be created using function [`comparableU`](./#val-comparableU) or [`comparable`](./#val-comparable). + +The idea of a unique identity when created is that it makes sure two sets would type mismatch if they use different comparison function + +``` +module MakeComparableU (M : sig ... end) : Comparable with type t = M.t +``` +``` +module MakeComparable (M : sig ... end) : Comparable with type t = M.t +``` +``` +val comparableU : + cmp:('a -> 'a -> int) Js.Fn.arity2 -> + (module Comparable + with type t = 'a) +``` +``` +val comparable : cmp:('a -> 'a -> int) -> (module Comparable with type t = 'a) +``` +```ocaml + module C = ( + val Belt.Id.comparable ~cmp:(compare : int -> int -> int) + ) + let m = Belt.Set.make(module C) +``` +Note that the name of C can not be ignored + +``` +module type Hashable = sig ... end +``` +``` +type ('key, 'id) hashable = + (module Hashable + with type identity = 'id + and type t = 'key) +``` +`('key, 'id) hashable` is a module of functions, here it only includes `hash`, `eq`. + +Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). + +It can be created using function [`hashableU`](./#val-hashableU) or [`hashable`](./#val-hashable). + +The idea of a unique identity when created is that it makes sure two hash sets would type mismatch if they use different comparison function + +``` +module MakeHashableU (M : sig ... end) : Hashable with type t = M.t +``` +``` +module MakeHashable (M : sig ... end) : Hashable with type t = M.t +``` +``` +val hashableU : + hash:('a -> int) Js.Fn.arity1 -> + eq:('a -> 'a -> bool) Js.Fn.arity2 -> + (module Hashable + with type t = 'a) +``` +``` +val hashable : + hash:('a -> int) -> + eq:('a -> 'a -> bool) -> + (module Hashable + with type t = 'a) +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Int.md b/docs/api/re/melange/Belt-Int.md new file mode 100644 index 000000000..e16080186 --- /dev/null +++ b/docs/api/re/melange/Belt-Int.md @@ -0,0 +1,29 @@ + +# Module `Belt.Int` + +[`Belt.Int`](#) Utililites for Int + +``` +val toFloat : int -> float +``` +``` +val fromFloat : float -> int +``` +``` +val fromString : string -> int option +``` +``` +val toString : int -> string +``` +``` +val (+) : int -> int -> int +``` +``` +val (-) : int -> int -> int +``` +``` +val (*) : int -> int -> int +``` +``` +val (/) : int -> int -> int +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-List.md b/docs/api/re/melange/Belt-List.md new file mode 100644 index 000000000..eb9dee2fd --- /dev/null +++ b/docs/api/re/melange/Belt-List.md @@ -0,0 +1,680 @@ + +# Module `Belt.List` + +[`Belt.List`](#) + +Utilities for List data type + +[`Belt.List`](#) + +Utilities for List data type. + +This module is compatible with original ocaml stdlib. In general, all functions comes with the original stdlib also applies to this collection, however, this module provides faster and stack safer utilities + +``` +type 'a t = 'a list +``` +`'a t` is compatible with built-in `list` type + +``` +val length : 'a t -> int +``` +`length xs` + +returns the length of the list xs +``` +val size : 'a t -> int +``` +**See** [`length`](./#val-length) + +``` +val head : 'a t -> 'a option +``` +`head xs` returns `None` if `xs` is the empty list, otherwise it returns `Some value` where `value` is the first element in the list. + +```ocaml + head [] = None ;; + head [1;2;3] = Some 1 ;; +``` +``` +val headExn : 'a t -> 'a +``` +`headExn xs` + +**See** [`head`](./#val-head) + +**raise** an exception if `xs` is empty + +``` +val tail : 'a t -> 'a t option +``` +`tail xs` returns `None` if `xs` is empty; otherwise it returns `Some xs2` where `xs2` is everything except the first element of `xs`; + +```ocaml + tail [] = None;; + tail [1;2;3;4] = Some [2;3;4];; +``` +``` +val tailExn : 'a t -> 'a t +``` +`tailExn xs` + +**See** [`tail`](./#val-tail) + +**raise** an exception if `xs` is empty + +``` +val add : 'a t -> 'a -> 'a t +``` +`add xs y` adds `y` to the beginning of list `xs` + +```ocaml + add [1] 3 = [3;1];; +``` +``` +val get : 'a t -> int -> 'a option +``` +`get xs n` + +return the nth element in `xs`, or `None` if `n` is larger than the length + +```ocaml + get [0;3;32] 2 = Some 32 ;; + get [0;3;32] 3 = None;; +``` +``` +val getExn : 'a t -> int -> 'a +``` +`getExn xs n` + +**See** [`get`](./#val-get) + +**raise** an exception if `n` is larger than the length + +``` +val make : int -> 'a -> 'a t +``` +`make n v` + +- return a list of length `n` with each element filled with value `v` +- return the empty list if `n` is negative +```ocaml + make 3 1 = [1;1;1] +``` +``` +val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t +``` +``` +val makeBy : int -> (int -> 'a) -> 'a t +``` +`makeBy n f` + +- return a list of length `n` with element `i` initialized with `f i` +- return the empty list if `n` is negative +```ocaml + makeBy 5 (fun i -> i) = [0;1;2;3;4];; + makeBy 5 (fun i -> i * i) = [0;1;4;9;16];; +``` +``` +val shuffle : 'a t -> 'a t +``` +`shuffle xs` + +returns a new list in random order +``` +val drop : 'a t -> int -> 'a t option +``` +`drop xs n` + +return the list obtained by dropping the first `n` elements, or `None` if `xs` has fewer than `n` elements + +```ocaml + drop [1;2;3] 2 = Some [3];; + drop [1;2;3] 3 = Some [];; + drop [1;2;3] 4 = None;; +``` +``` +val take : 'a t -> int -> 'a t option +``` +`take xs n` + +return a list with the first `n` elements from `xs`, or `None` if `xs` has fewer than `n` elements + +```ocaml + take [1;2;3] 1 = Some [1];; + take [1;2;3] 2 = Some [1;2];; + take [1;2;3] 4 = None;; +``` +``` +val splitAt : 'a t -> int -> ('a list * 'a list) option +``` +`splitAt xs n` split the list `xs` at position `n` return None when the length of `xs` is less than `n` + +```ocaml + splitAt [0;1;2;3;4] 2 = Some ([0;1], [2;3;4]) +``` +``` +val concat : 'a t -> 'a t -> 'a t +``` +`concat xs ys` + +returns the list obtained by adding ys after xs +```ocaml + concat [1;2;3] [4;5] = [1;2;3;4;5] +``` +``` +val concatMany : 'a t array -> 'a t +``` +`concatMany a` return the list obtained by concatenating in order all the lists in array `a` + +```ocaml + concatMany [| [1;2;3] ; []; [3]; [4] |] = [1;2;3;3;4] +``` +``` +val reverseConcat : 'a t -> 'a t -> 'a t +``` +`reverseConcat xs ys` is equivalent to `concat (reverse xs) ys` + +```ocaml + reverseConcat [1;2] [3;4] = [2;1;3;4] +``` +``` +val flatten : 'a t t -> 'a t +``` +`flatten ls` return the list obtained by concatenating in order all the lists in list `ls` + +```ocaml + flatten [ [1;2;3] ; []; [3]; [4] ] = [1;2;3;3;4] +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +`map xs f` + +return the list obtained by applying `f` to each element of `xs` + +```ocaml + map [1;2] (fun x-> x + 1) = [3;4] +``` +``` +val zip : 'a t -> 'b t -> ('a * 'b) t +``` +`zip xs ys` + +returns a list of pairs from the two lists with the length of the shorter list +```ocaml + zip [1;2] [3;4;5] = [(1,3); (2,4)] +``` +``` +val zipByU : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t +``` +``` +val zipBy : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t +``` +`zipBy xs ys f` + +**See** [`zip`](./#val-zip) + +Equivalent to `zip xs ys |> List.map (fun (x,y) -> f x y)` + +```ocaml + zipBy [1;2;3] [4;5] (fun a b -> 2 * a + b) = [6;9];; +``` +``` +val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t +``` +`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. + +```ocaml + mapWithIndex [1;2;3] (fun i x -> i + x) = + [0 + 1; 1 + 2; 2 + 3 ] +``` +``` +val fromArray : 'a array -> 'a t +``` +`fromArray arr` converts the given array to a list + +```ocaml + fromArray [|1;2;3|] = [1;2;3] +``` +``` +val toArray : 'a t -> 'a array +``` +`toArray xs` converts the given list to an array + +```ocaml + toArray [1;2;3] = [|1;2;3|] +``` +``` +val reverse : 'a t -> 'a t +``` +`reverse xs` returns a new list whose elements are those of `xs` in reverse order. + +```ocaml + reverse [1;2;3] = [3;2;1] +``` +``` +val mapReverseU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val mapReverse : 'a t -> ('a -> 'b) -> 'b t +``` +`mapReverse xs f` + +Equivalent to `reverse (map xs f)` + +```ocaml + mapReverse [3;4;5] (fun x -> x * x) = [25;16;9];; +``` +``` +val forEachU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> 'b) -> unit +``` +`forEach xs f ` Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`, so no new array is created. Use `foreach` when you are primarily concerned with repetitively creating side effects. + +```ocaml + forEach ["a";"b";"c"] (fun x -> Js.log("Item: " ^ x));; + (* prints: + Item: a + Item: b + Item: c + *) + + let us = ref 0;; + forEach [1;2;3;4] (fun x -> us := !us + x);; + !us = 1 + 2 + 3 + 4;; +``` +``` +val forEachWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> unit +``` +``` +val forEachWithIndex : 'a t -> (int -> 'a -> 'b) -> unit +``` +`forEachWithIndex xs f` + +```ocaml + + forEach ["a";"b";"c"] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; + (* prints: + Item 0 is a + Item 1 is b + Item 2 is cc + *) + + let total = ref 0 ;; + forEachWithIndex [10;11;12;13] (fun i x -> total := !total + x + i);; + !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; +``` +``` +val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b +``` +`reduce xs f` + +Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”, which starts with a value of `init`. `reduce` returns the final value of the accumulator. + +```ocaml + reduce [1;2;3;4] 0 (+) = 10;; + reduce [1;2;3;4] 10 (-) = 0;; + reduce [1;2;3;4] [] add = [4;3;2;1]; +``` +``` +val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b +``` +`reduceWithIndex xs f` + +Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the list and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. + +```ocaml + reduceWithIndex [1;2;3;4] 0 (fun acc x i -> acc + x + i) = 16;; +``` +``` +val reduceReverseU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b +``` +``` +val reduceReverse : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b +``` +`reduceReverse xs f` + +Works like [`reduce`](./#val-reduce), except that function `f` is applied to each item of `xs` from the last back to the first. + +```ocaml + reduceReverse [1;2;3;4] 0 (+) = 10;; + reduceReverse [1;2;3;4] 10 (-) = 0;; + reduceReverse [1;2;3;4] [] add = [1;2;3;4];; +``` +``` +val mapReverse2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t +``` +``` +val mapReverse2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t +``` +`mapReverse2 xs ys f` + +equivalent to `reverse (zipBy xs ys f)` + +```ocaml + mapReverse2 [1;2;3] [1;2] (+) = [4;2] +``` +``` +val forEach2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> unit +``` +``` +val forEach2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> unit +``` +`forEach2 xs ys f` stop with the shorter list + +``` +val reduce2U : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) Js.Fn.arity3 -> 'a +``` +``` +val reduce2 : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) -> 'a +``` +`reduce2 xs ys init f ` + +Applies `f` to each element of `xs` and `ys` from beginning to end. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. + +```ocaml + reduce2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; + reduce2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [2 +5;1 + 4 ];; (*add appends at end *) +``` +``` +val reduceReverse2U : + 'a t -> + 'b t -> + 'c -> + ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> + 'c +``` +``` +val reduceReverse2 : 'a t -> 'b t -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c +``` +`reduceReverse2 xs ys init f ` + +Applies `f` to each element of `xs` and `ys` from end to beginning. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. + +```ocaml + reduceReverse2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; + reduceReverse2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [1 + 4;2 + 5];; (*add appends at end *) +``` +``` +val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : 'a t -> ('a -> bool) -> bool +``` +`every xs p` + +returns true if all elements satisfy p, where p is a predicate: a function taking an element and returning a bool. +```ocaml + every [] (fun x -> x mod 2 = 0) = true;; + every [2;4;6] (fun x -> x mod 2 = 0 ) = true;; + every [1;-3;5] (fun x -> x > 0) = false;; +``` +``` +val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : 'a t -> ('a -> bool) -> bool +``` +`some xs p` + +returns true if at least one of the elements in xs satifies p, where p is a predicate: a function taking an element and returning a bool. +```ocaml + some [] (fun x -> x mod 2 = 0) = false ;; + some [1;2;4] (fun x -> x mod 2 = 0) = true;; + some [-1;-3;-5] (fun x -> x > 0) = false;; +``` +``` +val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`every2 xs ys p` returns true if predicate `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + +```ocaml + every2 [1;2;3] [0;1] (>) = true;; + every2 [] [1] (fun x y -> x > y) = true;; + every2 [2;3] [1] (fun x y -> x > y) = true;; + every2 [0;1] [5;0] (fun x y -> x > y) = false; +``` +``` +val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool +``` +`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) + +```ocaml + some2 [0;2] [1;0;3] (>) = true ;; + some2 [] [1] (fun x y -> x > y) = false;; + some2 [2;3] [1;4] (fun x y -> x > y) = true;; +``` +``` +val cmpByLength : 'a t -> 'a t -> int +``` +`cmpByLength l1 l2` + +Compare two lists solely by length. Returns \-1 if `length l1` is less than `length l2`, 0 if `length l1` equals `length l2`, and 1 if `length l1` is greater than `length l2`. + +```ocaml +cmpByLength [1;2] [3;4;5;6] = -1;; +cmpByLength [1;2;3] [4;5;6] = 0;; +cmpByLength [1;2;3;4] [5;6] = 1;; +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +Compare elements one by one `f x y`. `f` returns + +- a negative number if `x` is “less than” `y` +- zero if `x` is “equal to” `y` +- a positive number if `x` is “greater than” `y` The comparison returns the first non-zero result of `f`, or zero if `f` returns zero for all `x` and `y`. If all items have compared equal, but `xs` is exhausted first, return \-1. (`xs` is shorter) If all items have compared equal, but `ys` is exhausted first, return 1 (`xs` is longer) +```ocaml + cmp [3] [3;7] (fun a b -> compare a b) = -1 + cmp [5;3] [5] (fun a b -> compare a b) = 1 + cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; + cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; + cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; +``` +**Attention**: The total ordering of List is different from Array, for Array, we compare the length first and, only if the lengths are equal, elements one by one. For lists, we just compare elements one by one + +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq xs ys eqElem` check equality of `xs` and `ys` using `eqElem` for equality on elements, where `eqElem` is a function that returns true if items `x` and `y` meet some criterion for equality, false otherwise. `eq` false if length of `xs` and `ys` are not the same. + +```ocaml + eq [1;2;3] [1;2] (=) = false ;; + eq [1;2] [1;2] (=) = true;; + eq [1; 2; 3] [-1; -2; -3] (fun a b -> abs a = abs b) = true;; +``` +``` +val hasU : 'a t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val has : 'a t -> 'b -> ('a -> 'b -> bool) -> bool +``` +`has xs eqFcn` returns true if the list contains at least one element for which `eqFcn x` returns true + +```ocaml + has [1;2;3] 2 (=) = true;; + has [1;2;3] 4 (=) = false;; + has [-1;-2;-3] 2 (fun a b -> abs a = abs b) = true;; +``` +``` +val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option +``` +``` +val getBy : 'a t -> ('a -> bool) -> 'a option +``` +`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. + +```ocaml + getBy [1;4;3;2] (fun x -> x mod 2 = 0) = Some 4 + getBy [15;13;11] (fun x -> x mod 2 = 0) = None +``` +``` +val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t +``` +``` +val keep : 'a t -> ('a -> bool) -> 'a t +``` +`keep xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` + +```ocaml + keep [1;2;3;4] (fun x -> x mod 2 = 0) = + [2;4] +``` +``` +val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t +``` +``` +val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t +``` +`keepWithIndex xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` + +```ocaml + keepWithIndex [1;2;3;4] (fun _x i -> i mod 2 = 0) + = + [1;3] +``` +``` +val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b t +``` +``` +val keepMap : 'a t -> ('a -> 'b option) -> 'b t +``` +`keepMap xs f` applies `f` to each element of `xs`. If `f xi` returns `Some value`, then `value` is kept in the resulting list; if `f xi` returns `None`, the element is not retained in the result. + +```ocaml + keepMap [1;2;3;4] (fun x -> if x mod 2 = 0 then Some (-x ) else None) + = + [-2;-4] +``` +``` +val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t +``` +``` +val partition : 'a t -> ('a -> bool) -> 'a t * 'a t +``` +`partition xs p` creates a pair of lists; the first list consists of all elements of `xs` that satisfy the predicate function `p`; the second list consists of all elements of `xs` that do not satisfy `p` + +```ocaml + partition [1;2;3;4] (fun x -> x mod 2 = 0) = + ([2;4], [1;3]) +``` +``` +val unzip : ('a * 'b) t -> 'a t * 'b t +``` +`unzip xs` takes a list of pairs and creates a pair of lists. The first list contains all the first items of the pairs; the second list contains all the second items. + +```ocaml + unzip [(1,2) ; (3,4)] = ([1;3], [2;4]);; + unzip [(1,2) ; (3,4) ; (5,6) ; (7,8)] = ([1;3;5;7], [2;4;6;8]);; +``` +``` +val getAssocU : + ('a * 'c) t -> + 'b -> + ('a -> 'b -> bool) Js.Fn.arity2 -> + 'c option +``` +``` +val getAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> 'c option +``` +`getAssoc xs k eq` + +return the second element of a pair in `xs` where the first element equals `x` as per the predicate function `eq`, or `None` if not found + +```ocaml + getAssoc [ 1, "a"; 2, "b"; 3, "c"] 2 (=) = Some "b" + getAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = Some "afternoon" +``` +``` +val hasAssocU : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val hasAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> bool +``` +`hasAssoc xs k eq` return true if there is a pair in `xs` where the first element equals `k` as per the predicate funtion `eq` + +```ocaml + hasAssoc [1, "a"; 2, "b"; 3,"c"] 1 (=) = true;; + hasAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = true;; +``` +``` +val removeAssocU : + ('a * 'c) t -> + 'b -> + ('a -> 'b -> bool) Js.Fn.arity2 -> + ('a * 'c) t +``` +``` +val removeAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> ('a * 'c) t +``` +`removeAssoc xs k eq` Return a list after removing the first pair whose first value is `k` per the equality predicate `eq`; if not found, return a new list identical to `xs`. + +```ocaml + removeAssoc [1,"a"; 2, "b"; 3, "c" ] 1 (=) = + [2, "b"; 3, "c"] + removeAssoc [1,"a"; 2, "b"; 3, "c" ] 99 (=) = + [1, "a"; 2, "b"; 3, "c"] +``` +``` +val setAssocU : + ('a * 'c) t -> + 'a -> + 'c -> + ('a -> 'a -> bool) Js.Fn.arity2 -> + ('a * 'c) t +``` +``` +val setAssoc : ('a * 'c) t -> 'a -> 'c -> ('a -> 'a -> bool) -> ('a * 'c) t +``` +`setAssoc xs k v eq` if `k` exists in `xs` by satisfying the `eq` predicate, return a new list with the key and value replaced by the new `k` and `v`; otherwise, return a new list with the pair `k, v` added to the head of `xs`. + +```ocaml + setAssoc [1,"a"; 2, "b"; 3, "c"] 2 "x" (=) = + [1,"a"; 2, "x"; 3,"c"] ;; + + setAssoc [1,"a"; 3, "c"] 2 "b" (=) = + [2,"b"; 1,"a"; 3, "c"] + + setAssoc [9, "morning"; 3, "morning?!"; 22, "night"] 15 "afternoon" + (fun a b -> a mod 12 = b mod 12) = [9, "morning"; 15, "afternoon"; 22, "night"] +``` +Note carefully the last example\! Since `15 mod 12` equals `3 mod 12`, *both* the key and value are replaced in the list. + +``` +val sortU : 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a t +``` +``` +val sort : 'a t -> ('a -> 'a -> int) -> 'a t +``` +`sort xs` Returns a sorted list. + +```ocaml + sort [5; 4; 9; 3; 7] (fun a b -> a - b) = [3; 4; 5; 7; 9] +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map-Dict.md b/docs/api/re/melange/Belt-Map-Dict.md new file mode 100644 index 000000000..61b1e8167 --- /dev/null +++ b/docs/api/re/melange/Belt-Map-Dict.md @@ -0,0 +1,281 @@ + +# Module `Map.Dict` + +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + +**Advanced usage only** + +``` +type ('key, 'value, 'id) t +``` +``` +type ('key, 'id) cmp +``` +``` +val empty : ('k, 'v, 'id) t +``` +``` +val isEmpty : ('k, 'v, 'id) t -> bool +``` +``` +val has : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> bool +``` +``` +val cmpU : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + kcmp:('k, 'id) cmp -> + vcmp:('v -> 'v -> int) Js.Fn.arity2 -> + int +``` +``` +val cmp : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + kcmp:('k, 'id) cmp -> + vcmp:('v -> 'v -> int) -> + int +``` +``` +val eqU : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + kcmp:('k, 'id) cmp -> + veq:('a -> 'a -> bool) Js.Fn.arity2 -> + bool +``` +``` +val eq : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + kcmp:('k, 'id) cmp -> + veq:('a -> 'a -> bool) -> + bool +``` +`eq m1 m2 cmp` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + +``` +val findFirstByU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k * 'v) option +``` +``` +val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val reduceU : + ('k, 'a, 'id) t -> + 'b -> + ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> + 'b +``` +``` +val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + +``` +val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + +``` +val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + +``` +val size : ('k, 'a, 'id) t -> int +``` +``` +val toList : ('k, 'a, 'id) t -> ('k * 'a) list +``` +In increasing order. + +``` +val toArray : ('k, 'a, 'id) t -> ('k * 'a) array +``` +``` +val fromArray : ('k * 'a) array -> cmp:('k, 'id) cmp -> ('k, 'a, 'id) t +``` +``` +val keysToArray : ('k, 'a, 'id) t -> 'k array +``` +``` +val valuesToArray : ('k, 'a, 'id) t -> 'a array +``` +``` +val minKey : ('k, _, _) t -> 'k option +``` +``` +val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val maxKey : ('k, _, _) t -> 'k option +``` +``` +val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val minimum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val maximum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val get : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a option +``` +``` +val getUndefined : + ('k, 'a, 'id) t -> + 'k -> + cmp:('k, 'id) cmp -> + 'a Js.undefined +``` +``` +val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> cmp:('k, 'id) cmp -> 'a +``` +``` +val getExn : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a +``` +``` +val checkInvariantInternal : (_, _, _) t -> unit +``` +**raise** when invariant is not held + +``` +val remove : ('a, 'b, 'id) t -> 'a -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t +``` +`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. + +``` +val removeMany : + ('a, 'b, 'id) t -> + 'a array -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val set : ('a, 'b, 'id) t -> 'a -> 'b -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t +``` +`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + +``` +val updateU : + ('a, 'b, 'id) t -> + 'a -> + ('b option -> 'b option) Js.Fn.arity1 -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val update : + ('a, 'b, 'id) t -> + 'a -> + ('b option -> 'b option) -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val mergeU : + ('a, 'b, 'id) t -> + ('a, 'c, 'id) t -> + ('a -> 'b option -> 'c option -> 'd option) Js.Fn.arity3 -> + cmp:('a, 'id) cmp -> + ('a, 'd, 'id) t +``` +``` +val merge : + ('a, 'b, 'id) t -> + ('a, 'c, 'id) t -> + ('a -> 'b option -> 'c option -> 'd option) -> + cmp:('a, 'id) cmp -> + ('a, 'd, 'id) t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + +``` +val mergeMany : + ('a, 'b, 'id) t -> + ('a * 'b) array -> + cmp:('a, 'id) cmp -> + ('a, 'b, 'id) t +``` +``` +val keepU : + ('k, 'a, 'id) t -> + ('k -> 'a -> bool) Js.Fn.arity2 -> + ('k, 'a, 'id) t +``` +``` +val keep : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> ('k, 'a, 'id) t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + +``` +val partitionU : + ('k, 'a, 'id) t -> + ('k -> 'a -> bool) Js.Fn.arity2 -> + ('k, 'a, 'id) t * ('k, 'a, 'id) t +``` +``` +val partition : + ('k, 'a, 'id) t -> + ('k -> 'a -> bool) -> + ('k, 'a, 'id) t * ('k, 'a, 'id) t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + +``` +val split : + ('a, 'b, 'id) t -> + 'a -> + cmp:('a, 'id) cmp -> + (('a, 'b, 'id) t * ('a, 'b, 'id) t) * 'b option +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +``` +val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t +``` +``` +val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapWithKeyU : + ('k, 'a, 'id) t -> + ('k -> 'a -> 'b) Js.Fn.arity2 -> + ('k, 'b, 'id) t +``` +``` +val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map-Int.md b/docs/api/re/melange/Belt-Map-Int.md new file mode 100644 index 000000000..fe3ddaa90 --- /dev/null +++ b/docs/api/re/melange/Belt-Map-Int.md @@ -0,0 +1,217 @@ + +# Module `Map.Int` + +Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +``` +type key = int +``` +``` +type 'value t +``` +The type of maps from type `key` to type `'value`. + +``` +val empty : 'v t +``` +``` +val isEmpty : 'v t -> bool +``` +``` +val has : 'v t -> key -> bool +``` +``` +val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int +``` +``` +val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool +``` +`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. + +``` +val findFirstByU : + 'v t -> + (key -> 'v -> bool) Js.Fn.arity2 -> + (key * 'v) option +``` +``` +val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'v t -> (key -> 'v -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 +``` +``` +val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + +``` +val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'v t -> (key -> 'v -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + +``` +val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'v t -> (key -> 'v -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + +``` +val size : 'v t -> int +``` +``` +val toList : 'v t -> (key * 'v) list +``` +In increasing order. + +``` +val toArray : 'v t -> (key * 'v) array +``` +``` +val fromArray : (key * 'v) array -> 'v t +``` +``` +val keysToArray : 'v t -> key array +``` +``` +val valuesToArray : 'v t -> 'v array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'v t -> (key * 'v) option +``` +``` +val minUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val maximum : 'v t -> (key * 'v) option +``` +``` +val maxUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val get : 'v t -> key -> 'v option +``` +``` +val getUndefined : 'v t -> key -> 'v Js.undefined +``` +``` +val getWithDefault : 'v t -> key -> 'v -> 'v +``` +``` +val getExn : 'v t -> key -> 'v +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held + +``` +val remove : 'v t -> key -> 'v t +``` +`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. + +``` +val removeMany : 'v t -> key array -> 'v t +``` +``` +val set : 'v t -> key -> 'v -> 'v t +``` +`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + +``` +val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t +``` +``` +val update : 'v t -> key -> ('v option -> 'v option) -> 'v t +``` +``` +val mergeU : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> + 'c t +``` +``` +val merge : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) -> + 'c t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + +``` +val mergeMany : 'v t -> (key * 'v) array -> 'v t +``` +``` +val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t +``` +``` +val keep : 'v t -> (key -> 'v -> bool) -> 'v t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + +``` +val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t +``` +``` +val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + +``` +val split : key -> 'v t -> 'v t * 'v option * 'v t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +``` +val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t +``` +``` +val map : 'v t -> ('v -> 'v2) -> 'v2 t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t +``` +``` +val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map-String.md b/docs/api/re/melange/Belt-Map-String.md new file mode 100644 index 000000000..1fa79b3e6 --- /dev/null +++ b/docs/api/re/melange/Belt-Map-String.md @@ -0,0 +1,217 @@ + +# Module `Map.String` + +specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +``` +type key = string +``` +``` +type 'value t +``` +The type of maps from type `key` to type `'value`. + +``` +val empty : 'v t +``` +``` +val isEmpty : 'v t -> bool +``` +``` +val has : 'v t -> key -> bool +``` +``` +val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int +``` +``` +val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool +``` +`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. + +``` +val findFirstByU : + 'v t -> + (key -> 'v -> bool) Js.Fn.arity2 -> + (key * 'v) option +``` +``` +val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'v t -> (key -> 'v -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 +``` +``` +val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + +``` +val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'v t -> (key -> 'v -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + +``` +val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'v t -> (key -> 'v -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + +``` +val size : 'v t -> int +``` +``` +val toList : 'v t -> (key * 'v) list +``` +In increasing order. + +``` +val toArray : 'v t -> (key * 'v) array +``` +``` +val fromArray : (key * 'v) array -> 'v t +``` +``` +val keysToArray : 'v t -> key array +``` +``` +val valuesToArray : 'v t -> 'v array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'v t -> (key * 'v) option +``` +``` +val minUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val maximum : 'v t -> (key * 'v) option +``` +``` +val maxUndefined : 'v t -> (key * 'v) Js.undefined +``` +``` +val get : 'v t -> key -> 'v option +``` +``` +val getUndefined : 'v t -> key -> 'v Js.undefined +``` +``` +val getWithDefault : 'v t -> key -> 'v -> 'v +``` +``` +val getExn : 'v t -> key -> 'v +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held + +``` +val remove : 'v t -> key -> 'v t +``` +`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. + +``` +val removeMany : 'v t -> key array -> 'v t +``` +``` +val set : 'v t -> key -> 'v -> 'v t +``` +`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + +``` +val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t +``` +``` +val update : 'v t -> key -> ('v option -> 'v option) -> 'v t +``` +``` +val mergeU : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> + 'c t +``` +``` +val merge : + 'v t -> + 'v2 t -> + (key -> 'v option -> 'v2 option -> 'c option) -> + 'c t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + +``` +val mergeMany : 'v t -> (key * 'v) array -> 'v t +``` +``` +val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t +``` +``` +val keep : 'v t -> (key -> 'v -> bool) -> 'v t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + +``` +val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t +``` +``` +val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + +``` +val split : key -> 'v t -> 'v t * 'v option * 'v t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +``` +val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t +``` +``` +val map : 'v t -> ('v -> 'v2) -> 'v2 t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t +``` +``` +val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map.md b/docs/api/re/melange/Belt-Map.md new file mode 100644 index 000000000..23dfe9607 --- /dev/null +++ b/docs/api/re/melange/Belt-Map.md @@ -0,0 +1,460 @@ + +# Module `Belt.Map` + +[`Belt.Map`](#), + +The top level provides generic **immutable** map operations. + +It also has three specialized inner modules [`Belt.Map.Int`](./Belt-Map-Int.md), [`Belt.Map.String`](./Belt-Map-String.md) and + +[`Belt.Map.Dict`](./Belt-Map-Dict.md): This module separates data from function which is more verbose but slightly more efficient + +A *immutable* sorted map module which allows customize *compare* behavior. + +The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + +For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. + +Example usage: + +```ocaml + module PairComparator = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c + end) + + let myMap = Belt.Map.make ~id:(module PairComparator) + let myMap2 = Belt.Map.set myMap (1, 2) "myValue" +``` +The API documentation below will assume a predeclared comparator module for integers, IntCmp + +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +``` +module String : sig ... end +``` +specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +``` +module Dict : sig ... end +``` +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + +``` +type ('key, 'value, 'identity) t +``` +`('key, 'identity) t` + +`'key` is the field type + +`'value` is the element type + +`'identity` the identity of the collection + +``` +type ('key, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'key) +``` +The identity needed for making an empty map + +``` +val make : id:('k, 'id) id -> ('k, 'v, 'id) t +``` +`make ~id` creates a new map by taking in the comparator + +```ocaml + let m = Belt.Map.make ~id:(module IntCmp) +``` +``` +val isEmpty : (_, _, _) t -> bool +``` +`isEmpty m` checks whether a map m is empty + +```ocaml + isEmpty (fromArray [|1,"1"|] ~id:(module IntCmp)) = false +``` +``` +val has : ('k, 'v, 'id) t -> 'k -> bool +``` +`has m k` checks whether m has the key k + +```ocaml + has (fromArray [|1,"1"|] ~id:(module IntCmp)) 1 = true +``` +``` +val cmpU : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + ('v -> 'v -> int) Js.Fn.arity2 -> + int +``` +``` +val cmp : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> int) -> int +``` +`cmp m0 m1 vcmp` + +Total ordering of map given total ordering of value function. + +It will compare size first and each element following the order one by one. + +``` +val eqU : + ('k, 'v, 'id) t -> + ('k, 'v, 'id) t -> + ('v -> 'v -> bool) Js.Fn.arity2 -> + bool +``` +``` +val eq : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> bool) -> bool +``` +`eq m1 m2 veq` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `veq` is the equality predicate used to compare the data associated with the keys. + +``` +val findFirstByU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k * 'v) option +``` +``` +val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option +``` +`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; +``` +``` +val forEachU : ('k, 'v, 'id) t -> ('k -> 'v -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : ('k, 'v, 'id) t -> ('k -> 'v -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + let acc = ref [] ;; + forEach s0 (fun k v -> acc := (k,v) :: !acc);; + + !acc = [4,"4"; 3,"3"; 2,"2"; 1,"1"] +``` +``` +val reduceU : + ('k, 'v, 'id) t -> + 'acc -> + ('acc -> 'k -> 'v -> 'acc) Js.Fn.arity3 -> + 'acc +``` +``` +val reduce : ('k, 'v, 'id) t -> 'acc -> ('acc -> 'k -> 'v -> 'acc) -> 'acc +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; + reduce s0 [] (fun acc k v -> (k,v) acc ) = [4,"4";3,"3";2,"2";1,"1"];; +``` +``` +val everyU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified + +``` +val someU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified + +``` +val size : ('k, 'v, 'id) t -> int +``` +`size s` + +```ocaml + size (fromArray [2,"2"; 2,"1"; 3,"3"] ~id:(module IntCmp)) = 2 ;; +``` +``` +val toArray : ('k, 'v, 'id) t -> ('k * 'v) array +``` +`toArray s` + +```ocaml + toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] +``` +``` +val toList : ('k, 'v, 'id) t -> ('k * 'v) list +``` +In increasing order + +**See** [`toArray`](./#val-toArray) + +``` +val fromArray : ('k * 'v) array -> id:('k, 'id) id -> ('k, 'v, 'id) t +``` +`fromArray kvs ~id` + +```ocaml + toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] +``` +``` +val keysToArray : ('k, 'v, 'id) t -> 'k array +``` +`keysToArray s` + +```ocaml + keysToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = + [|1;2;3|];; +``` +``` +val valuesToArray : ('k, 'v, 'id) t -> 'v array +``` +`valuesToArray s` + +```ocaml + valuesToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = + [|"1";"2";"3"|];; +``` +``` +val minKey : ('k, _, _) t -> 'k option +``` +`minKey s` + +returns the minimum key, None if not exist +``` +val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +**See** [`minKey`](./#val-minKey) + +``` +val maxKey : ('k, _, _) t -> 'k option +``` +`maxKey s` + +returns the maximum key, None if not exist +``` +val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +**See** [`maxKey`](./#val-maxKey) + +``` +val minimum : ('k, 'v, _) t -> ('k * 'v) option +``` +`minimum s` + +returns the minimum key value pair, None if not exist +``` +val minUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined +``` +**See** [`minimum`](./#val-minimum) + +``` +val maximum : ('k, 'v, _) t -> ('k * 'v) option +``` +`maximum s` + +returns the maximum key value pair, None if not exist +``` +val maxUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined +``` +**See** [`maximum`](./#val-maximum) + +``` +val get : ('k, 'v, 'id) t -> 'k -> 'v option +``` +`get s k` + +```ocaml + get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = + Some "2";; + get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = + None;; +``` +``` +val getUndefined : ('k, 'v, 'id) t -> 'k -> 'v Js.undefined +``` +**See** [`get`](./#val-get) + +returns undefined when not found +``` +val getWithDefault : ('k, 'v, 'id) t -> 'k -> 'v -> 'v +``` +`getWithDefault s k default` + +**See** [`get`](./#val-get) + +returns default when k is not found +``` +val getExn : ('k, 'v, 'id) t -> 'k -> 'v +``` +`getExn s k` + +**See** [`getExn`](./#val-getExn) + +**raise** when `k` not exist + +``` +val remove : ('k, 'v, 'id) t -> 'k -> ('k, 'v, 'id) t +``` +`remove m x` when `x` is not in `m`, `m` is returned reference unchanged. + +```ocaml + let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; + + let s1 = remove s0 1;; + let s2 = remove s1 1;; + s1 == s2 ;; + keysToArray s1 = [|2;3|];; +``` +``` +val removeMany : ('k, 'v, 'id) t -> 'k array -> ('k, 'v, 'id) t +``` +`removeMany s xs` + +Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` + +``` +val set : ('k, 'v, 'id) t -> 'k -> 'v -> ('k, 'v, 'id) t +``` +`set m x y ` returns a map containing the same bindings as `m`, with a new binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. + +```ocaml + let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; + + let s1 = set s0 2 "3";; + + valuesToArray s1 = ["1";"3";"3"];; +``` +``` +val updateU : + ('k, 'v, 'id) t -> + 'k -> + ('v option -> 'v option) Js.Fn.arity1 -> + ('k, 'v, 'id) t +``` +``` +val update : + ('k, 'v, 'id) t -> + 'k -> + ('v option -> 'v option) -> + ('k, 'v, 'id) t +``` +`update m x f` returns a map containing the same bindings as `m`, except for the binding of `x`. Depending on the value of `y` where `y` is `f (get x m)`, the binding of `x` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `x` is associated to `z` in the resulting map. + +``` +val mergeMany : ('k, 'v, 'id) t -> ('k * 'v) array -> ('k, 'v, 'id) t +``` +`mergeMany s xs` + +Add each of `xs` to `s`, note unlike [`set`](./#val-set), the reference of return value might be changed even if all values in `xs` exist `s` + +``` +val mergeU : + ('k, 'v, 'id) t -> + ('k, 'v2, 'id) t -> + ('k -> 'v option -> 'v2 option -> 'v3 option) Js.Fn.arity3 -> + ('k, 'v3, 'id) t +``` +``` +val merge : + ('k, 'v, 'id) t -> + ('k, 'v2, 'id) t -> + ('k -> 'v option -> 'v2 option -> 'v3 option) -> + ('k, 'v3, 'id) t +``` +`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. + +``` +val keepU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k, 'v, 'id) t +``` +``` +val keep : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k, 'v, 'id) t +``` +`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. + +``` +val partitionU : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) Js.Fn.arity2 -> + ('k, 'v, 'id) t * ('k, 'v, 'id) t +``` +``` +val partition : + ('k, 'v, 'id) t -> + ('k -> 'v -> bool) -> + ('k, 'v, 'id) t * ('k, 'v, 'id) t +``` +`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. + +``` +val split : + ('k, 'v, 'id) t -> + 'k -> + (('k, 'v, 'id) t * ('k, 'v, 'id) t) * 'v option +``` +`split x m` returns a tuple `(l r), data`, where `l` is the map with all the bindings of `m` whose 'k is strictly less than `x`; `r` is the map with all the bindings of `m` whose 'k is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +``` +val mapU : ('k, 'v, 'id) t -> ('v -> 'v2) Js.Fn.arity1 -> ('k, 'v2, 'id) t +``` +``` +val map : ('k, 'v, 'id) t -> ('v -> 'v2) -> ('k, 'v2, 'id) t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapWithKeyU : + ('k, 'v, 'id) t -> + ('k -> 'v -> 'v2) Js.Fn.arity2 -> + ('k, 'v2, 'id) t +``` +``` +val mapWithKey : ('k, 'v, 'id) t -> ('k -> 'v -> 'v2) -> ('k, 'v2, 'id) t +``` +`mapWithKey m f` + +The same as [`map`](./#val-map) except that `f` is supplied with one more argument: the key + +``` +val getData : ('k, 'v, 'id) t -> ('k, 'v, 'id) Belt__.Belt_MapDict.t +``` +`getData s0` + +**Advanced usage only** + +returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing +``` +val getId : ('k, 'v, 'id) t -> ('k, 'id) id +``` +`getId s0` + +**Advanced usage only** + +returns the identity of s0 +``` +val packIdData : + id:('k, 'id) id -> + data:('k, 'v, 'id) Belt__.Belt_MapDict.t -> + ('k, 'v, 'id) t +``` +`packIdData ~id ~data` + +**Advanced usage only** + +returns the packed collection \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableMap-Int.md b/docs/api/re/melange/Belt-MutableMap-Int.md new file mode 100644 index 000000000..09b46fa13 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableMap-Int.md @@ -0,0 +1,165 @@ + +# Module `MutableMap.Int` + +``` +type key = int +``` +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val isEmpty : 'a t -> bool +``` +``` +val has : 'a t -> key -> bool +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair + +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq m1 m2 cmp` + +``` +val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'a t -> (key -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. + +``` +val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + +``` +val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'a t -> (key -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. + +``` +val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'a t -> (key -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. + +``` +val size : 'a t -> int +``` +``` +val toList : 'a t -> (key * 'a) list +``` +In increasing order + +``` +val toArray : 'a t -> (key * 'a) array +``` +In increasing order + +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'a t -> (key * 'a) option +``` +``` +val minUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val maximum : 'a t -> (key * 'a) option +``` +``` +val maxUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val getUndefined : 'a t -> key -> 'a Js.undefined +``` +``` +val getWithDefault : 'a t -> key -> 'a -> 'a +``` +``` +val getExn : 'a t -> key -> 'a +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held + +``` +val remove : 'a t -> key -> unit +``` +`remove m x` do the in-place modification + +``` +val removeMany : 'a t -> key array -> unit +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. + +``` +val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit +``` +``` +val update : 'a t -> key -> ('a option -> 'a option) -> unit +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableMap-String.md b/docs/api/re/melange/Belt-MutableMap-String.md new file mode 100644 index 000000000..8743e1b84 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableMap-String.md @@ -0,0 +1,165 @@ + +# Module `MutableMap.String` + +``` +type key = string +``` +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val isEmpty : 'a t -> bool +``` +``` +val has : 'a t -> key -> bool +``` +``` +val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int +``` +`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair + +``` +val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool +``` +`eq m1 m2 cmp` + +``` +val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : 'a t -> (key -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. + +``` +val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + +``` +val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : 'a t -> (key -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. + +``` +val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : 'a t -> (key -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. + +``` +val size : 'a t -> int +``` +``` +val toList : 'a t -> (key * 'a) list +``` +In increasing order + +``` +val toArray : 'a t -> (key * 'a) array +``` +In increasing order + +``` +val fromArray : (key * 'a) array -> 'a t +``` +``` +val keysToArray : 'a t -> key array +``` +``` +val valuesToArray : 'a t -> 'a array +``` +``` +val minKey : _ t -> key option +``` +``` +val minKeyUndefined : _ t -> key Js.undefined +``` +``` +val maxKey : _ t -> key option +``` +``` +val maxKeyUndefined : _ t -> key Js.undefined +``` +``` +val minimum : 'a t -> (key * 'a) option +``` +``` +val minUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val maximum : 'a t -> (key * 'a) option +``` +``` +val maxUndefined : 'a t -> (key * 'a) Js.undefined +``` +``` +val get : 'a t -> key -> 'a option +``` +``` +val getUndefined : 'a t -> key -> 'a Js.undefined +``` +``` +val getWithDefault : 'a t -> key -> 'a -> 'a +``` +``` +val getExn : 'a t -> key -> 'a +``` +``` +val checkInvariantInternal : _ t -> unit +``` +**raise** when invariant is not held + +``` +val remove : 'a t -> key -> unit +``` +`remove m x` do the in-place modification + +``` +val removeMany : 'a t -> key array -> unit +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. + +``` +val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit +``` +``` +val update : 'a t -> key -> ('a option -> 'a option) -> unit +``` +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t +``` +``` +val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableMap.md b/docs/api/re/melange/Belt-MutableMap.md new file mode 100644 index 000000000..cf079ddd2 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableMap.md @@ -0,0 +1,206 @@ + +# Module `Belt.MutableMap` + +[`Belt.MutableMap`](#) + +The top level provides generic **mutable** map operations. + +It also has two specialized inner modules [`Belt.MutableMap.Int`](./Belt-MutableMap-Int.md) and [`Belt.MutableMap.String`](./Belt-MutableMap-String.md) + +``` +module Int : sig ... end +``` +``` +module String : sig ... end +``` +A **mutable** sorted map module which allows customize *compare* behavior. + +Same as Belt.Map, but mutable. + +``` +type ('k, 'v, 'id) t +``` +``` +type ('key, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'key) +``` +``` +val make : id:('k, 'id) id -> ('k, 'a, 'id) t +``` +``` +val clear : (_, _, _) t -> unit +``` +``` +val isEmpty : (_, _, _) t -> bool +``` +``` +val has : ('k, _, _) t -> 'k -> bool +``` +``` +val cmpU : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + ('a -> 'a -> int) Js.Fn.arity2 -> + int +``` +``` +val cmp : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> int) -> int +``` +`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair + +``` +val eqU : + ('k, 'a, 'id) t -> + ('k, 'a, 'id) t -> + ('a -> 'a -> bool) Js.Fn.arity2 -> + bool +``` +``` +val eq : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> bool) -> bool +``` +`eq m1 m2 eqf` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `eqf` is the equality predicate used to compare the data associated with the keys. + +``` +val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit +``` +``` +val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit +``` +`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val reduceU : + ('k, 'a, 'id) t -> + 'b -> + ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> + 'b +``` +``` +val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b +``` +`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + +``` +val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`every m p` checks if all the bindings of the map satisfy the predicate `p`. + +``` +val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool +``` +``` +val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool +``` +`some m p` checks if at least one binding of the map satisfy the predicate `p`. + +``` +val size : ('k, 'a, 'id) t -> int +``` +``` +val toList : ('k, 'a, 'id) t -> ('k * 'a) list +``` +In increasing order + +``` +val toArray : ('k, 'a, 'id) t -> ('k * 'a) array +``` +In increasing order + +``` +val fromArray : ('k * 'a) array -> id:('k, 'id) id -> ('k, 'a, 'id) t +``` +``` +val keysToArray : ('k, _, _) t -> 'k array +``` +``` +val valuesToArray : (_, 'a, _) t -> 'a array +``` +``` +val minKey : ('k, _, _) t -> 'k option +``` +``` +val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val maxKey : ('k, _, _) t -> 'k option +``` +``` +val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined +``` +``` +val minimum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val maximum : ('k, 'a, _) t -> ('k * 'a) option +``` +``` +val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined +``` +``` +val get : ('k, 'a, 'id) t -> 'k -> 'a option +``` +``` +val getUndefined : ('k, 'a, 'id) t -> 'k -> 'a Js.undefined +``` +``` +val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> 'a +``` +``` +val getExn : ('k, 'a, 'id) t -> 'k -> 'a +``` +``` +val checkInvariantInternal : (_, _, _) t -> unit +``` +**raise** when invariant is not held + +``` +val remove : ('k, 'a, 'id) t -> 'k -> unit +``` +`remove m x` do the in-place modification, + +``` +val removeMany : ('k, 'a, 'id) t -> 'k array -> unit +``` +``` +val set : ('k, 'a, 'id) t -> 'k -> 'a -> unit +``` +`set m x y ` do the in-place modification + +``` +val updateU : + ('k, 'a, 'id) t -> + 'k -> + ('a option -> 'a option) Js.Fn.arity1 -> + unit +``` +``` +val update : ('k, 'a, 'id) t -> 'k -> ('a option -> 'a option) -> unit +``` +``` +val mergeMany : ('k, 'a, 'id) t -> ('k * 'a) array -> unit +``` +``` +val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t +``` +``` +val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t +``` +`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapWithKeyU : + ('k, 'a, 'id) t -> + ('k -> 'a -> 'b) Js.Fn.arity2 -> + ('k, 'b, 'id) t +``` +``` +val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableQueue.md b/docs/api/re/melange/Belt-MutableQueue.md new file mode 100644 index 000000000..fcb94e0a5 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableQueue.md @@ -0,0 +1,114 @@ + +# Module `Belt.MutableQueue` + +[`Belt.MutableQueue`](#) + +An FIFO(first in first out) queue data structure + +First-in first-out queues. + +This module implements queues (FIFOs), with in-place modification. + +``` +type 'a t +``` +The type of queues containing elements of type `'a`. + +``` +val make : unit -> 'a t +``` +returns a new queue, initially empty. +``` +val clear : 'a t -> unit +``` +Discard all elements from the queue. + +``` +val isEmpty : 'a t -> bool +``` +returns true if the given queue is empty, false otherwise. +``` +val fromArray : 'a array -> 'a t +``` +`fromArray a` is equivalent to `Array.forEach a (add q a)` + +``` +val add : 'a t -> 'a -> unit +``` +`add q x` adds the element `x` at the end of the queue `q`. + +``` +val peek : 'a t -> 'a option +``` +`peekOpt q` returns the first element in queue `q`, without removing it from the queue. + +``` +val peekUndefined : 'a t -> 'a Js.undefined +``` +`peekUndefined q` returns `undefined` if not found + +``` +val peekExn : 'a t -> 'a +``` +`peekExn q` + +**raise** an exception if `q` is empty + +``` +val pop : 'a t -> 'a option +``` +`pop q` removes and returns the first element in queue `q`. + +``` +val popUndefined : 'a t -> 'a Js.undefined +``` +`popUndefined q` removes and returns the first element in queue `q`. it will return undefined if it is already empty + +``` +val popExn : 'a t -> 'a +``` +`popExn q` + +**raise** an exception if `q` is empty + +``` +val copy : 'a t -> 'a t +``` +`copy q` + +returns a fresh queue +``` +val size : 'a t -> int +``` +returns the number of elements in a queue. +``` +val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t +``` +``` +val map : 'a t -> ('a -> 'b) -> 'b t +``` +``` +val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> unit) -> unit +``` +`forEach q f` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. + +``` +val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b +``` +``` +val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b +``` +`reduce q accu f` is equivalent to `List.reduce l accu f`, where `l` is the list of `q`'s elements. The queue remains unchanged. + +``` +val transfer : 'a t -> 'a t -> unit +``` +`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `forEach (fun x -> add x q2) q1; clear q1`, but runs in constant time. + +``` +val toArray : 'a t -> 'a array +``` +First added will be in the beginning of the array diff --git a/docs/api/re/melange/Belt-MutableSet-Int.md b/docs/api/re/melange/Belt-MutableSet-Int.md new file mode 100644 index 000000000..5c5d225e5 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableSet-Int.md @@ -0,0 +1,166 @@ + +# Module `MutableSet.Int` + +Specalized when key type is `int`, more efficient than the generic type + +This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. + +It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + +**See** [`Belt.MutableSet`](./Belt-MutableSet.md) + +``` +type value = int +``` +The type of the set elements. + +``` +type t +``` +The type of sets. + +``` +val make : unit -> t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val copy : t -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> unit +``` +``` +val addCheck : t -> value -> bool +``` +``` +val mergeMany : t -> value array -> unit +``` +``` +val remove : t -> value -> unit +``` +``` +val removeCheck : t -> value -> bool +``` +``` +val removeMany : t -> value array -> unit +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +``` +val cmp : t -> t -> int +``` +``` +val eq : t -> t -> bool +``` +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +In increasing order + +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. + +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. + +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order with respect + +``` +val toArray : t -> value array +``` +In increasing order with respect + +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split s key` return a fresh copy of each + +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-MutableSet-String.md b/docs/api/re/melange/Belt-MutableSet-String.md new file mode 100644 index 000000000..df5e825f6 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableSet-String.md @@ -0,0 +1,166 @@ + +# Module `MutableSet.String` + +Specalized when key type is `string`, more efficient than the generic type + +This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. + +It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) + +**See** [`Belt.MutableSet`](./Belt-MutableSet.md) + +``` +type value = string +``` +The type of the set elements. + +``` +type t +``` +The type of sets. + +``` +val make : unit -> t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val copy : t -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> unit +``` +``` +val addCheck : t -> value -> bool +``` +``` +val mergeMany : t -> value array -> unit +``` +``` +val remove : t -> value -> unit +``` +``` +val removeCheck : t -> value -> bool +``` +``` +val removeMany : t -> value array -> unit +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +``` +val cmp : t -> t -> int +``` +``` +val eq : t -> t -> bool +``` +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +In increasing order + +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. + +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. + +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order with respect + +``` +val toArray : t -> value array +``` +In increasing order with respect + +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split s key` return a fresh copy of each + +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-MutableSet.md b/docs/api/re/melange/Belt-MutableSet.md new file mode 100644 index 000000000..ab101f1c9 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableSet.md @@ -0,0 +1,189 @@ + +# Module `Belt.MutableSet` + +[`Belt.MutableSet`](#) + +The top level provides generic **mutable** set operations. + +It also has two specialized inner modules [`Belt.MutableSet.Int`](./Belt-MutableSet-Int.md) and [`Belt.MutableSet.String`](./Belt-MutableSet-String.md) + +A *mutable* sorted set module which allows customize *compare* behavior. + +Same as Belt.Set, but mutable. + +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type + +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type + +``` +type ('k, 'id) t +``` +``` +type ('k, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'k) +``` +``` +val make : id:('value, 'id) id -> ('value, 'id) t +``` +``` +val fromArray : 'k array -> id:('k, 'id) id -> ('k, 'id) t +``` +``` +val fromSortedArrayUnsafe : + 'value array -> + id:('value, 'id) id -> + ('value, 'id) t +``` +``` +val copy : ('k, 'id) t -> ('k, 'id) t +``` +``` +val isEmpty : (_, _) t -> bool +``` +``` +val has : ('value, _) t -> 'value -> bool +``` +``` +val add : ('value, 'id) t -> 'value -> unit +``` +``` +val addCheck : ('value, 'id) t -> 'value -> bool +``` +``` +val mergeMany : ('value, 'id) t -> 'value array -> unit +``` +``` +val remove : ('value, 'id) t -> 'value -> unit +``` +``` +val removeCheck : ('value, 'id) t -> 'value -> bool +``` +``` +val removeMany : ('value, 'id) t -> 'value array -> unit +``` +``` +val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +``` +val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +``` +val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +``` +val subset : ('value, 'id) t -> ('value, 'id) t -> bool +``` +``` +val cmp : ('value, 'id) t -> ('value, 'id) t -> int +``` +``` +val eq : ('value, 'id) t -> ('value, 'id) t -> bool +``` +``` +val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('value, 'id) t -> ('value -> unit) -> unit +``` +`forEach m f` applies `f` in turn to all elements of `m`. In increasing order + +``` +val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a +``` +In increasing order. + +``` +val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : ('value, 'id) t -> ('value -> bool) -> bool +``` +`every s p` checks if all elements of the set satisfy the predicate `p`. Order unspecified + +``` +val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : ('value, 'id) t -> ('value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. + +``` +val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t +``` +``` +val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t +``` +`keep s p` returns the set of all elements in `s` that satisfy predicate `p`. + +``` +val partitionU : + ('value, 'id) t -> + ('value -> bool) Js.Fn.arity1 -> + ('value, 'id) t * ('value, 'id) t +``` +``` +val partition : + ('value, 'id) t -> + ('value -> bool) -> + ('value, 'id) t * ('value, 'id) t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + +``` +val size : ('value, 'id) t -> int +``` +``` +val toList : ('value, 'id) t -> 'value list +``` +In increasing order + +``` +val toArray : ('value, 'id) t -> 'value array +``` +In increasing order + +``` +val minimum : ('value, 'id) t -> 'value option +``` +``` +val minUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val maximum : ('value, 'id) t -> 'value option +``` +``` +val maxUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val get : ('value, 'id) t -> 'value -> 'value option +``` +``` +val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined +``` +``` +val getExn : ('value, 'id) t -> 'value -> 'value +``` +``` +val split : + ('value, 'id) t -> + 'value -> + (('value, 'id) t * ('value, 'id) t) * bool +``` +`split s x` returns a triple `((l, r), present)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. `l,r` are freshly made, no sharing with `s` + +``` +val checkInvariantInternal : (_, _) t -> unit +``` +**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-MutableStack.md b/docs/api/re/melange/Belt-MutableStack.md new file mode 100644 index 000000000..291f3caa3 --- /dev/null +++ b/docs/api/re/melange/Belt-MutableStack.md @@ -0,0 +1,62 @@ + +# Module `Belt.MutableStack` + +[`Belt.MutableStack`](#) + +An FILO(first in last out) stack data structure + +First in last out stack. + +This module implements stacks, with in-place modification. + +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +returns a new stack, initially empty. +``` +val clear : 'a t -> unit +``` +Discard all elements from the stack. + +``` +val copy : 'a t -> 'a t +``` +`copy x` O(1) operation, return a new stack + +``` +val push : 'a t -> 'a -> unit +``` +``` +val popUndefined : 'a t -> 'a Js.undefined +``` +``` +val pop : 'a t -> 'a option +``` +``` +val topUndefined : 'a t -> 'a Js.undefined +``` +``` +val top : 'a t -> 'a option +``` +``` +val isEmpty : 'a t -> bool +``` +``` +val size : 'a t -> int +``` +``` +val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : 'a t -> ('a -> unit) -> unit +``` +``` +val dynamicPopIterU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit +``` +``` +val dynamicPopIter : 'a t -> ('a -> unit) -> unit +``` +`dynamicPopIter s f ` apply `f` to each element of `s`. The item is poped before applying `f`, `s` will be empty after this opeartion. This function is useful for worklist algorithm diff --git a/docs/api/re/melange/Belt-Option.md b/docs/api/re/melange/Belt-Option.md new file mode 100644 index 000000000..a13563de7 --- /dev/null +++ b/docs/api/re/melange/Belt-Option.md @@ -0,0 +1,200 @@ + +# Module `Belt.Option` + +[`Belt.Option`](#) + +Utilities for option data type. + +[`Belt.Option`](#) + +Utilities for option data type + +``` +val keepU : 'a option -> ('a -> bool) Js.Fn.arity1 -> 'a option +``` +Uncurried version of `keep` + +``` +val keep : 'a option -> ('a -> bool) -> 'a option +``` +`keep optionValue p` + +If `optionValue` is `Some value` and `p value = true`, it returns `Some value`; otherwise returns `None` + +```ocaml + keep (Some 10)(fun x -> x > 5);; (* returns [Some 10] *) + keep (Some 4)(fun x -> x > 5);; (* returns [None] *) + keep None (fun x -> x > 5);; (* returns [None] *) +``` +``` +val forEachU : 'a option -> ('a -> unit) Js.Fn.arity1 -> unit +``` +Uncurried version of `forEach` + +``` +val forEach : 'a option -> ('a -> unit) -> unit +``` +`forEach optionValue f` + +If `optionValue` is `Some value`, it calls `f value`; otherwise returns `()` + +```ocaml + forEach (Some "thing")(fun x -> Js.log x);; (* logs "thing" *) + forEach None (fun x -> Js.log x);; (* returns () *) +``` +``` +val getExn : 'a option -> 'a +``` +`getExn optionalValue` Returns `value` if `optionalValue` is `Some value`, otherwise raises `getExn` + +```ocaml + getExn (Some 3) = 3;; + getExn None (* Raises getExn error *) +``` +``` +val getUnsafe : 'a option -> 'a +``` +`getUnsafe x` returns x This is an unsafe operation, it assumes x is neither not None or (Some (None .. )) + +``` +val mapWithDefaultU : 'a option -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b +``` +Uncurried version of `mapWithDefault` + +``` +val mapWithDefault : 'a option -> 'b -> ('a -> 'b) -> 'b +``` +`mapWithDefault optionValue default f` + +If `optionValue` is `Some value`, returns `f value`; otherwise returns `default` + +```ocaml + mapWithDefault (Some 3) 0 (fun x -> x + 5) = 8;; + mapWithDefault None 0 (fun x -> x + 5) = 0;; +``` +``` +val mapU : 'a option -> ('a -> 'b) Js.Fn.arity1 -> 'b option +``` +Uncurried version of `map` + +``` +val map : 'a option -> ('a -> 'b) -> 'b option +``` +`map optionValue f` + +If `optionValue` is `Some value`, returns `Some (f value)`; otherwise returns `None` + +```ocaml + map (Some 3) (fun x -> x * x) = (Some 9);; + map None (fun x -> x * x) = None;; +``` +``` +val flatMapU : 'a option -> ('a -> 'b option) Js.Fn.arity1 -> 'b option +``` +Uncurried version of `flatMap` + +``` +val flatMap : 'a option -> ('a -> 'b option) -> 'b option +``` +`flatMap optionValue f` + +If `optionValue` is `Some value`, returns `f value`; otherwise returns `None` The function `f` must have a return type of `'a option` + +```ocaml + let f (x : float) = + if x >= 0.0 then + Some (sqrt x) + else + None;; + + flatMap (Some 4.0) f = Some 2.0;; + flatMap (Some (-4.0)) f = None;; + flatMap None f = None;; +``` +``` +val getWithDefault : 'a option -> 'a -> 'a +``` +`getWithDefault optionalValue default` + +If `optionalValue` is `Some value`, returns `value`, otherwise `default` + +```ocaml + getWithDefault (Some 1812) 1066 = 1812;; + getWithDefault None 1066 = 1066;; +``` +``` +val orElse : 'a option -> 'a option -> 'a option +``` +`orElse optionalValue otherOptional` + +If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOptional` + +```ocaml + orElse (Some 1812) (Some 1066) = Some 1812;; + orElse None (Some 1066) = Some 1066;; + orElse None None = None;; +``` +``` +val isSome : 'a option -> bool +``` +Returns `true` if the argument is `Some value`, `false` otherwise + +``` +val isNone : 'a option -> bool +``` +Returns `true` if the argument is `None`, `false` otherwise + +``` +val eqU : 'a option -> 'b option -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +Uncurried version of `eq` + +``` +val eq : 'a option -> 'b option -> ('a -> 'b -> bool) -> bool +``` +`eq optValue1 optvalue2 predicate` + +Evaluates two optional values for equality with respect to a predicate function. + +If both `optValue1` and `optValue2` are `None`, returns `true`. + +If one of the arguments is `Some value` and the other is `None`, returns `false` + +If arguments are `Some value1` and `Some value2`, returns the result of `predicate value1 value2`; the `predicate` function must return a `bool` + +```ocaml + let clockEqual = (fun a b -> a mod 12 = b mod 12);; + eq (Some 3) (Some 15) clockEqual = true;; + eq (Some 3) None clockEqual = false;; + eq None (Some 3) clockEqual = false;; + eq None None clockEqual = true;; +``` +``` +val cmpU : 'a option -> 'b option -> ('a -> 'b -> int) Js.Fn.arity2 -> int +``` +Uncurried version of `cmp` + +``` +val cmp : 'a option -> 'b option -> ('a -> 'b -> int) -> int +``` +`cmp optValue1 optvalue2 comparisonFcn` + +Compares two optional values with respect to a comparison function + +If both `optValue1` and `optValue2` are `None`, returns 0. + +If the first argument is `Some value1` and the second is `None`, returns 1 (something is greater than nothing) + +If the first argument is `None` and the second is `Some value2`, returns \-1 (nothing is less than something) + +If the arguments are `Some value1` and `Some value2`, returns the result of `comparisonFcn value1 value2`; `comparisonFcn` takes two arguments and returns \-1 if the first argument is less than the second, 0 if the arguments are equal, and 1 if the first argument is greater than the second. + +```ocaml + let clockCompare = fun a b -> compare (a mod 12) (b mod 12);; + cmp (Some 3) (Some 15) clockCompare = 0;; + cmp (Some 3) (Some 14) clockCompare = 1;; + cmp (Some 2) (Some 15) clockCompare = -1;; + cmp None (Some 15) clockCompare = -1;; + cmp (Some 14) None clockCompare = 1;; + cmp None None clockCompare = 0;; +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Range.md b/docs/api/re/melange/Belt-Range.md new file mode 100644 index 000000000..fabb4625e --- /dev/null +++ b/docs/api/re/melange/Belt-Range.md @@ -0,0 +1,62 @@ + +# Module `Belt.Range` + +[`Belt.Range`](#) + +Utilities for a closed range `(from, start)` + +A small module to provide a inclusive range operations `[start, finsish]`, it use a for-loop internally instead of creating an array + +``` +val forEachU : int -> int -> (int -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : int -> int -> (int -> unit) -> unit +``` +`forEach start finish action` + +equivalent to `Belt.Array.(forEach (range start finish) action)` + +``` +val everyU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : int -> int -> (int -> bool) -> bool +``` +`every start finish p` + +equivalent to `Belt.Array.(every (range start finish) p )` + +``` +val everyByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val everyBy : int -> int -> step:int -> (int -> bool) -> bool +``` +`everyBy start finish ~step p` + +**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) + +equivalent to `Belt.Array.(every (rangeBy start finish ~step) p)` + +``` +val someU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : int -> int -> (int -> bool) -> bool +``` +`some start finish p` + +equivalent to `Belt.Array.(some (range start finish) p)` + +``` +val someByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool +``` +``` +val someBy : int -> int -> step:int -> (int -> bool) -> bool +``` +`someBy start finish ~step p` + +**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) + +equivalent to `Belt.Array.(some (rangeBy start finish ~step) p)` diff --git a/docs/api/re/melange/Belt-Result.md b/docs/api/re/melange/Belt-Result.md new file mode 100644 index 000000000..093023ba0 --- /dev/null +++ b/docs/api/re/melange/Belt-Result.md @@ -0,0 +1,165 @@ + +# Module `Belt.Result` + +[`Belt.Result`](#) + +Utilities for result data type. + +`Belt.Result` is a data type with two variants: `Ok` and `Error`. Each of these variants can contain data, and those two pieces of data need not have the same data type. `Belt.Result` is useful when you need to not only determine whether some data is valid or not (use `Belt.Option` for that), but also keep information about the invalid data. + +In the examples, we presume the existence of two variables: + +```ocaml +let good = Ok 42 +let bad = Error "Invalid data" +``` +``` +type ('a, 'b) t = ('a, 'b) result = +``` +``` +| Ok of 'a +``` +``` +| Error of 'b +``` +``` + +``` +``` +val getExn : ('a, 'b) t -> 'a +``` +`getExn res` + +when `res` is `Ok n`, returns `n` when `res` is `Error m`, **raise** an exception + +```ocaml + getExn good = 42;; + getExn bad;; (* raises exception *) +``` +``` +val mapWithDefaultU : ('a, 'c) t -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b +``` +``` +val mapWithDefault : ('a, 'c) t -> 'b -> ('a -> 'b) -> 'b +``` +`mapWithDefault res default f` + +When `res` is `Ok n`, returns `f n`, otherwise `default`. + +```ocaml + mapWithDefault good 0 (fun x -> x / 2) = 21 + mapWithDefault bad 0 (fun x -> x / 2) = 0 +``` +``` +val mapU : ('a, 'c) t -> ('a -> 'b) Js.Fn.arity1 -> ('b, 'c) t +``` +``` +val map : ('a, 'c) t -> ('a -> 'b) -> ('b, 'c) t +``` +`map res f` + +When `res` is `Ok n`, returns `Ok (f n)`. Otherwise returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns an ordinary value. + +```ocaml + let f x = sqrt (float_of_int x) + map (Ok 64) f = Ok 8.0 + map (Error "Invalid data") f = Error "Invalid data" +``` +``` +val flatMapU : ('a, 'c) t -> ('a -> ('b, 'c) t) Js.Fn.arity1 -> ('b, 'c) t +``` +``` +val flatMap : ('a, 'c) t -> ('a -> ('b, 'c) t) -> ('b, 'c) t +``` +`flatMap res f` + +When `res` is `Ok n`, returns `f n`. Otherwise, returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns a `Belt.Result`. + +```ocaml +let recip x = + if x != 0.0 + then + Ok (1.0 /. x) + else + Error "Divide by zero" + + flatMap (Ok 2.0) recip = Ok 0.5 + flatMap (Ok 0.0) recip = Error "Divide by zero" + flatMap (Error "Already bad") recip = Error "Already bad" +``` +``` +val getWithDefault : ('a, 'b) t -> 'a -> 'a +``` +`getWithDefault res defaultValue` + +if `res` is `Ok n`, returns `n`, otherwise `default` + +```ocaml + getWithDefault (Ok 42) 0 = 42 + getWithDefault (Error "Invalid Data") = 0 +``` +``` +val isOk : ('a, 'b) t -> bool +``` +`isOk res` + +Returns `true` if `res` is of the form `Ok n`, `false` if it is the `Error e` variant. + +``` +val isError : ('a, 'b) t -> bool +``` +`isError res` + +Returns `true` if `res` is of the form `Error e`, `false` if it is the `Ok n` variant. + +``` +val eqU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool +``` +``` +val eq : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) -> bool +``` +`eq res1 res2 f` + +Determine if two `Belt.Result` variables are equal with respect to an equality function. If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If one of `res1` and `res2` are of the form `Error e`, return false If both `res1` and `res2` are of the form `Error e`, return true + +```ocaml + let good1 = Ok 42 + let good2 = Ok 32 + let bad1 = Error "invalid" + let bad2 = Error "really invalid" + + let mod10equal a b = + a mod 10 == b mod 10 + + eq good1 good2 mod10equal = true + eq good1 bad1 mod10equal = false + eq bad2 good2 mod10equal = false + eq bad1 bad2 mod10equal = true +``` +``` +val cmpU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) Js.Fn.arity2 -> int +``` +``` +val cmp : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) -> int +``` +`cmp res1 res2 f` + +Compare two `Belt.Result` variables with respect to a comparison function. The comparison function returns \-1 if the first variable is "less than" the second, 0 if the two variables are equal, and 1 if the first is "greater than" the second. + +If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If `res1` is of the form `Error e` and `res2` of the form `Ok n`, return \-1 (nothing is less than something) If `res1` is of the form `Ok n` and `res2` of the form `Error e`, return 1 (something is greater than nothing) If both `res1` and `res2` are of the form `Error e`, return 0 (equal) + +```ocaml + let good1 = Ok 59 + let good2 = Ok 37 + let bad1 = Error "invalid" + let bad2 = Error "really invalid" + + let mod10cmp a b = + Pervasives.compare (a mod 10) (b mod 10) + + cmp (Ok 39) (Ok 57) mod10cmp = 1 + cmp (Ok 57) (Ok 39) mod10cmp = -1 + cmp (Ok 39) (Error "y") mod10cmp = 1 + cmp (Error "x") (Ok 57) mod10cmp = -1 + cmp (Error "x") (Error "y") mod10cmp = 0 +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Set-Dict.md b/docs/api/re/melange/Belt-Set-Dict.md new file mode 100644 index 000000000..249bfc951 --- /dev/null +++ b/docs/api/re/melange/Belt-Set-Dict.md @@ -0,0 +1,197 @@ + +# Module `Set.Dict` + +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + +``` +type ('value, 'identity) t +``` +``` +type ('value, 'id) cmp +``` +``` +val empty : ('value, 'id) t +``` +``` +val fromArray : 'value array -> cmp:('value, 'id) cmp -> ('value, 'id) t +``` +``` +val fromSortedArrayUnsafe : 'value array -> ('value, 'id) t +``` +``` +val isEmpty : (_, _) t -> bool +``` +``` +val has : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> bool +``` +``` +val add : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> ('value, 'id) t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. + +``` +val mergeMany : + ('value, 'id) t -> + 'value array -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val remove : + ('value, 'id) t -> + 'value -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + +``` +val removeMany : + ('value, 'id) t -> + 'value array -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val union : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val intersect : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val diff : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + ('value, 'id) t +``` +``` +val subset : + ('value, 'id) t -> + ('value, 'id) t -> + cmp:('value, 'id) cmp -> + bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + +``` +val cmp : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. + +``` +val eq : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> bool +``` +`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + +``` +val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('value, 'id) t -> ('value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order + +``` +val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a +``` +Iterate in increasing order. + +``` +val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : ('value, 'id) t -> ('value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + +``` +val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : ('value, 'id) t -> ('value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + +``` +val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t +``` +``` +val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t +``` +`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. + +``` +val partitionU : + ('value, 'id) t -> + ('value -> bool) Js.Fn.arity1 -> + ('value, 'id) t * ('value, 'id) t +``` +``` +val partition : + ('value, 'id) t -> + ('value -> bool) -> + ('value, 'id) t * ('value, 'id) t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + +``` +val size : ('value, 'id) t -> int +``` +``` +val toList : ('value, 'id) t -> 'value list +``` +In increasing order + +``` +val toArray : ('value, 'id) t -> 'value array +``` +``` +val minimum : ('value, 'id) t -> 'value option +``` +``` +val minUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val maximum : ('value, 'id) t -> 'value option +``` +``` +val maxUndefined : ('value, 'id) t -> 'value Js.undefined +``` +``` +val get : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value option +``` +``` +val getUndefined : + ('value, 'id) t -> + 'value -> + cmp:('value, 'id) cmp -> + 'value Js.undefined +``` +``` +val getExn : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value +``` +``` +val split : + ('value, 'id) t -> + 'value -> + cmp:('value, 'id) cmp -> + (('value, 'id) t * ('value, 'id) t) * bool +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + +``` +val checkInvariantInternal : (_, _) t -> unit +``` +**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-Set-Int.md b/docs/api/re/melange/Belt-Set-Int.md new file mode 100644 index 000000000..697d28cf4 --- /dev/null +++ b/docs/api/re/melange/Belt-Set-Int.md @@ -0,0 +1,163 @@ + +# Module `Set.Int` + +Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) + +**See** [`Belt.Set`](./Belt-Set.md) + +``` +type value = int +``` +The type of the set elements. + +``` +type t +``` +The type of sets. + +``` +val empty : t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. + +``` +val mergeMany : t -> value array -> t +``` +``` +val remove : t -> value -> t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + +``` +val removeMany : t -> value array -> t +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + +``` +val cmp : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. + +``` +val eq : t -> t -> bool +``` +`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order + +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. + +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. + +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order + +``` +val toArray : t -> value array +``` +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-Set-String.md b/docs/api/re/melange/Belt-Set-String.md new file mode 100644 index 000000000..cd17e0b37 --- /dev/null +++ b/docs/api/re/melange/Belt-Set-String.md @@ -0,0 +1,163 @@ + +# Module `Set.String` + +Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) + +**See** [`Belt.Set`](./Belt-Set.md) + +``` +type value = string +``` +The type of the set elements. + +``` +type t +``` +The type of sets. + +``` +val empty : t +``` +``` +val fromArray : value array -> t +``` +``` +val fromSortedArrayUnsafe : value array -> t +``` +``` +val isEmpty : t -> bool +``` +``` +val has : t -> value -> bool +``` +``` +val add : t -> value -> t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. + +``` +val mergeMany : t -> value array -> t +``` +``` +val remove : t -> value -> t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + +``` +val removeMany : t -> value array -> t +``` +``` +val union : t -> t -> t +``` +``` +val intersect : t -> t -> t +``` +``` +val diff : t -> t -> t +``` +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + +``` +val cmp : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. + +``` +val eq : t -> t -> bool +``` +`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + +``` +val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : t -> (value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order + +``` +val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a +``` +Iterate in increasing order. + +``` +val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : t -> (value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + +``` +val someU : t -> (value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : t -> (value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. + +``` +val keepU : t -> (value -> bool) Js.Fn.arity1 -> t +``` +``` +val keep : t -> (value -> bool) -> t +``` +`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. + +``` +val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t +``` +``` +val partition : t -> (value -> bool) -> t * t +``` +`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + +``` +val size : t -> int +``` +``` +val toList : t -> value list +``` +In increasing order + +``` +val toArray : t -> value array +``` +``` +val minimum : t -> value option +``` +``` +val minUndefined : t -> value Js.undefined +``` +``` +val maximum : t -> value option +``` +``` +val maxUndefined : t -> value Js.undefined +``` +``` +val get : t -> value -> value option +``` +``` +val getUndefined : t -> value -> value Js.undefined +``` +``` +val getExn : t -> value -> value +``` +``` +val split : t -> value -> (t * t) * bool +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + +``` +val checkInvariantInternal : t -> unit +``` +**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-Set.md b/docs/api/re/melange/Belt-Set.md new file mode 100644 index 000000000..d923eb6f2 --- /dev/null +++ b/docs/api/re/melange/Belt-Set.md @@ -0,0 +1,377 @@ + +# Module `Belt.Set` + +[`Belt.Set`](#) + +The top level provides generic **immutable** set operations. + +It also has three specialized inner modules [`Belt.Set.Int`](./Belt-Set-Int.md), [`Belt.Set.String`](./Belt-Set-String.md) and + +[`Belt.Set.Dict`](./Belt-Set-Dict.md): This module separates data from function which is more verbose but slightly more efficient + +A *immutable* sorted set module which allows customize *compare* behavior. + +The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + +For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. + +Example usage: + +```ocaml + module PairComparator = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c + end) + + let mySet = Belt.Set.make ~id:(module PairComparator) + let mySet2 = Belt.Set.add mySet (1, 2) +``` +The API documentation below will assume a predeclared comparator module for integers, IntCmp + +``` +module Int : sig ... end +``` +Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +``` +module String : sig ... end +``` +Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison + +``` +module Dict : sig ... end +``` +This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation + +``` +type ('value, 'identity) t +``` +`('value, 'identity) t` + +`'value` is the element type + +`'identity` the identity of the collection + +``` +type ('value, 'id) id = + (module Belt__.Belt_Id.Comparable + with type identity = 'id + and type t = 'value) +``` +The identity needed for making a set from scratch + +``` +val make : id:('value, 'id) id -> ('value, 'id) t +``` +`make ~id` creates a new set by taking in the comparator + +```ocaml + let s = make ~id:(module IntCmp) +``` +``` +val fromArray : 'value array -> id:('value, 'id) id -> ('value, 'id) t +``` +`fromArray xs ~id` + +```ocaml + toArray (fromArray [1;3;2;4] (module IntCmp)) = [1;2;3;4] +``` +``` +val fromSortedArrayUnsafe : + 'value array -> + id:('value, 'id) id -> + ('value, 'id) t +``` +`fromSortedArrayUnsafe xs ~id` + +The same as [`fromArray`](./#val-fromArray) except it is after assuming the input array `x` is already sorted + +**Unsafe** + +``` +val isEmpty : (_, _) t -> bool +``` +```ocaml + isEmpty (fromArray [||] ~id:(module IntCmp)) = true;; + isEmpty (fromArray [|1|] ~id:(module IntCmp)) = true;; +``` +``` +val has : ('value, 'id) t -> 'value -> bool +``` +```ocaml + let v = fromArray [|1;4;2;5|] ~id:(module IntCmp);; + has v 3 = false;; + has v 1 = true;; +``` +``` +val add : ('value, 'id) t -> 'value -> ('value, 'id) t +``` +`add s x` If `x` was already in `s`, `s` is returned unchanged. + +```ocaml + let s0 = make ~id:(module IntCmp);; + let s1 = add s0 1 ;; + let s2 = add s1 2;; + let s3 = add s2 2;; + toArray s0 = [||];; + toArray s1 = [|1|];; + toArray s2 = [|1;2|];; + toArray s3 = [|1;2|];; + s2 == s3;; +``` +``` +val mergeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t +``` +`mergeMany s xs` + +Adding each of `xs` to `s`, note unlike [`add`](./#val-add), the reference of return value might be changed even if all values in `xs` exist `s` + +``` +val remove : ('value, 'id) t -> 'value -> ('value, 'id) t +``` +`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|2;3;1;4;5|];; + let s1 = remove s0 1 ;; + let s2 = remove s1 3 ;; + let s3 = remove s2 3 ;; + + toArray s1 = [|2;3;4;5|];; + toArray s2 = [|2;4;5|];; + s2 == s3;; +``` +``` +val removeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t +``` +`removeMany s xs` + +Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` + +``` +val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +`union s0 s1` + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + toArray (union s0 s1) = [|1;2;3;4;5;6|] +``` +``` +val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +`intersect s0 s1` + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + toArray (intersect s0 s1) = [|2;3;5|] +``` +``` +val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t +``` +`diff s0 s1` + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + toArray (diff s0 s1) = [|6|];; + toArray (diff s1 s0) = [|1;4|];; +``` +``` +val subset : ('value, 'id) t -> ('value, 'id) t -> bool +``` +`subset s0 s1` + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; + let s2 = intersect s0 s1;; + subset s2 s0 = true;; + subset s2 s1 = true;; + subset s1 s0 = false;; +``` +``` +val cmp : ('value, 'id) t -> ('value, 'id) t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. It compare `size` first and then iterate over each element following the order of elements + +``` +val eq : ('value, 'id) t -> ('value, 'id) t -> bool +``` +`eq s0 s1` + +returns true if toArray s0 = toArray s1 +``` +val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit +``` +``` +val forEach : ('value, 'id) t -> ('value -> unit) -> unit +``` +`forEach s f` applies `f` in turn to all elements of `s`. In increasing order + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + let acc = ref [] ;; + forEach s0 (fun x -> acc := x !acc);; + !acc = [6;5;3;2];; +``` +``` +val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a +``` +``` +val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a +``` +In increasing order. + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + reduce s0 [] Belt.List.add = [6;5;3;2];; +``` +``` +val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val every : ('value, 'id) t -> ('value -> bool) -> bool +``` +`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. + +``` +val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool +``` +``` +val some : ('value, 'id) t -> ('value -> bool) -> bool +``` +`some p s` checks if at least one element of the set satisfies the predicate `p`. + +``` +val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t +``` +``` +val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t +``` +`keep m p` returns the set of all elements in `s` that satisfy predicate `p`. + +``` +val partitionU : + ('value, 'id) t -> + ('value -> bool) Js.Fn.arity1 -> + ('value, 'id) t * ('value, 'id) t +``` +``` +val partition : + ('value, 'id) t -> + ('value -> bool) -> + ('value, 'id) t * ('value, 'id) t +``` +`partition m p` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. + +``` +val size : ('value, 'id) t -> int +``` +`size s` + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + size s0 = 4;; +``` +``` +val toArray : ('value, 'id) t -> 'value array +``` +`toArray s0` + +```ocaml + let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; + toArray s0 = [|2;3;5;6|];; +``` +``` +val toList : ('value, 'id) t -> 'value list +``` +In increasing order + +**See** [`toArray`](./#val-toArray) + +``` +val minimum : ('value, 'id) t -> 'value option +``` +`minimum s0` + +returns the minimum element of the collection, None if it is empty +``` +val minUndefined : ('value, 'id) t -> 'value Js.undefined +``` +`minUndefined s0` + +returns the minimum element of the collection, undefined if it is empty +``` +val maximum : ('value, 'id) t -> 'value option +``` +`maximum s0` + +returns the maximum element of the collection, None if it is empty +``` +val maxUndefined : ('value, 'id) t -> 'value Js.undefined +``` +`maxUndefined s0` + +returns the maximum element of the collection, undefined if it is empty +``` +val get : ('value, 'id) t -> 'value -> 'value option +``` +`get s0 k` + +returns the reference of the value k' which is equivalent to k using the comparator specifiecd by this collection, None if it does not exist +``` +val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined +``` +**See** [`get`](./#val-get) + +``` +val getExn : ('value, 'id) t -> 'value -> 'value +``` +**See** [`get`](./#val-get) + +**raise** if not exist + +``` +val split : + ('value, 'id) t -> + 'value -> + (('value, 'id) t * ('value, 'id) t) * bool +``` +`split set ele` + +returns a tuple ((smaller, larger), present), present is true when ele exist in set +Below are operations only when better performance needed, it is still safe API but more verbose. More API will be exposed by needs + +``` +val getData : ('value, 'id) t -> ('value, 'id) Belt__.Belt_SetDict.t +``` +`getData s0` + +**Advanced usage only** + +returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing +``` +val getId : ('value, 'id) t -> ('value, 'id) id +``` +`getId s0` + +**Advanced usage only** + +returns the identity of s0 +``` +val packIdData : + id:('value, 'id) id -> + data:('value, 'id) Belt__.Belt_SetDict.t -> + ('value, 'id) t +``` +`packIdData ~id ~data` + +**Advanced usage only** + +returns the packed collection \ No newline at end of file diff --git a/docs/api/re/melange/Belt-SortArray-Int.md b/docs/api/re/melange/Belt-SortArray-Int.md new file mode 100644 index 000000000..44bd7b00f --- /dev/null +++ b/docs/api/re/melange/Belt-SortArray-Int.md @@ -0,0 +1,39 @@ + +# Module `SortArray.Int` + +Specalized when key type is `int`, more efficient than the generic type + +This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined + +``` +type element = int +``` +``` +val strictlySortedLength : element array -> int +``` +The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed + +returns \+n means increasing order -n means negative order +``` +val isSorted : element array -> bool +``` +`sorted xs` return true if `xs` is in non strict increasing order + +``` +val stableSortInPlace : element array -> unit +``` +The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed + +``` +val stableSort : element array -> element array +``` +The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed + +``` +val binarySearch : element array -> element -> int +``` +If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. + +If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) + +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/re/melange/Belt-SortArray-String.md b/docs/api/re/melange/Belt-SortArray-String.md new file mode 100644 index 000000000..842fd2dd0 --- /dev/null +++ b/docs/api/re/melange/Belt-SortArray-String.md @@ -0,0 +1,39 @@ + +# Module `SortArray.String` + +Specalized when key type is `string`, more efficient than the generic type + +This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined + +``` +type element = string +``` +``` +val strictlySortedLength : element array -> int +``` +The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed + +returns \+n means increasing order -n means negative order +``` +val isSorted : element array -> bool +``` +`sorted xs` return true if `xs` is in non strict increasing order + +``` +val stableSortInPlace : element array -> unit +``` +The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed + +``` +val stableSort : element array -> element array +``` +The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed + +``` +val binarySearch : element array -> element -> int +``` +If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. + +If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) + +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/re/melange/Belt-SortArray.md b/docs/api/re/melange/Belt-SortArray.md new file mode 100644 index 000000000..67893ed3b --- /dev/null +++ b/docs/api/re/melange/Belt-SortArray.md @@ -0,0 +1,81 @@ + +# Module `Belt.SortArray` + +[`Belt.SortArray`](#) + +The top level provides some generic sort related utilities. + +It also has two specialized inner modules [`Belt.SortArray.Int`](./Belt-SortArray-Int.md) and [`Belt.SortArray.String`](./Belt-SortArray-String.md) + +A module for Array sort relevant utiliites + +``` +module Int : sig ... end +``` +Specalized when key type is `int`, more efficient than the generic type + +``` +module String : sig ... end +``` +Specalized when key type is `string`, more efficient than the generic type + +``` +val strictlySortedLengthU : 'a array -> ('a -> 'a -> bool) Js.Fn.arity2 -> int +``` +``` +val strictlySortedLength : 'a array -> ('a -> 'a -> bool) -> int +``` +`strictlySortedLenght xs cmp` return `+n` means increasing order `-n` means negative order + +```ocaml + strictlySortedLength [|1;2;3;4;3|] (fun x y -> x < y) = 4;; + strictlySortedLength [||] (fun x y -> x < y) = 0;; + strictlySortedLength [|1|] (fun x y -> x < y) = 1;; + strictlySortedLength [|4;3;2;1|] (fun x y -> x < y) = -4;; +``` +``` +val isSortedU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> bool +``` +``` +val isSorted : 'a array -> ('a -> 'a -> int) -> bool +``` +`isSorted arr cmp` + +returns true if array is increasingly sorted (equal is okay ) isSorted \[\|1;1;2;3;4\|\] (fun x y -\> compare x y) = true +``` +val stableSortInPlaceByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> unit +``` +``` +val stableSortInPlaceBy : 'a array -> ('a -> 'a -> int) -> unit +``` +`stableSortBy xs cmp` + +Sort xs in place using comparator `cmp`, the stable means if the elements are equal, their order will be preserved + +``` +val stableSortByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a array +``` +``` +val stableSortBy : 'a array -> ('a -> 'a -> int) -> 'a array +``` +`stableSort xs cmp` + +returns a fresh array +The same as [`stableSortInPlaceBy`](./#val-stableSortInPlaceBy) except that `xs` is not modified + +``` +val binarySearchByU : 'a array -> 'a -> ('a -> 'a -> int) Js.Fn.arity2 -> int +``` +``` +val binarySearchBy : 'a array -> 'a -> ('a -> 'a -> int) -> int +``` +If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. + +If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) + +for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` + +```ocaml + binarySearchBy [|1;2;3;4;33;35;36|] 33 = 4;; + lnot (binarySearchBy [|1;3;5;7|] 4) = 2;; +``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt.md b/docs/api/re/melange/Belt.md new file mode 100644 index 000000000..59effce75 --- /dev/null +++ b/docs/api/re/melange/Belt.md @@ -0,0 +1,168 @@ + +# Module `Belt` + +A stdlib shipped with Melange + +This stdlib is still in *beta* but we encourage you to try it out and give us feedback. + +**Motivation** + +The motivation for creating such library is to provide Melange users a better end-to-end user experience, since the original OCaml stdlib was not written with JS in mind. Below is a list of areas this lib aims to improve: + +1. Consistency in name convention: camlCase, and arguments order +2. Exception thrown functions are all suffixed with *Exn*, e.g, *getExn* +3. Better performance and smaller code size running on JS platform +**Name Convention** + +For higher order functions, it will be suffixed **U** if it takes uncurried callback. + +```ocaml + val forEach : 'a t -> ('a -> unit) -> unit + val forEachU : 'a t -> ('a -> unit [\@u]) -> unit +``` +In general, uncurried version will be faster, but it may be less familiar to people who have a background in functional programming. + +**A special encoding for collection safety** + +When we create a collection library for a custom data type we need a way to provide a comparator function. Take *Set* for example, suppose its element type is a pair of ints, it needs a custom *compare* function that takes two tuples and returns their order. The *Set* could not just be typed as ` Set.t (int * int) `, its customized *compare* function needs to manifest itself in the signature, otherwise, if the user creates another customized *compare* function, the two collection could mix which would result in runtime error. + +The original OCaml stdlib solved the problem using *functor* which creates a big closure at runtime and makes dead code elimination much harder. We use a phantom type to solve the problem: + +```ocaml + module Comparable1 = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c + end) + +let mySet1 = Belt.Set.make ~id:(module Comparable1) + +module Comparable2 = Belt.Id.MakeComparable(struct + type t = int * int + let cmp (a0, a1) (b0, b1) = + match Pervasives.compare a0 b0 with + | 0 -> Pervasives.compare a1 b1 + | c -> c +end) + +let mySet2 = Belt.Set.make ~id:(module Comparable2) +``` +Here, the compiler would infer `mySet1` and `mySet2` having different type, so e.g. a \`merge\` operation that tries to merge these two sets will correctly fail. + +```ocaml + val mySet1 : ((int * int), Comparable1.identity) t + val mySet2 : ((int * int), Comparable2.identity) t +``` +`Comparable1.identity` and `Comparable2.identity` are not the same using our encoding scheme. + +**Collection Hierarchy** + +In general, we provide a generic collection module, but also create specialized modules for commonly used data type. Take *Belt.Set* for example, we provide: + +```ocaml + Belt.Set + Belt.Set.Int + Belt.Set.String +``` +The specialized modules *Belt.Set.Int*, *Belt.Set.String* are in general more efficient. + +Currently, both *Belt\_Set* and *Belt.Set* are accessible to users for some technical reasons, we **strongly recommend** users stick to qualified import, *Belt.Set*, we may hide the internal, *i.e*, *Belt\_Set* in the future + +``` +module Id : sig ... end +``` +[`Belt.Id`](./Belt-Id.md) + +``` +module Array : sig ... end +``` +[`Belt.Array`](./Belt-Array.md) + +``` +module SortArray : sig ... end +``` +[`Belt.SortArray`](./Belt-SortArray.md) + +``` +module MutableQueue : sig ... end +``` +[`Belt.MutableQueue`](./Belt-MutableQueue.md) + +``` +module MutableStack : sig ... end +``` +[`Belt.MutableStack`](./Belt-MutableStack.md) + +``` +module List : sig ... end +``` +[`Belt.List`](./Belt-List.md) + +``` +module Range : sig ... end +``` +[`Belt.Range`](./Belt-Range.md) + +``` +module Set : sig ... end +``` +[`Belt.Set`](./Belt-Set.md) + +``` +module Map : sig ... end +``` +[`Belt.Map`](./Belt-Map.md), + +``` +module MutableSet : sig ... end +``` +[`Belt.MutableSet`](./Belt-MutableSet.md) + +``` +module MutableMap : sig ... end +``` +[`Belt.MutableMap`](./Belt-MutableMap.md) + +``` +module HashSet : sig ... end +``` +[`Belt.HashSet`](./Belt-HashSet.md) + +``` +module HashMap : sig ... end +``` +[`Belt.HashMap`](./Belt-HashMap.md) + +``` +module Option : sig ... end +``` +[`Belt.Option`](./Belt-Option.md) + +[`Belt.Result`](./Belt-Result.md) + +Utilities for result data type. + +``` +module Result : sig ... end +``` +[`Belt.Result`](./Belt-Result.md) + +[`Belt.Int`](./Belt-Int.md) + +Utilities for Int. + +``` +module Int : sig ... end +``` +[`Belt.Int`](./Belt-Int.md) Utililites for Int + +[`Belt.Float`](./Belt-Float.md) + +Utilities for Float. + +``` +module Float : sig ... end +``` +[`Belt.Float`](./Belt-Float.md) Utililites for Float diff --git a/docs/api/re/melange/Dom-Storage.md b/docs/api/re/melange/Dom-Storage.md new file mode 100644 index 000000000..5196172ac --- /dev/null +++ b/docs/api/re/melange/Dom-Storage.md @@ -0,0 +1,30 @@ + +# Module `Dom.Storage` + +``` +type t +``` +``` +val getItem : string -> t -> string option +``` +``` +val setItem : string -> string -> t -> unit +``` +``` +val removeItem : string -> t -> unit +``` +``` +val clear : t -> unit +``` +``` +val key : int -> t -> string option +``` +``` +val length : t -> int +``` +``` +val localStorage : t +``` +``` +val sessionStorage : t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Dom.md b/docs/api/re/melange/Dom.md new file mode 100644 index 000000000..37f92a4ef --- /dev/null +++ b/docs/api/re/melange/Dom.md @@ -0,0 +1,841 @@ + +# Module `Dom` + +``` +type _baseClass +``` +``` +type animation +``` +``` +type cssStyleDeclaration +``` +``` +type cssStyleSheet +``` +``` +type 'a eventTarget_like +``` +``` +type eventTarget = _baseClass eventTarget_like +``` +``` +type _messagePort +``` +``` +type messagePort = _messagePort eventTarget_like +``` +``` +type _serviceWorker +``` +``` +type serviceWorker = _serviceWorker eventTarget_like +``` +``` +type _worker +``` +``` +type worker = _worker eventTarget_like +``` +``` +type 'a _workerGlobalScope +``` +``` +type workerGlobalScope = _baseClass _workerGlobalScope eventTarget_like +``` +``` +type _dedicatedWorkerGlobalScope +``` +``` +type dedicatedWorkerGlobalScope = + _dedicatedWorkerGlobalScope _workerGlobalScope eventTarget_like +``` +``` +type _serviceWorkerGlobalScope +``` +``` +type serviceWorkerGlobalScope = + _serviceWorkerGlobalScope _workerGlobalScope eventTarget_like +``` +``` +type _sharedWorkerGlobalScope +``` +``` +type sharedWorkerGlobalScope = + _sharedWorkerGlobalScope _workerGlobalScope eventTarget_like +``` +``` +type 'a _node +``` +``` +type 'a node_like = 'a _node eventTarget_like +``` +``` +type node = _baseClass node_like +``` +``` +type _attr +``` +``` +type attr = _attr node_like +``` +``` +type 'a _characterData +``` +``` +type 'a characterData_like = 'a _characterData node_like +``` +``` +type characterData = _baseClass characterData_like +``` +``` +type _cdataSection +``` +``` +type cdataSection = _cdataSection characterData_like +``` +``` +type _comment +``` +``` +type comment = _comment characterData_like +``` +``` +type 'a _document +``` +``` +type 'a document_like = 'a _document node_like +``` +``` +type document = _baseClass document_like +``` +``` +type _documentFragment +``` +``` +type documentFragment = _documentFragment node_like +``` +``` +type _documentType +``` +``` +type documentType = _documentType node_like +``` +``` +type domImplementation +``` +``` +type 'a _element +``` +``` +type 'a element_like = 'a _element node_like +``` +``` +type element = _baseClass element_like +``` +``` +type htmlCollection +``` +``` +type htmlFormControlsCollection +``` +``` +type htmlOptionsCollection +``` +``` +type intersectionObserver +``` +``` +type intersectionObserverEntry +``` +``` +type mutationObserver +``` +``` +type mutationRecord +``` +``` +type performanceObserver +``` +``` +type performanceObserverEntryList +``` +``` +type reportingObserver +``` +``` +type reportingObserverOptions +``` +``` +type resizeObserver +``` +``` +type resizeObserverEntry +``` +``` +type namedNodeMap +``` +``` +type nodeList +``` +``` +type radioNodeList +``` +``` +type processingInstruction +``` +``` +type _shadowRoot +``` +``` +type shadowRoot = _shadowRoot node_like +``` +``` +type _text +``` +``` +type text = _text characterData_like +``` +``` +type domRect +``` +``` +type dataTransfer +``` +``` +type domStringMap +``` +``` +type history +``` +``` +type _htmlDocument +``` +``` +type htmlDocument = _htmlDocument document_like +``` +``` +type 'a _htmlElement +``` +``` +type 'a htmlElement_like = 'a _htmlElement element_like +``` +``` +type htmlElement = _baseClass htmlElement_like +``` +``` +type _htmlAnchorElement +``` +``` +type htmlAnchorElement = _htmlAnchorElement htmlElement_like +``` +``` +type _htmlAreaElement +``` +``` +type htmlAreaElement = _htmlAreaElement htmlElement_like +``` +``` +type _htmlAudioElement +``` +``` +type htmlAudioElement = _htmlAudioElement htmlElement_like +``` +``` +type _htmlBaseElement +``` +``` +type htmlBaseElement = _htmlBaseElement htmlElement_like +``` +``` +type _htmlBodyElement +``` +``` +type htmlBodyElement = _htmlBodyElement htmlElement_like +``` +``` +type _htmlBrElement +``` +``` +type htmlBrElement = _htmlBrElement htmlElement_like +``` +``` +type _htmlButtonElement +``` +``` +type htmlButtonElement = _htmlButtonElement htmlElement_like +``` +``` +type _htmlCanvasElement +``` +``` +type htmlCanvasElement = _htmlCanvasElement htmlElement_like +``` +``` +type _htmlDataElement +``` +``` +type htmlDataElement = _htmlDataElement htmlElement_like +``` +``` +type _htmlDataListElement +``` +``` +type htmlDataListElement = _htmlDataListElement htmlElement_like +``` +``` +type _htmlDialogElement +``` +``` +type htmlDialogElement = _htmlDialogElement htmlElement_like +``` +``` +type _htmlDivElement +``` +``` +type htmlDivElement = _htmlDivElement htmlElement_like +``` +``` +type _htmlDlistElement +``` +``` +type htmlDlistElement = _htmlDlistElement htmlElement_like +``` +``` +type _htmlEmbedElement +``` +``` +type htmlEmbedElement = _htmlEmbedElement htmlElement_like +``` +``` +type _htmlFieldSetElement +``` +``` +type htmlFieldSetElement = _htmlFieldSetElement htmlElement_like +``` +``` +type _htmlFormElement +``` +``` +type htmlFormElement = _htmlFormElement htmlElement_like +``` +``` +type _htmlHeadElement +``` +``` +type htmlHeadElement = _htmlHeadElement htmlElement_like +``` +``` +type _htmlHeadingElement +``` +``` +type htmlHeadingElement = _htmlHeadingElement htmlElement_like +``` +``` +type _htmlHrElement +``` +``` +type htmlHrElement = _htmlHrElement htmlElement_like +``` +``` +type _htmlHtmlElement +``` +``` +type htmlHtmlElement = _htmlHtmlElement htmlElement_like +``` +``` +type _htmlIframeElement +``` +``` +type htmlIframeElement = _htmlIframeElement htmlElement_like +``` +``` +type _htmlImageElement +``` +``` +type htmlImageElement = _htmlImageElement htmlElement_like +``` +``` +type _htmlInputElement +``` +``` +type htmlInputElement = _htmlInputElement htmlElement_like +``` +``` +type _htmlLabelElement +``` +``` +type htmlLabelElement = _htmlLabelElement htmlElement_like +``` +``` +type _htmlLegendElement +``` +``` +type htmlLegendElement = _htmlLegendElement htmlElement_like +``` +``` +type _htmlLiElement +``` +``` +type htmlLiElement = _htmlLiElement htmlElement_like +``` +``` +type _htmlLinkElement +``` +``` +type htmlLinkElement = _htmlLinkElement htmlElement_like +``` +``` +type _htmlMapElement +``` +``` +type htmlMapElement = _htmlMapElement htmlElement_like +``` +``` +type _htmlMediaElement +``` +``` +type htmlMediaElement = _htmlMediaElement htmlElement_like +``` +``` +type _htmlMenuElement +``` +``` +type htmlMenuElement = _htmlMenuElement htmlElement_like +``` +``` +type _htmlMetaElement +``` +``` +type htmlMetaElement = _htmlMetaElement htmlElement_like +``` +``` +type _htmlMeterElement +``` +``` +type htmlMeterElement = _htmlMeterElement htmlElement_like +``` +``` +type _htmlModElement +``` +``` +type htmlModElement = _htmlModElement htmlElement_like +``` +``` +type _htmlOListElement +``` +``` +type htmlOListElement = _htmlOListElement htmlElement_like +``` +``` +type _htmlObjectElement +``` +``` +type htmlObjectElement = _htmlObjectElement htmlElement_like +``` +``` +type _htmlOptGroupElement +``` +``` +type htmlOptGroupElement = _htmlOptGroupElement htmlElement_like +``` +``` +type _htmlOptionElement +``` +``` +type htmlOptionElement = _htmlOptionElement htmlElement_like +``` +``` +type _htmlOutputElement +``` +``` +type htmlOutputElement = _htmlOutputElement htmlElement_like +``` +``` +type _htmlParagraphElement +``` +``` +type htmlParagraphElement = _htmlParagraphElement htmlElement_like +``` +``` +type _htmlParamElement +``` +``` +type htmlParamElement = _htmlParamElement htmlElement_like +``` +``` +type _htmlPreElement +``` +``` +type htmlPreElement = _htmlPreElement htmlElement_like +``` +``` +type _htmlProgressElement +``` +``` +type htmlProgressElement = _htmlProgressElement htmlElement_like +``` +``` +type _htmlQuoteElement +``` +``` +type htmlQuoteElement = _htmlQuoteElement htmlElement_like +``` +``` +type _htmlScriptElement +``` +``` +type htmlScriptElement = _htmlScriptElement htmlElement_like +``` +``` +type _htmlSelectElement +``` +``` +type htmlSelectElement = _htmlSelectElement htmlElement_like +``` +``` +type _htmlSlotElement +``` +``` +type htmlSlotElement = _htmlSlotElement htmlElement_like +``` +``` +type _htmlSourceElement +``` +``` +type htmlSourceElement = _htmlSourceElement htmlElement_like +``` +``` +type _htmlSpanElement +``` +``` +type htmlSpanElement = _htmlSpanElement htmlElement_like +``` +``` +type _htmlStyleElement +``` +``` +type htmlStyleElement = _htmlStyleElement htmlElement_like +``` +``` +type _htmlTableCaptionElement +``` +``` +type htmlTableCaptionElement = _htmlTableCaptionElement htmlElement_like +``` +``` +type _htmlTableCellElement +``` +``` +type htmlTableCellElement = _htmlTableCellElement htmlElement_like +``` +``` +type _htmlTableColElement +``` +``` +type htmlTableColElement = _htmlTableColElement htmlElement_like +``` +``` +type _htmlTableDataCellElement +``` +``` +type htmlTableDataCellElement = _htmlTableDataCellElement htmlElement_like +``` +``` +type _htmlTableElement +``` +``` +type htmlTableElement = _htmlTableElement htmlElement_like +``` +``` +type _htmlTableHeaderCellElement +``` +``` +type htmlTableHeaderCellElement = _htmlTableHeaderCellElement htmlElement_like +``` +``` +type _htmlTableRowElement +``` +``` +type htmlTableRowElement = _htmlTableRowElement htmlElement_like +``` +``` +type _htmlTableSectionElement +``` +``` +type htmlTableSectionElement = _htmlTableSectionElement htmlElement_like +``` +``` +type _htmlTextAreaElement +``` +``` +type htmlTextAreaElement = _htmlTextAreaElement htmlElement_like +``` +``` +type _htmlTimeElement +``` +``` +type htmlTimeElement = _htmlTimeElement htmlElement_like +``` +``` +type _htmlTitleElement +``` +``` +type htmlTitleElement = _htmlTitleElement htmlElement_like +``` +``` +type _htmlTrackElement +``` +``` +type htmlTrackElement = _htmlTrackElement htmlElement_like +``` +``` +type _htmlUlistElement +``` +``` +type htmlUlistElement = _htmlUlistElement htmlElement_like +``` +``` +type _htmlUnknownElement +``` +``` +type htmlUnknownElement = _htmlUnknownElement htmlElement_like +``` +``` +type _htmlVideoElement +``` +``` +type htmlVideoElement = _htmlVideoElement htmlElement_like +``` +``` +type location +``` +``` +type window +``` +``` +type _xmlDocument +``` +``` +type xmlDocument = _xmlDocument document_like +``` +``` +type 'a event_like +``` +``` +type event = _baseClass event_like +``` +``` +type 'a _uiEvent +``` +``` +type 'a uiEvent_like = 'a _uiEvent event_like +``` +``` +type uiEvent = _baseClass uiEvent_like +``` +``` +type _animationEvent +``` +``` +type animationEvent = _animationEvent event_like +``` +``` +type _beforeUnloadEvent +``` +``` +type beforeUnloadEvent = _beforeUnloadEvent event_like +``` +``` +type _clipboardEvent +``` +``` +type clipboardEvent = _clipboardEvent event_like +``` +``` +type _closeEvent +``` +``` +type closeEvent = _closeEvent event_like +``` +``` +type _compositionEvent +``` +``` +type compositionEvent = _compositionEvent uiEvent_like +``` +``` +type _customEvent +``` +``` +type customEvent = _customEvent event_like +``` +``` +type _dragEvent +``` +``` +type dragEvent = _dragEvent event_like +``` +``` +type _errorEvent +``` +``` +type errorEvent = _errorEvent event_like +``` +``` +type _focusEvent +``` +``` +type focusEvent = _focusEvent uiEvent_like +``` +``` +type _idbVersionChangeEvent +``` +``` +type idbVersionChangeEvent = _idbVersionChangeEvent event_like +``` +``` +type _inputEvent +``` +``` +type inputEvent = _inputEvent uiEvent_like +``` +``` +type _keyboardEvent +``` +``` +type keyboardEvent = _keyboardEvent uiEvent_like +``` +``` +type _messageEvent +``` +``` +type messageEvent = _messageEvent event_like +``` +``` +type 'a _mouseEvent +``` +``` +type 'a mouseEvent_like = 'a _mouseEvent uiEvent_like +``` +``` +type mouseEvent = _baseClass mouseEvent_like +``` +``` +type _pageTransitionEvent +``` +``` +type pageTransitionEvent = _pageTransitionEvent event_like +``` +``` +type _pointerEvent +``` +``` +type pointerEvent = _pointerEvent mouseEvent_like +``` +``` +type _popStateEvent +``` +``` +type popStateEvent = _popStateEvent event_like +``` +``` +type _progressEvent +``` +``` +type progressEvent = _progressEvent event_like +``` +``` +type _relatedEvent +``` +``` +type relatedEvent = _relatedEvent event_like +``` +``` +type _storageEvent +``` +``` +type storageEvent = _storageEvent event_like +``` +``` +type _svgZoomEvent +``` +``` +type svgZoomEvent = _svgZoomEvent event_like +``` +``` +type _timeEvent +``` +``` +type timeEvent = _timeEvent event_like +``` +``` +type _touchEvent +``` +``` +type touchEvent = _touchEvent uiEvent_like +``` +``` +type _trackEvent +``` +``` +type trackEvent = _trackEvent event_like +``` +``` +type _transitionEvent +``` +``` +type transitionEvent = _transitionEvent event_like +``` +``` +type _webGlContextEvent +``` +``` +type webGlContextEvent = _webGlContextEvent event_like +``` +``` +type _wheelEvent +``` +``` +type wheelEvent = _wheelEvent uiEvent_like +``` +``` +type range +``` +``` +type selection +``` +``` +type domTokenList +``` +``` +type domSettableTokenList +``` +``` +type nodeFilter = { +``` +`acceptNode : element -> int;` +``` +} +``` +``` +type nodeIterator +``` +``` +type treeWalker +``` +``` +type svgRect +``` +``` +type svgPoint +``` +``` +type eventPointerId +``` +``` +type messageChannel +``` +``` +module Storage : sig ... end +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Array.md b/docs/api/re/melange/Js-Array.md new file mode 100644 index 000000000..dff910797 --- /dev/null +++ b/docs/api/re/melange/Js-Array.md @@ -0,0 +1,179 @@ + +# Module `Js.Array` + +Bindings to the functions in `Array.prototype` + +JavaScript Array API + +``` +type 'a t = 'a array +``` +``` +type 'a array_like = 'a Js.array_like +``` +``` +val from : 'a array_like -> 'a array +``` +``` +val fromMap : 'a array_like -> f:('a -> 'b) -> 'b array +``` +``` +val isArray : 'a -> bool +``` +``` +val length : 'a array -> int +``` +Mutating functions + +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> 'a t -> 'a t +``` +``` +val fill : value:'a -> ?start:int -> ?end_:int -> 'a t -> 'a t +``` +``` +val pop : 'a t -> 'a option +``` +https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/push + +``` +val push : value:'a -> 'a t -> int +``` +``` +val pushMany : values:'a array -> 'a t -> int +``` +``` +val reverseInPlace : 'a t -> 'a t +``` +``` +val shift : 'a t -> 'a option +``` +``` +val sortInPlace : 'a t -> 'a t +``` +``` +val sortInPlaceWith : f:('a -> 'a -> int) -> 'a t -> 'a t +``` +``` +val spliceInPlace : start:int -> remove:int -> add:'a array -> 'a t -> 'a t +``` +``` +val removeFromInPlace : start:int -> 'a t -> 'a t +``` +``` +val removeCountInPlace : start:int -> count:int -> 'a t -> 'a t +``` +``` +val unshift : value:'a -> 'a t -> int +``` +``` +val unshiftMany : values:'a array -> 'a t -> int +``` +``` +val concat : other:'a t -> 'a t -> 'a t +``` +``` +val concatMany : arrays:'a t array -> 'a t -> 'a t +``` +``` +val includes : value:'a -> 'a t -> bool +``` +ES2015 + +``` +val join : ?sep:string -> 'a t -> string +``` +Accessor functions + +``` +val indexOf : value:'a -> ?start:int -> 'a t -> int +``` +``` +val lastIndexOf : value:'a -> 'a t -> int +``` +``` +val lastIndexOfFrom : value:'a -> start:int -> 'a t -> int +``` +``` +val copy : 'a t -> 'a t +``` +``` +val slice : ?start:int -> ?end_:int -> 'a t -> 'a t +``` +``` +val toString : 'a t -> string +``` +``` +val toLocaleString : 'a t -> string +``` +Iteration functions + +``` +val entries : 'a t -> (int * 'a) Js.iterator +``` +``` +val every : f:('a -> bool) -> 'a t -> bool +``` +``` +val everyi : f:('a -> int -> bool) -> 'a t -> bool +``` +``` +val filter : f:('a -> bool) -> 'a t -> 'a t +``` +``` +val filteri : f:('a -> int -> bool) -> 'a t -> 'a t +``` +``` +val find : f:('a -> bool) -> 'a t -> 'a option +``` +``` +val findi : f:('a -> int -> bool) -> 'a t -> 'a option +``` +``` +val findIndex : f:('a -> bool) -> 'a t -> int +``` +``` +val findIndexi : f:('a -> int -> bool) -> 'a t -> int +``` +``` +val forEach : f:('a -> unit) -> 'a t -> unit +``` +``` +val forEachi : f:('a -> int -> unit) -> 'a t -> unit +``` +``` +val keys : 'a t -> int Js.iterator +``` +``` +val map : f:('a -> 'b) -> 'a t -> 'b t +``` +``` +val mapi : f:('a -> int -> 'b) -> 'a t -> 'b t +``` +``` +val reduce : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val reducei : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val reduceRight : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val reduceRighti : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b +``` +``` +val some : f:('a -> bool) -> 'a t -> bool +``` +``` +val somei : f:('a -> int -> bool) -> 'a t -> bool +``` +``` +val values : 'a t -> 'a Js.iterator +``` +``` +val unsafe_get : 'a array -> int -> 'a +``` +``` +val unsafe_set : 'a array -> int -> 'a -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Bigint.md b/docs/api/re/melange/Js-Bigint.md new file mode 100644 index 000000000..d4b488ac6 --- /dev/null +++ b/docs/api/re/melange/Js-Bigint.md @@ -0,0 +1,71 @@ + +# Module `Js.Bigint` + +Bindings to functions in JavaScript's `BigInt` + +JavaScript BigInt API + +``` +type t = Js.bigint +``` +``` +val make : 'a -> t +``` +`make repr` creates a new BigInt from the representation `repr`. `repr` can be a number, a string, boolean, etc. + +``` +val asIntN : precision:int -> t -> t +``` +`asIntN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as a signed integer. + +``` +val asUintN : precision:int -> t -> t +``` +`asUintN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as an unsigned integer. + +``` +type toLocaleStringOptions = { +``` +`style : string;` +`currency : string;` +``` +} +``` +``` +val toLocaleString : + locale:string -> + ?options:toLocaleStringOptions -> + t -> + string +``` +`toLocaleString bigint` returns a string with a language-sensitive representation of this BigInt. + +``` +val toString : t -> string +``` +`toString bigint` returns a string representing the specified BigInt value. + +``` +val neg : t -> t +``` +``` +val add : t -> t -> t +``` +``` +val sub : t -> t -> t +``` +Subtraction. + +``` +val mul : t -> t -> t +``` +Multiplication. + +``` +val div : t -> t -> t +``` +Division. + +``` +val rem : t -> t -> t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Blob.md b/docs/api/re/melange/Js-Blob.md new file mode 100644 index 000000000..89b228319 --- /dev/null +++ b/docs/api/re/melange/Js-Blob.md @@ -0,0 +1,54 @@ + +# Module `Js.Blob` + +Bindings to Blob + +``` +type t = Js.blob +``` +``` +type options = { +``` +`type_ : string option;` +A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". + +``endings : [ `transparent | `native ] option;`` +How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the blob without changing them. To convert newlines to the host system's native convention, specify the value native. + +``` +} +``` +``` +val make : string Js.iterator -> ?options:options -> unit -> t +``` +`make (Js.Array.values contents_array)` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. + +``` +val size : t -> float +``` +`size t` returns the size of the Blob in bytes + +``` +val type_ : t -> string +``` +`type_ t` returns the MIME type of the file. + +``` +val arrayBuffer : t -> Js.arrayBuffer Js.promise +``` +`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. + +``` +val bytes : t -> Js.uint8Array Js.promise +``` +`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the blob as an array of bytes. + +``` +val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t +``` +`slice ?start ?end_ ?contentType t` creates and returns a new Blob object which contains data from a subset of the blob on which it's called. + +``` +val text : t -> string Js.promise +``` +`text t` returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. diff --git a/docs/api/re/melange/Js-Console.md b/docs/api/re/melange/Js-Console.md new file mode 100644 index 000000000..b68a7e2de --- /dev/null +++ b/docs/api/re/melange/Js-Console.md @@ -0,0 +1,72 @@ + +# Module `Js.Console` + +``` +val log : 'a -> unit +``` +``` +val log2 : 'a -> 'b -> unit +``` +``` +val log3 : 'a -> 'b -> 'c -> unit +``` +``` +val log4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val logMany : 'a array -> unit +``` +``` +val info : 'a -> unit +``` +``` +val info2 : 'a -> 'b -> unit +``` +``` +val info3 : 'a -> 'b -> 'c -> unit +``` +``` +val info4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val infoMany : 'a array -> unit +``` +``` +val warn : 'a -> unit +``` +``` +val warn2 : 'a -> 'b -> unit +``` +``` +val warn3 : 'a -> 'b -> 'c -> unit +``` +``` +val warn4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val warnMany : 'a array -> unit +``` +``` +val error : 'a -> unit +``` +``` +val error2 : 'a -> 'b -> unit +``` +``` +val error3 : 'a -> 'b -> 'c -> unit +``` +``` +val error4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val errorMany : 'a array -> unit +``` +``` +val trace : unit -> unit +``` +``` +val timeStart : string -> unit +``` +``` +val timeEnd : string -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Date.md b/docs/api/re/melange/Js-Date.md new file mode 100644 index 000000000..3d66c2b18 --- /dev/null +++ b/docs/api/re/melange/Js-Date.md @@ -0,0 +1,319 @@ + +# Module `Js.Date` + +Bindings to the functions in JS's `Date.prototype` + +JavaScript Date API + +``` +type t +``` +``` +val valueOf : t -> float +``` +returns the primitive value of this date, equivalent to getTime + +``` +val make : unit -> t +``` +returns a date representing the current time + +``` +val fromFloat : float -> t +``` +``` +val fromString : string -> t +``` +``` +val makeWithYM : year:float -> month:float -> t +``` +``` +val makeWithYMD : year:float -> month:float -> date:float -> t +``` +``` +val makeWithYMDH : year:float -> month:float -> date:float -> hours:float -> t +``` +``` +val makeWithYMDHM : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + t +``` +``` +val makeWithYMDHMS : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + seconds:float -> + t +``` +``` +val utcWithYM : year:float -> month:float -> float +``` +``` +val utcWithYMD : year:float -> month:float -> date:float -> float +``` +``` +val utcWithYMDH : + year:float -> + month:float -> + date:float -> + hours:float -> + float +``` +``` +val utcWithYMDHM : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + float +``` +``` +val utcWithYMDHMS : + year:float -> + month:float -> + date:float -> + hours:float -> + minutes:float -> + seconds:float -> + float +``` +``` +val now : unit -> float +``` +returns the number of milliseconds since Unix epoch + +``` +val parseAsFloat : string -> float +``` +returns NaN if passed invalid date string + +``` +val getDate : t -> float +``` +return the day of the month (1-31) + +``` +val getDay : t -> float +``` +returns the day of the week (0-6) + +``` +val getFullYear : t -> float +``` +``` +val getHours : t -> float +``` +``` +val getMilliseconds : t -> float +``` +``` +val getMinutes : t -> float +``` +``` +val getMonth : t -> float +``` +returns the month (0-11) + +``` +val getSeconds : t -> float +``` +``` +val getTime : t -> float +``` +returns the number of milliseconds since Unix epoch + +``` +val getTimezoneOffset : t -> float +``` +``` +val getUTCDate : t -> float +``` +return the day of the month (1-31) + +``` +val getUTCDay : t -> float +``` +returns the day of the week (0-6) + +``` +val getUTCFullYear : t -> float +``` +``` +val getUTCHours : t -> float +``` +``` +val getUTCMilliseconds : t -> float +``` +``` +val getUTCMinutes : t -> float +``` +``` +val getUTCMonth : t -> float +``` +returns the month (0-11) + +``` +val getUTCSeconds : t -> float +``` +``` +val setDate : date:float -> t -> float +``` +``` +val setFullYear : year:float -> t -> float +``` +``` +val setFullYearM : year:float -> month:float -> t -> float +``` +``` +val setFullYearMD : year:float -> month:float -> date:float -> t -> float +``` +``` +val setHours : hours:float -> t -> float +``` +``` +val setHoursM : hours:float -> minutes:float -> t -> float +``` +``` +val setHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float +``` +``` +val setHoursMSMs : + hours:float -> + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setMilliseconds : milliseconds:float -> t -> float +``` +``` +val setMinutes : minutes:float -> t -> float +``` +``` +val setMinutesS : minutes:float -> seconds:float -> t -> float +``` +``` +val setMinutesSMs : + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setMonth : month:float -> t -> float +``` +``` +val setMonthD : month:float -> date:float -> t -> float +``` +``` +val setSeconds : seconds:float -> t -> float +``` +``` +val setSecondsMs : seconds:float -> milliseconds:float -> t -> float +``` +``` +val setTime : time:float -> t -> float +``` +``` +val setUTCDate : date:float -> t -> float +``` +``` +val setUTCFullYear : year:float -> t -> float +``` +``` +val setUTCFullYearM : year:float -> month:float -> t -> float +``` +``` +val setUTCFullYearMD : year:float -> month:float -> date:float -> t -> float +``` +``` +val setUTCHours : hours:float -> t -> float +``` +``` +val setUTCHoursM : hours:float -> minutes:float -> t -> float +``` +``` +val setUTCHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float +``` +``` +val setUTCHoursMSMs : + hours:float -> + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setUTCMilliseconds : milliseconds:float -> t -> float +``` +``` +val setUTCMinutes : minutes:float -> t -> float +``` +``` +val setUTCMinutesS : minutes:float -> seconds:float -> t -> float +``` +``` +val setUTCMinutesSMs : + minutes:float -> + seconds:float -> + milliseconds:float -> + t -> + float +``` +``` +val setUTCMonth : month:float -> t -> float +``` +``` +val setUTCMonthD : month:float -> date:float -> t -> float +``` +``` +val setUTCSeconds : seconds:float -> t -> float +``` +``` +val setUTCSecondsMs : seconds:float -> milliseconds:float -> t -> float +``` +``` +val setUTCTime : time:float -> t -> float +``` +``` +val toDateString : t -> string +``` +``` +val toISOString : t -> string +``` +``` +val toJSON : t -> string option +``` +``` +val toJSONUnsafe : t -> string +``` +``` +val toLocaleDateString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val toLocaleTimeString : t -> string +``` +``` +val toString : t -> string +``` +``` +val toTimeString : t -> string +``` +``` +val toUTCString : t -> string +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Dict.md b/docs/api/re/melange/Js-Dict.md new file mode 100644 index 000000000..3a0f74eb6 --- /dev/null +++ b/docs/api/re/melange/Js-Dict.md @@ -0,0 +1,74 @@ + +# Module `Js.Dict` + +Utility functions to treat a JS object as a dictionary + +``` +type 'a t = 'a Js.dict +``` +Dictionary type (ie an '{ }' JS object). However it is restricted to hold a single type; therefore values must have the same type. + +This Dictionary type is mostly used with the `Js_json.t` type. + +``` +type key = string +``` +Key type + +``` +val get : 'a t -> key -> 'a option +``` +`get dict key` returns `None` if the `key` is not found in the dictionary, `Some value` otherwise + +``` +val unsafeGet : 'a t -> key -> 'a +``` +`unsafeGet dict key` return the value if the `key` exists, otherwise an **undefined** value is returned. Must be used only when the existence of a key is certain. (i.e. when having called `keys` function previously. + +```ocaml +Array.iter (fun key -> Js.log (Js_dict.unsafeGet dic key)) (Js_dict.keys dict) +``` +``` +val set : 'a t -> key -> 'a -> unit +``` +`set dict key value` sets the `key`/`value` in `dict` + +``` +val keys : 'a t -> string array +``` +`keys dict` returns all the keys in the dictionary `dict` + +``` +val empty : unit -> 'a t +``` +`empty ()` returns an empty dictionary + +``` +val unsafeDeleteKey : (string t -> string -> unit) Js.Fn.arity2 +``` +Experimental internal function + +``` +val entries : 'a t -> (key * 'a) array +``` +`entries dict` returns the key value pairs in `dict` (ES2017) + +``` +val values : 'a t -> 'a array +``` +`values dict` returns the values in `dict` (ES2017) + +``` +val fromList : (key * 'a) list -> 'a t +``` +`fromList entries` creates a new dictionary containing each `(key, value)` pair in `entries` + +``` +val fromArray : (key * 'a) array -> 'a t +``` +`fromArray entries` creates a new dictionary containing each `(key, value)` pair in `entries` + +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +`map f dict` maps `dict` to a new dictionary with the same keys, using `f` to map each value diff --git a/docs/api/re/melange/Js-Exn.md b/docs/api/re/melange/Js-Exn.md new file mode 100644 index 000000000..afea42336 --- /dev/null +++ b/docs/api/re/melange/Js-Exn.md @@ -0,0 +1,78 @@ + +# Module `Js.Exn` + +Utilities for dealing with Js exceptions + +``` +type t +``` +``` +type exn += private +``` +``` +| Error of t +``` +``` + +``` +``` +val asJsExn : exn -> t option +``` +``` +val stack : t -> string option +``` +``` +val message : t -> string option +``` +``` +val name : t -> string option +``` +``` +val fileName : t -> string option +``` +``` +val isCamlExceptionOrOpenVariant : 'a -> bool +``` +internal use only + +``` +val anyToExnInternal : 'a -> exn +``` +`anyToExnInternal obj` will take any value `obj` and wrap it in a Js.Exn.Error if given value is not an exn already. If `obj` is an exn, it will return `obj` without any changes. + +This function is mostly useful for cases where you want to unify a type of a value that potentially is either exn, a JS error, or any other JS value really (e.g. for a value passed to a Promise.catch callback) + +IMPORTANT: This is an internal API and may be changed / removed any time in the future. + +```ocaml + switch (Js.Exn.unsafeAnyToExn("test")) { + | Js.Exn.Error(v) => + switch (Js.Exn.message(v)) { + | Some(str) => Js.log("We won't end up here") + | None => Js.log2("We will land here: ", v) + } + } +``` +``` +val raiseError : string -> 'a +``` +Raise Js exception Error object with stacktrace + +``` +val raiseEvalError : string -> 'a +``` +``` +val raiseRangeError : string -> 'a +``` +``` +val raiseReferenceError : string -> 'a +``` +``` +val raiseSyntaxError : string -> 'a +``` +``` +val raiseTypeError : string -> 'a +``` +``` +val raiseUriError : string -> 'a +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-File.md b/docs/api/re/melange/Js-File.md new file mode 100644 index 000000000..71a732734 --- /dev/null +++ b/docs/api/re/melange/Js-File.md @@ -0,0 +1,72 @@ + +# Module `Js.File` + +Bindings to File + +``` +type t = Js.file +``` +``` +type options = { +``` +`type_ : string option;` +A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". + +``endings : [ `transparent | `native ] option;`` +How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the file without changing them. To convert newlines to the host system's native convention, specify the value native. + +`lastModified : float option;` +A number representing the number of milliseconds between the Unix time epoch and when the file was last modified. Defaults to a value of Date.now(). + +``` +} +``` +``` +val make : + string Js.iterator -> + filename:string -> + ?options:options -> + unit -> + t +``` +`make contents_array ~filename` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. + +``` +val lastModified : t -> float +``` +`lastModified t` accesses the read-only property of the File interface, which provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + +``` +val name : t -> string +``` +The `name t` read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property. + +``` +val size : t -> float +``` +`size t` returns the size of the File in bytes + +``` +val type_ : t -> string +``` +`type_ t` returns the MIME type of the file. + +``` +val arrayBuffer : t -> Js.arrayBuffer Js.promise +``` +`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. + +``` +val bytes : t -> Js.uint8Array Js.promise +``` +`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the file as an array of bytes. + +``` +val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t +``` +`slice ?start ?end_ ?contentType t` creates and returns a new File object which contains data from a subset of the file on which it's called. + +``` +val text : t -> string Js.promise +``` +`text t` returns a Promise that resolves with a string containing the contents of the file, interpreted as UTF-8. diff --git a/docs/api/re/melange/Js-Float.md b/docs/api/re/melange/Js-Float.md new file mode 100644 index 000000000..fa4803615 --- /dev/null +++ b/docs/api/re/melange/Js-Float.md @@ -0,0 +1,140 @@ + +# Module `Js.Float` + +Bindings to functions in JavaScript's `Number` that deal with floats + +Provides functions for inspecting and manipulating `float`s + +``` +type t = float +``` +``` +val _NaN : t +``` +The special value "Not a Number" + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) MDN +``` +val isNaN : t -> bool +``` +Tests if the given value is `_NaN` + +Note that both `_NaN = _NaN` and `_NaN == _NaN` will return `false`. `isNaN` is therefore necessary to test for `_NaN`. + +**Returns** `true` if the given value is `_NaN`, `false` otherwise + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) MDN +``` +val isFinite : t -> bool +``` +Tests if the given value is finite + +**Returns** `true` if the given value is a finite number, `false` otherwise + +```ocaml +(* returns [false] *) +let _ = Js.Float.isFinite infinity + +(* returns [false] *) +let _ = Js.Float.isFinite neg_infinity + +(* returns [false] *) +let _ = Js.Float.isFinite _NaN + +(* returns [true] *) +let _ = Js.Float.isFinite 1234 +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) MDN +``` +val toExponential : ?digits:int -> t -> string +``` +Formats a `float` using exponential (scientific) notation + +**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). + +**Returns** a `string` representing the given value in exponential notation + +The output will be rounded or padded with zeroes if necessary. + +raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) +```ocaml + Js.Float.toExponential 77.1234 = "7.71234e+1" + Js.Float.toExponential 77. = "7.7e+1" + Js.Float.toExponential ~digits:2 77.1234 = "7.71e+1" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN +``` +val toFixed : ?digits:int -> t -> string +``` +Formats a `float` using fixed point notation + +**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). Defaults to `0`. + +**Returns** a `string` representing the given value in fixed-point notation (usually) + +The output will be rounded or padded with zeroes if necessary. + +raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) +```ocaml + Js.Float.toFixed 12345.6789 = "12346" + Js.Float.toFixed 1.2e21 = "1.2e+21" + Js.Float.toFixed ~digits:1 12345.6789 = "12345.7" + Js.Float.toFixed ~digits:2 0. = "0.00" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toFixed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) MDN +``` +val toPrecision : ?digits:int -> t -> string +``` +Formats a `float` using some fairly arbitrary rules + +**digits** specifies how many digits should appear in total. The value must between 0 and some arbitrary number that's hopefully at least larger than 20 (for Node it's 21. Why? Who knows). + +**Returns** a `string` representing the given value in fixed-point or scientific notation + +The output will be rounded or padded with zeroes if necessary. + +`toPrecision` differs from `toFixed` in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. + +raises `RangeError` if digits is not in the range accepted by this function (what do you mean "vague"?) +```ocaml + Js.Float.toPrecision 12345.6789 = "12345.6789" + Js.Float.toPrecision 1.2e21 = "1.2e+21" + Js.Float.toPrecision ~digits:1 12345.6789 = "1e+4" + Js.Float.toPrecision ~digits:2 0. = "0.0" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN +``` +val toString : ?radix:int -> t -> string +``` +Formats a `float` as a string + +**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). + +**Returns** a `string` representing the given value in fixed-point (usually) + +raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) +```ocaml + Js.Float.toString 12345.6789 = "12345.6789" + Js.Float.toString ~radix:2 6. = "110" + Js.Float.toString ~radix:2 3.14 = "11.001000111101011100001010001111010111000010100011111" + Js.Float.toString ~radix:16 3735928559. = "deadbeef" + Js.Float.toString ~radix:36 123.456 = "3f.gez4w97ry0a18ymf6qadcxr" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN +``` +val fromString : string -> t +``` +Parses the given `string` into a `float` using JavaScript semantics + +**Returns** the number as a `float` if successfully parsed, `_NaN` otherwise. + +```ocaml +Js.Float.fromString "123" = 123. +Js.Float.fromString "12.3" = 12.3 +Js.Float.fromString "" = 0. +Js.Float.fromString "0x11" = 17. +Js.Float.fromString "0b11" = 3. +Js.Float.fromString "0o11" = 9. +Js.Float.fromString "foo" = _NaN +Js.Float.fromString "100a" = _NaN +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-FormData.md b/docs/api/re/melange/Js-FormData.md new file mode 100644 index 000000000..57c30522d --- /dev/null +++ b/docs/api/re/melange/Js-FormData.md @@ -0,0 +1,90 @@ + +# Module `Js.FormData` + +Bindings to FormData + +``` +type t +``` +``` +type entryValue +``` +The values returned by the \`get`,All`\` and iteration functions is either a string or a Blob. Melange uses an abstract type and defers to users of the API to handle it according to their application needs. + +``` +val make : unit -> t +``` +`make ()` creates a new `FormData` object, initially empty. + +``` +val append : + name:string -> + value:[ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> + t -> + unit +``` +`append t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. + +``` +val appendBlob : + name:string -> + value:[ `Blob of Js.blob | `File of Js.file ] -> + ?filename:string -> + t -> + unit +``` +`appendBlob t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. This method differs from `append` in that instances in the Blob hierarchy can pass a third filename argument. + +``` +val delete : name:string -> t -> unit +``` +`delete t ~name` deletes a key and its value(s) from a FormData object. + +``` +val get : name:string -> t -> entryValue option +``` +`get t ~name` returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use [`getAll`](./#val-getAll) instead. + +``` +val getAll : name:string -> t -> entryValue array +``` +`getAll t ~name` returns all the values associated with a given key from within a FormData object. + +``` +val set : + name:string -> + [ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> + t -> + unit +``` +`set t ~name ~value` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. + +``` +val setBlob : + name:string -> + [ `Blob of Js.blob | `File of Js.file ] -> + ?filename:string -> + t -> + unit +``` +`setBlob t ~name ~value ?filename` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. This method differs from `set` in that instances in the Blob hierarchy can pass a third filename argument. + +``` +val has : name:string -> t -> bool +``` +`has ~name t` returns whether a FormData object contains a certain key. + +``` +val keys : t -> string Js.iterator +``` +`keys t` returns an iterator which iterates through all keys contained in the FormData. The keys are strings. + +``` +val values : t -> entryValue Js.iterator +``` +`values t` returns an iterator which iterates through all values contained in the FormData. The values are strings or Blob objects. + +``` +val entries : t -> (string * entryValue) Js.iterator +``` +`entries t` returns an iterator which iterates through all key/value pairs contained in the FormData. diff --git a/docs/api/re/melange/Js-Global.md b/docs/api/re/melange/Js-Global.md new file mode 100644 index 000000000..b8e00b08f --- /dev/null +++ b/docs/api/re/melange/Js-Global.md @@ -0,0 +1,150 @@ + +# Module `Js.Global` + +Bindings to functions in the JS global namespace + +Contains functions available in the global scope (`window` in a browser context) + +``` +type intervalId +``` +Identify an interval started by [`setInterval`](./#val-setInterval) + +``` +type timeoutId +``` +Identify timeout started by [`setTimeout`](./#val-setTimeout) + +``` +val clearInterval : intervalId -> unit +``` +Clear an interval started by [`setInterval`](./#val-setInterval) + +```ocaml +(* API for a somewhat aggressive snoozing alarm clock *) + +let interval = ref Js.Nullable.null + +let remind () = + Js.log "Wake Up!"; + IO.punchSleepyGuy () + +let snooze mins = + interval := Js.Nullable.return (Js.Global.setInterval remind (mins * 60 * 1000)) + +let cancel () = + Js.Nullable.iter !interval (fun[\@u] intervalId -> Js.Global.clearInterval intervalId) +``` +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) MDN +``` +val clearTimeout : timeoutId -> unit +``` +Clear a timeout started by [`setTimeout`](./#val-setTimeout) + +```ocaml +(* A simple model of a code monkey's brain *) + +let timer = ref Js.Nullable.null + +let work () = + IO.closeHackerNewsTab () + +let procrastinate mins = + Js.Nullable.iter !timer (fun[\@u] timer -> Js.Global.clearTimeout timer); + timer := Js.Nullable.return (Js.Global.setTimeout work (mins * 60 * 1000)) +``` +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout) MDN +``` +val setInterval : f:(unit -> unit) -> int -> intervalId +``` +*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls + +**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout + +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN +```ocaml +(* Will count up and print the count to the console every second *) + +let count = ref 0 + +let tick () = + count := !count + 1; Js.log (string_of_int !count) + +let _ = + Js.Global.setInterval tick 1000 +``` +``` +val setIntervalFloat : f:(unit -> unit) -> float -> intervalId +``` +*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls + +**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout + +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN +```ocaml +(* Will count up and print the count to the console every second *) + +let count = ref 0 + +let tick () = + count := !count + 1; Js.log (string_of_int !count) + +let _ = + Js.Global.setIntervalFloat tick 1000.0 +``` +``` +val setTimeout : f:(unit -> unit) -> int -> timeoutId +``` +Execute a callback after a specified delay (in milliseconds) + +**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout + +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN +```ocaml +(* Prints "Timed out!" in the console after one second *) + +let message = "Timed out!" + +let _ = + Js.Global.setTimeout (fun () -> Js.log message) 1000 +``` +``` +val setTimeoutFloat : f:(unit -> unit) -> float -> timeoutId +``` +Execute a callback after a specified delay (in milliseconds) + +**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout + +see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN +```ocaml +(* Prints "Timed out!" in the console after one second *) + +let message = "Timed out!" + +let _ = + Js.Global.setTimeoutFloat (fun () -> Js.log message) 1000.0 +``` +``` +val encodeURI : string -> string +``` +URL-encodes a string. + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) MDN +``` +val decodeURI : string -> string +``` +Decodes a URL-enmcoded string produced by `encodeURI` + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) MDN +``` +val encodeURIComponent : string -> string +``` +URL-encodes a string, including characters with special meaning in a URI. + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) MDN +``` +val decodeURIComponent : string -> string +``` +Decodes a URL-enmcoded string produced by `encodeURIComponent` + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) MDN \ No newline at end of file diff --git a/docs/api/re/melange/Js-Int.md b/docs/api/re/melange/Js-Int.md new file mode 100644 index 000000000..08c28ca4a --- /dev/null +++ b/docs/api/re/melange/Js-Int.md @@ -0,0 +1,79 @@ + +# Module `Js.Int` + +Bindings to functions in JavaScript's `Number` that deal with ints + +Provides functions for inspecting and manipulating `int`s + +``` +type t = int +``` +If we use number, we need coerce to int32 by adding \`\|0\`, otherwise \`+0\` can be wrong. Most JS API is float oriented, it may overflow int32 or comes with `NAN` + +``` +val toExponential : ?digits:t -> t -> string +``` +Formats an `int` using exponential (scientific) notation + +**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). + +**Returns** a `string` representing the given value in exponential notation + +The output will be rounded or padded with zeroes if necessary. + +raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) +```ocaml + Js.Int.toExponential 77 = "7.7e+1" + Js.Int.toExponential ~digits:2 77 = "7.70e+1" + Js.Int.toExponential ~digits:2 5678 = "5.68e+3" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN +``` +val toPrecision : ?digits:t -> t -> string +``` +Formats an `int` using some fairly arbitrary rules + +**digits** specifies how many digits should appear in total. The value must between 1 and some 100. + +**Returns** a `string` representing the given value in fixed-point or scientific notation + +The output will be rounded or padded with zeroes if necessary. + +`toPrecision` differs from [`Js.Float.toFixed`](./Js-Float.md#val-toFixed) in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. + +raises `RangeError` if digits is not between 1 and 100. +```ocaml + Js.Int.toPrecision 123456789 = "123456789" + Js.Int.toPrecision ~digits:2 123456789 = "1.2e+8" + Js.Int.toPrecision ~digits:2 0 = "0.0" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN +``` +val toString : ?radix:t -> t -> string +``` +Formats an `int` as a string + +**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). + +**Returns** a `string` representing the given value in fixed-point (usually) + +raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) +```ocaml + Js.Int.toString 123456789 = "123456789" + Js.Int.toString ~radix:2 6 = "110" + Js.Int.toString ~radix:16 3735928559 = "deadbeef" + Js.Int.toString ~radix:36 123456 = "2n9c" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN +``` +val toFloat : t -> float +``` +``` +val equal : t -> t -> bool +``` +``` +val max : t +``` +``` +val min : t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Iterator.md b/docs/api/re/melange/Js-Iterator.md new file mode 100644 index 000000000..3f07302ff --- /dev/null +++ b/docs/api/re/melange/Js-Iterator.md @@ -0,0 +1,25 @@ + +# Module `Js.Iterator` + +Bindings to functions on `Iterator` + +``` +type 'a t = 'a Js.iterator +``` +``` +type 'a value = { +``` +`done_ : bool option;` +`value : 'a option;` +``` +} +``` +``` +val next : 'a t -> 'a value +``` +``` +val toArray : 'a t -> 'a array +``` +``` +val toArrayWithMapper : 'a t -> f:('a -> 'b) -> 'b array +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Json.md b/docs/api/re/melange/Js-Json.md new file mode 100644 index 000000000..f23f571bf --- /dev/null +++ b/docs/api/re/melange/Js-Json.md @@ -0,0 +1,285 @@ + +# Module `Js.Json` + +Utility functions to manipulate JSON values + +Efficient JSON encoding using JavaScript API @see \ MDN + + +### Types + +``` +type t +``` +The JSON data structure + +``` +type _ kind = +``` +``` +| String : string kind +``` +``` +| Number : float kind +``` +``` +| Object : t Js.dict kind +``` +``` +| Array : t array kind +``` +``` +| Boolean : bool kind +``` +``` +| Null : t Js.null kind +``` +``` + +``` +Underlying type of a JSON value + +``` +type tagged_t = +``` +``` +| JSONFalse +``` +``` +| JSONTrue +``` +``` +| JSONNull +``` +``` +| JSONString of string +``` +``` +| JSONNumber of float +``` +``` +| JSONObject of t Js.dict +``` +``` +| JSONArray of t array +``` +``` + +``` + +### Accessor + +``` +val classify : t -> tagged_t +``` +``` +val test : 'a -> 'b kind -> bool +``` +`test v kind` returns true if `v` is of `kind` + +``` +val decodeString : t -> string option +``` +`decodeString json` returns `Some s` if `json` is a string, `None` otherwise + +``` +val decodeNumber : t -> float option +``` +`decodeNumber json` returns `Some n` if `json` is a number, `None` otherwise + +``` +val decodeObject : t -> t Js.dict option +``` +`decodeObject json` returns `Some o` if `json` is an object, `None` otherwise + +``` +val decodeArray : t -> t array option +``` +`decodeArray json` returns `Some a` if `json` is an array, `None` otherwise + +``` +val decodeBoolean : t -> bool option +``` +`decodeBoolean json` returns `Some b` if `json` is a boolean, `None` otherwise + +``` +val decodeNull : t -> 'a Js.null option +``` +`decodeNull json` returns `Some null` if `json` is a null, `None` otherwise + + +### Construtors + +Those functions allows the construction of an arbitrary complex JSON values. + +``` +val null : t +``` +`null` is the singleton null JSON value + +``` +val string : string -> t +``` +`string s` makes a JSON string of the `string` `s` + +``` +val number : float -> t +``` +`number n` makes a JSON number of the `float` `n` + +``` +val boolean : bool -> t +``` +`boolean b` makes a JSON boolean of the `bool` `b` + +``` +val object_ : t Js.dict -> t +``` +`object_ dict` makes a JSON object of the `Js.dict` `dict` + +``` +val array : t array -> t +``` +`array a` makes a JSON array of the `Js.Json.t array` `a` + +The functions below are specialized for specific array type which happened to be already JSON object in the Melange runtime. Therefore they are more efficient (constant time rather than linear conversion). + +``` +val stringArray : string array -> t +``` +`stringArray a` makes a JSON array of the `string array` `a` + +``` +val numberArray : float array -> t +``` +`numberArray a` makes a JSON array of the `float array` `a` + +``` +val booleanArray : bool array -> t +``` +`booleanArray` makes a JSON array of the `bool array` `a` + +``` +val objectArray : t Js.dict array -> t +``` +`objectArray a` makes a JSON array of the `JsDict.t array` `a` + + +### String conversion + +``` +val parseExn : string -> t +``` +`parseExn s` parses the string `s` into a JSON data structure + +**Returns** a JSON data structure + +raises `SyntaxError` if given string is not a valid JSON. Note SyntaxError is a JavaScript exception. +```ocaml +(* parse a simple JSON string *) + +let json = + try + Js.Json.parseExn {| "foo" |} + with + | _ -> failwith "Error parsing JSON string" +in +match Js.Json.classify json with +| Js.Json.JSONString value -> Js.log value +| _ -> failwith "Expected a string" +``` +```ocaml +(* parse a complex JSON string *) + +let getIds s = + let json = + try + Js.Json.parseExn s + with + | _ -> failwith "Error parsing JSON string" + in + match Js.Json.classify json with + | Js.Json.JSONObject value -> + (* In this branch, compiler infer value : Js.Json.t Js.dict *) + begin match Js.Dict.get value "ids" with + | Some ids -> + begin match Js.Json.classify ids with + | Js.Json.JSONArray ids -> + (* In this branch compiler infer ids : Js.Json.t array *) + ids + | _ -> failwith "Expected an array" + end + | None -> failwith "Expected an `ids` property" + end + | _ -> failwith "Expected an object" + + (* prints `1, 2, 3` *) + let _ = + Js.log (getIds {| { "ids" : [1, 2, 3] } |}) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) MDN +``` +val stringify : t -> string +``` +`stringify json` formats the JSON data structure as a string + +**Returns** the string representation of a given JSON data structure + +```ocaml +(* Creates and stringifies a simple JS object *) + +let dict = Js.Dict.empty () in +Js.Dict.set dict "name" (Js.Json.string "John Doe"); +Js.Dict.set dict "age" (Js.Json.number 30.0); +Js.Dict.set dict "likes" + (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); + +Js.log (Js.Json.stringify (Js.Json.object_ dict)) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN +``` +val stringifyWithSpace : t -> int -> string +``` +`stringify json` formats the JSON data structure as a string + +**Returns** the string representation of a given JSON data structure + +```ocaml +(* Creates and stringifies a simple JS object with spacing *) + +let dict = Js.Dict.empty () in +Js.Dict.set dict "name" (Js.Json.string "John Doe"); +Js.Dict.set dict "age" (Js.Json.number 30.0); +Js.Dict.set dict "likes" + (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); + + Js.log (Js.Json.stringifyWithSpace (Js.Json.object_ dict) 2) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN +``` +val stringifyAny : 'a -> string option +``` +`stringifyAny value` formats any `value` into a JSON string + +```ocaml + (* prints ``"foo", "bar"`` *) + Js.log (Js.Json.stringifyAny [| "foo"; "bar" |]) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN +Best-effort serialization, it tries to seralize as many objects as possible and deserialize it back + +``` +val deserializeUnsafe : string -> 'a +``` +It is unsafe in two aspects + +- It may throw during parsing +- when you cast it to a specific type, it may have a type mismatch +``` +val serializeExn : 'a -> string +``` +It will raise in such situations: + +- The object can not be serlialized to a JSON +- There are cycles +- Some JS engines can not stringify deeply nested json objects \ No newline at end of file diff --git a/docs/api/re/melange/Js-Map.md b/docs/api/re/melange/Js-Map.md new file mode 100644 index 000000000..51c7817bf --- /dev/null +++ b/docs/api/re/melange/Js-Map.md @@ -0,0 +1,49 @@ + +# Module `Js.Map` + +Bindings to functions in `Map` + +ES6 Map API + +``` +type ('k, 'v) t +``` +``` +val make : unit -> ('k, 'v) t +``` +``` +val fromArray : ('k * 'v) array -> ('k, 'v) t +``` +``` +val toArray : ('k, 'v) t -> ('k * 'v) array +``` +``` +val size : ('k, 'v) t -> int +``` +``` +val has : key:'k -> ('k, 'v) t -> bool +``` +``` +val get : key:'k -> ('k, 'v) t -> 'v option +``` +``` +val set : key:'k -> value:'v -> ('k, 'v) t -> ('k, 'v) t +``` +``` +val clear : ('k, 'v) t -> unit +``` +``` +val delete : key:'k -> ('k, 'v) t -> bool +``` +``` +val forEach : f:('v -> 'k -> ('k, 'v) t -> unit) -> ('k, 'v) t -> unit +``` +``` +val keys : ('k, 'v) t -> 'k Js.iterator +``` +``` +val values : ('k, 'v) t -> 'v Js.iterator +``` +``` +val entries : ('k, 'v) t -> ('k * 'v) Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Math.md b/docs/api/re/melange/Js-Math.md new file mode 100644 index 000000000..5d799dbda --- /dev/null +++ b/docs/api/re/melange/Js-Math.md @@ -0,0 +1,299 @@ + +# Module `Js.Math` + +Bindings to the functions in the `Math` object + +JavaScript Math API + +``` +val _E : float +``` +Euler's number + +``` +val _LN2 : float +``` +natural logarithm of 2 + +``` +val _LN10 : float +``` +natural logarithm of 10 + +``` +val _LOG2E : float +``` +base 2 logarithm of E + +``` +val _LOG10E : float +``` +base 10 logarithm of E + +``` +val _PI : float +``` +Pi... (ratio of the circumference and diameter of a circle) + +``` +val _SQRT1_2 : float +``` +square root of 1/2 + +``` +val _SQRT2 : float +``` +square root of 2 + +``` +val abs_int : int -> int +``` +absolute value + +``` +val abs_float : float -> float +``` +absolute value + +``` +val acos : float -> float +``` +arccosine in radians, can return NaN + +``` +val acosh : float -> float +``` +hyperbolic arccosine in raidans, can return NaN, ES2015 + +``` +val asin : float -> float +``` +arcsine in radians, can return NaN + +``` +val asinh : float -> float +``` +hyperbolic arcsine in raidans, ES2015 + +``` +val atan : float -> float +``` +arctangent in radians + +``` +val atanh : float -> float +``` +hyperbolic arctangent in radians, can return NaN, ES2015 + +``` +val atan2 : y:float -> x:float -> float +``` +arctangent of the quotient of x and y, mostly... this one's a bit weird + +``` +val cbrt : float -> float +``` +cube root, can return NaN, ES2015 + +``` +val unsafe_ceil_int : float -> int +``` +may return values not representable by `int` + +``` +val ceil_int : float -> int +``` +smallest int greater than or equal to the argument + +``` +val ceil_float : float -> float +``` +smallest float greater than or equal to the argument + +``` +val clz32 : int -> int +``` +number of leading zero bits of the argument's 32 bit int representation, ES2015 + +``` +val cos : float -> float +``` +cosine in radians + +``` +val cosh : float -> float +``` +hyperbolic cosine in radians, ES2015 + +``` +val exp : float -> float +``` +natural exponentional + +``` +val expm1 : float -> float +``` +natural exponential minus 1, ES2015 + +``` +val unsafe_floor_int : float -> int +``` +may return values not representable by `int` + +``` +val floor_int : float -> int +``` +largest int greater than or equal to the arugment + +``` +val floor_float : float -> float +``` +``` +val fround : float -> float +``` +round to nearest single precision float, ES2015 + +``` +val hypot : float -> float -> float +``` +pythagorean equation, ES2015 + +``` +val hypotMany : float array -> float +``` +generalized pythagorean equation, ES2015 + +``` +val imul : int -> int -> int +``` +32-bit integer multiplication, ES2015 + +``` +val log : float -> float +``` +natural logarithm, can return NaN + +``` +val log1p : float -> float +``` +natural logarithm of 1 \+ the argument, can return NaN, ES2015 + +``` +val log10 : float -> float +``` +base 10 logarithm, can return NaN, ES2015 + +``` +val log2 : float -> float +``` +base 2 logarithm, can return NaN, ES2015 + +``` +val max_int : int -> int -> int +``` +max value + +``` +val maxMany_int : int array -> int +``` +max value + +``` +val max_float : float -> float -> float +``` +max value + +``` +val maxMany_float : float array -> float +``` +max value + +``` +val min_int : int -> int -> int +``` +min value + +``` +val minMany_int : int array -> int +``` +min value + +``` +val min_float : float -> float -> float +``` +min value + +``` +val minMany_float : float array -> float +``` +min value + +``` +val pow_float : base:float -> exp:float -> float +``` +base to the power of the exponent + +``` +val random : unit -> float +``` +random number in \[0,1) + +``` +val random_int : int -> int -> int +``` +random number in \[min,max) + +``` +val unsafe_round : float -> int +``` +rounds to nearest integer, returns a value not representable as `int` if NaN + +``` +val round : float -> float +``` +rounds to nearest integer + +``` +val sign_int : int -> int +``` +the sign of the argument, 1, \-1 or 0, ES2015 + +``` +val sign_float : float -> float +``` +the sign of the argument, 1, \-1, 0, \-0 or NaN, ES2015 + +``` +val sin : float -> float +``` +sine in radians + +``` +val sinh : float -> float +``` +hyperbolic sine in radians, ES2015 + +``` +val sqrt : float -> float +``` +square root, can return NaN + +``` +val tan : float -> float +``` +tangent in radians + +``` +val tanh : float -> float +``` +hyperbolic tangent in radians, ES2015 + +``` +val unsafe_trunc : float -> int +``` +truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 + +``` +val trunc : float -> float +``` +truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 diff --git a/docs/api/re/melange/Js-Null.md b/docs/api/re/melange/Js-Null.md new file mode 100644 index 000000000..46aa576d8 --- /dev/null +++ b/docs/api/re/melange/Js-Null.md @@ -0,0 +1,74 @@ + +# Module `Js.Null` + +Utility functions on [`null`](./Js.md#type-null) + +Provides functionality for dealing with the `'a Js.null` type + +``` +type +'a t = 'a Js.null +``` +Local alias for `'a Js.null` + +``` +val return : 'a -> 'a t +``` +Constructs a value of `'a Js.null` containing a value of `'a` + +``` +val empty : 'a t +``` +The empty value, `null` + +``` +val getUnsafe : 'a t -> 'a +``` +``` +val getExn : 'a t -> 'a +``` +``` +val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t +``` +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +Maps the contained value using the given function + +If `'a Js.null` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.null` + +```ocaml +let maybeGreetWorld (maybeGreeting: string Js.null) = + Js.Null.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") +``` +``` +val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit +``` +Iterates over the contained value with the given function + +If `'a Js.null` contains a value, that value is unwrapped and applied to the given function. + +```ocaml +let maybeSay (maybeMessage: string Js.null) = + Js.Null.iter maybeMessage ~f:(fun message -> Js.log message) +``` +``` +val fromOption : 'a option -> 'a t +``` +Maps `'a option` to `'a Js.null` + + + +
Some a -> return a +
None -> empty +
+ +``` +val toOption : 'a t -> 'a option +``` +Maps `'a Js.null` to `'a option` + + + +
return a -> Some a +
empty -> None +
diff --git a/docs/api/re/melange/Js-Nullable.md b/docs/api/re/melange/Js-Nullable.md new file mode 100644 index 000000000..c4f7ffb3c --- /dev/null +++ b/docs/api/re/melange/Js-Nullable.md @@ -0,0 +1,79 @@ + +# Module `Js.Nullable` + +Utility functions on [`nullable`](./Js.md#type-nullable) + +Contains functionality for dealing with values that can be both `null` and `undefined` + +``` +type +'a t = 'a Js.nullable +``` +Local alias for `'a Js.nullable` + +``` +val return : 'a -> 'a t +``` +Constructs a value of `'a Js.nullable` containing a value of `'a` + +``` +val isNullable : 'a t -> bool +``` +Returns `true` if the given value is `null` or `undefined`, `false` otherwise + +``` +val null : 'a t +``` +The `null` value of type `'a Js.nullable` + +``` +val undefined : 'a t +``` +The `undefined` value of type `'a Js.nullable` + +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +``` +val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t +``` +Binds the contained value using the given function + +If `'a Js.nullable` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.nullable` + +```ocaml +let maybeGreetWorld (maybeGreeting: string Js.nullable) = + Js.Nullable.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") +``` +``` +val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit +``` +Iterates over the contained value with the given function + +If `'a Js.nullable` contains a value, that value is unwrapped and applied to the given function. + +```ocaml +let maybeSay (maybeMessage: string Js.nullable) = + Js.Nullable.iter maybeMessage ~f:(fun message -> Js.log message) +``` +``` +val fromOption : 'a option -> 'a t +``` +Maps `'a option` to `'a Js.nullable` + + + +
Some a -> return a +
None -> undefined +
+ +``` +val toOption : 'a t -> 'a option +``` +Maps `'a Js.nullable` to `'a option` + + + +
return a -> Some a +
undefined -> None +
null -> None +
diff --git a/docs/api/re/melange/Js-Obj.md b/docs/api/re/melange/Js-Obj.md new file mode 100644 index 000000000..7ff457710 --- /dev/null +++ b/docs/api/re/melange/Js-Obj.md @@ -0,0 +1,19 @@ + +# Module `Js.Obj` + +Utility functions on \`Js.t\` JS objects + +``` +val empty : unit -> < .. > Js.t +``` +``` +val assign : < .. > Js.t -> < .. > Js.t -> < .. > Js.t +``` +``` +val merge : < .. > Js.t -> < .. > Js.t -> < .. > Js.t +``` +`merge obj1 obj2` assigns the properties in `obj2` to a copy of `obj1`. The function returns a new object, and both arguments are not mutated + +``` +val keys : _ Js.t -> string array +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Promise.md b/docs/api/re/melange/Js-Promise.md new file mode 100644 index 000000000..2a493825c --- /dev/null +++ b/docs/api/re/melange/Js-Promise.md @@ -0,0 +1,57 @@ + +# Module `Js.Promise` + +Bindings to JS `Promise` functions + +Specialized bindings to Promise. Note: For simplicity, this binding does not track the error type, it treat it as an opaque type + +``` +type +'a t = 'a Js.promise +``` +``` +type error +``` +``` +val make : + (resolve:('a -> unit) Js.Fn.arity1 -> + reject:(exn -> unit) Js.Fn.arity1 -> + unit) -> + 'a t +``` +``` +val resolve : 'a -> 'a t +``` +``` +val reject : exn -> 'a t +``` +``` +val all : 'a t array -> 'a array t +``` +``` +val all2 : ('a0 t * 'a1 t) -> ('a0 * 'a1) t +``` +``` +val all3 : ('a0 t * 'a1 t * 'a2 t) -> ('a0 * 'a1 * 'a2) t +``` +``` +val all4 : ('a0 t * 'a1 t * 'a2 t * 'a3 t) -> ('a0 * 'a1 * 'a2 * 'a3) t +``` +``` +val all5 : + ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t) -> + ('a0 * 'a1 * 'a2 * 'a3 * 'a4) t +``` +``` +val all6 : + ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t * 'a5 t) -> + ('a0 * 'a1 * 'a2 * 'a3 * 'a4 * 'a5) t +``` +``` +val race : 'a t array -> 'a t +``` +``` +val then_ : ('a -> 'b t) -> 'a t -> 'b t +``` +``` +val catch : (error -> 'a t) -> 'a t -> 'a t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Re.md b/docs/api/re/melange/Js-Re.md new file mode 100644 index 000000000..36f5547da --- /dev/null +++ b/docs/api/re/melange/Js-Re.md @@ -0,0 +1,178 @@ + +# Module `Js.Re` + +Bindings to the functions in `RegExp.prototype` + +Provides bindings for JavaScript Regular Expressions + + +##### Syntax sugar + +Melange provides a bit of syntax sugar for regex literals: `[%re "/foo/g"]` will evaluate to a [`t`](./#type-t) that can be passed around and used like usual. + +**Note:** This is not an immutable API. A RegExp object with the `global` ("g") flag set will modify the [`lastIndex`](./#val-lastIndex) property when the RegExp object is used, and subsequent uses will continue the search from the previous [`lastIndex`](./#val-lastIndex). + +```ocaml +let maybeMatches = Js.String.exec ~str:"banana" [\[%re "/na+/g"\]] +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) JavaScript API reference on MDN +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular\_Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) JavaScript Regular Expressions Guide on MDN +``` +type t = Js.re +``` +the RegExp object + +``` +type result +``` +the result of a executing a RegExp on a string + +``` +val captures : result -> string Js.nullable array +``` +an array of the match and captures, the first is the full match and the remaining are the substring captures + +``` +val index : result -> int +``` +0-based index of the match in the input string + +``` +val input : result -> string +``` +the original input string + +``` +val fromString : string -> t +``` +Constructs a RegExp object ([`t`](./#type-t)) from a string + +Regex literals (`[%re "/.../"]`) should generally be preferred, but `fromString` is very useful when you need to insert a string into a regex. + +```ocaml +(* A function that extracts the content of the first element with the given tag *) + +let contentOf tag xmlString = + Js.Re.fromString ("<" ^ tag ^ ">(.*?)<\\/" ^ tag ^">") + |> Js.Re.exec ~str:xmlString + |> function + | Some result -> Js.Nullable.toOption (Js.Re.captures result).(1) + | None -> None +``` +``` +val fromStringWithFlags : string -> flags:string -> t +``` +Constructs a RegExp object ([`t`](./#type-t)) from a string with the given `flags` + +See [`fromString`](./#val-fromString) + +Valid flags: + +
g global +
i ignore case +
m multiline +
u unicode (es2015) +
y sticky (es2015) +
+ + +``` +val flags : t -> string +``` +returns the enabled flags as a string + +``` +val global : t -> bool +``` +returns a bool indicating whether the `global` flag is set + +``` +val ignoreCase : t -> bool +``` +returns a bool indicating whether the `ignoreCase` flag is set + +``` +val lastIndex : t -> int +``` +returns the index where the next match will start its search + +This property will be modified when the RegExp object is used, if the `global` ("g") flag is set. + +```ocaml +(* Finds and prints successive matches *) + +let re = [%re "/ab*/g"] in +let str = "abbcdefabh" in + +let break = ref false in +while not !break do + match re |> Js.Re.exec ~str with + | None -> break := true + | Some result -> + Js.Nullable.iter (Js.Re.captures result).(0) ((fun match_ -> + let next = string_of_int (Js.Re.lastIndex re) in + Js.log ("Found " ^ match_ ^ ". Next match starts at " ^ next))) +done +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/lastIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) MDN +``` +val setLastIndex : t -> int -> unit +``` +sets the index at which the next match will start its search from + +``` +val multiline : t -> bool +``` +returns a bool indicating whether the `multiline` flag is set + +``` +val source : t -> string +``` +returns the pattern as a string + +``` +val sticky : t -> bool +``` +returns a bool indicating whether the `sticky` flag is set + +``` +val unicode : t -> bool +``` +returns a bool indicating whether the `unicode` flag is set + +``` +val exec : str:string -> t -> result option +``` +executes a search on a given string using the given RegExp object + +**returns** `Some` [`result`](./#type-result) if a match is found, `None` otherwise + +```ocaml +(* Match "quick brown" followed by "jumps", ignoring characters in between + * Remember "brown" and "jumps" + * Ignore case + *) + +let re = [%re "/quick\s(brown).+?(jumps)/ig"] in +let result = re |. Js.Re.exec ~str:"The Quick Brown Fox Jumps Over The Lazy Dog" +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/exec](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) MDN +``` +val test : str:string -> t -> bool +``` +tests whether the given RegExp object will match a given string + +**returns** `true` if a match is found, `false` otherwise + +```ocaml +(* A simple implementation of Js.String.startsWith *) + +let str = "hello world!" + +let startsWith target substring = + Js.Re.fromString ("^" ^ substring) + |. Js.Re.test ~str:target + +let () = Js.log (str |. startsWith "hello") (* prints "true" *) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) MDN \ No newline at end of file diff --git a/docs/api/re/melange/Js-Set.md b/docs/api/re/melange/Js-Set.md new file mode 100644 index 000000000..bd1087307 --- /dev/null +++ b/docs/api/re/melange/Js-Set.md @@ -0,0 +1,43 @@ + +# Module `Js.Set` + +Bindings to functions in `Set` + +ES6 Set API + +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val fromArray : 'a array -> 'a t +``` +``` +val toArray : 'a t -> 'a array +``` +``` +val size : 'a t -> int +``` +``` +val add : value:'a -> 'a t -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val delete : value:'a -> 'a t -> bool +``` +``` +val forEach : f:('a -> unit) -> 'a t -> unit +``` +``` +val has : value:'a -> 'a t -> bool +``` +``` +val values : 'a t -> 'a Js.iterator +``` +``` +val entries : 'a t -> ('a * 'a) Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-String.md b/docs/api/re/melange/Js-String.md new file mode 100644 index 000000000..ff90c544a --- /dev/null +++ b/docs/api/re/melange/Js-String.md @@ -0,0 +1,464 @@ + +# Module `Js.String` + +Bindings to the functions in `String.prototype` + +JavaScript String API + +``` +type t = string +``` +``` +val make : 'a -> t +``` +`make value` converts the given value to a string + +```ocaml + make 3.5 = "3.5";; + make [|1;2;3|]) = "1,2,3";; +``` +``` +val fromCharCode : int -> t +``` +`fromCharCode n` creates a string containing the character corresponding to that number; *n* ranges from 0 to 65535. If out of range, the lower 16 bits of the value are used. Thus, `fromCharCode 0x1F63A` gives the same result as `fromCharCode 0xF63A`. + +```ocaml + fromCharCode 65 = "A";; + fromCharCode 0x3c8 = {js|ψ|js};; + fromCharCode 0xd55c = {js|한|js};; + fromCharCode -64568 = {js|ψ|js};; +``` +``` +val fromCharCodeMany : int array -> t +``` +`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given numbers, using the same rules as `fromCharCode`. + +```ocaml + fromCharCodeMany([|0xd55c, 0xae00, 33|]) = {js|한글!|js};; +``` +``` +val fromCodePoint : int -> t +``` +`fromCodePoint n` creates a string containing the character corresponding to that numeric code point. If the number is not a valid code point, **raises** `RangeError`. Thus, `fromCodePoint 0x1F63A` will produce a correct value, unlike `fromCharCode 0x1F63A`, and `fromCodePoint -5` will raise a `RangeError`. + +```ocaml + fromCodePoint 65 = "A";; + fromCodePoint 0x3c8 = {js|ψ|js};; + fromCodePoint 0xd55c = {js|한|js};; + fromCodePoint 0x1f63a = {js|😺|js};; +``` +``` +val fromCodePointMany : int array -> t +``` +`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given code point numbers, using the same rules as `fromCodePoint`. + +```ocaml + fromCodePointMany([|0xd55c; 0xae00; 0x1f63a|]) = {js|한글😺|js} +``` +``` +val length : t -> int +``` +`length s` returns the length of the given string. + +```ocaml + length "abcd" = 4;; +``` +``` +val get : t -> int -> t +``` +`get s n` returns as a string the character at the given index number. If `n` is out of range, this function returns `undefined`, so at some point this function may be modified to return `t option`. + +```ocaml + get "Reason" 0 = "R";; + get "Reason" 4 = "o";; + get {js|Rẽasöń|js} 5 = {js|ń|js};; +``` +``` +val charAt : index:int -> t -> t +``` +`charAt ~index s` gets the character at position `index` within string `s`. If `index` is negative or greater than the length of `s`, returns the empty string. If the string contains characters outside the range `\u0000-\uffff`, it will return the first 16-bit value at that position in the string. + +```ocaml + charAt ~index:0 "Reason" = "R" + charAt ~index:12 "Reason" = ""; + charAt ~index:5 {js|Rẽasöń|js} = {js|ń|js} +``` +``` +val charCodeAt : index:int -> t -> float +``` +`charCodeAt s ~index` returns the character code at position `index` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to `0x10000`. The return type is `float` because this function returns `NaN` if `index` is less than zero or greater than the length of the string. + +```ocaml + charCodeAt ~index:0 {js|😺|js} = 0xd83d + codePointAt ~index:0 {js|😺|js} = Some 0x1f63a +``` +``` +val codePointAt : index:int -> t -> int option +``` +`codePointAt s ~index` returns the code point at position `index` within string `s` as a `Some` value. The return value handles code points greater than or equal to `0x10000`. If there is no code point at the given position, the function returns `None`. + +```ocaml + codePointAt ~index:1 {js|¿😺?|js} = Some 0x1f63a + codePointAt ~index:5 "abc" = None +``` +ES2015 + +``` +val concat : other:t -> t -> t +``` +`concat ~other:str2 str1` returns a new string with `str2` added after `str1`. + +```ocaml + concat ~other:"bell" "cow" = "cowbell";; +``` +``` +val concatMany : strings:t array -> t -> t +``` +`concatMany ~strings original` returns a new string consisting of each item of the array of strings `strings` added to the `original` string. + +```ocaml + concatMany ~strings:[|"2nd"; "3rd"; "4th"|] "1st" = "1st2nd3rd4th";; +``` +``` +val endsWith : suffix:t -> ?len:int -> t -> bool +``` +`endsWith ~suffix ?len str` returns `true` if the `str` ends with `suffix`, `false` otherwise. If `len` is specified, \`endsWith\` only takes into account the first `len` characters. + +```ocaml + endsWith ~suffix:"cd" ~len:4 "abcd" = true;; + endsWith ~suffix:"cd" ~len:3 "abcde" = false;; + endsWith ~suffix:"cde" ~len:99 "abcde" = true;; + endsWith ~suffix:"ple" ~len:7 "example.dat" = true;; + endsWith ~suffix:"World!" "Hello, World!" = true;; + endsWith ~suffix:"world!" "Hello, World!" = false;; (* case-sensitive *) + endsWith ~suffix:"World" "Hello, World!" = false;; (* exact match *) +``` +``` +val includes : search:t -> ?start:int -> t -> bool +``` +`includes ~search ?start s` returns `true` if `search` is found anywhere within `s` starting at character number `start` (where 0 is the first character), `false` otherwise. + +```ocaml + includes ~search:"gram" "programmer" = true;; + includes ~search:"er" "programmer" = true;; + includes ~search:"pro" "programmer" = true;; + includes ~search:"xyz" "programmer" = false;; + includes ~search:"gram" ~start:1 "programmer" = true;; + includes ~search:"gram" ~start:4 "programmer" = false;; + includes ~search:{js|한|js} ~start:1 {js|대한민국|js} = true;; +``` +``` +val indexOf : search:t -> ?start:int -> t -> int +``` +`indexOf ~search ?start s` returns the position at which `search` was found within `s` starting at character position `start`, or `-1` if `search` is not found in that portion of `s`. The return value is relative to the beginning of the string, no matter where the search started from. + +```ocaml + indexOf ~search:"ok" "bookseller" = 2;; + indexOf ~search:"sell" "bookseller" = 4;; + indexOf ~search:"ee" "beekeeper" = 1;; + indexOf ~search:"xyz" "bookseller" = -1;; + indexOf ~search:"ok" ~start:1 "bookseller" = 2;; + indexOf ~search:"sell" ~start:2 "bookseller" = 4;; + indexOf ~search:"sell" ~start:5 "bookseller" = -1;; +``` +``` +val lastIndexOf : search:t -> ?start:int -> t -> int +``` +`lastIndexOf ~search ~start s` returns the position of the *last* occurrence of `searchValue` within `s`, searching backwards from the given `start` position. Returns `-1` if `searchValue` is not in `s`. The return value is always relative to the beginning of the string. + +```ocaml + lastIndexOf ~search:"ok" "bookseller" = 2;; + lastIndexOf ~search:"ee" "beekeeper" = 4;; + lastIndexOf ~search:"xyz" "abcdefg" = -1;; + lastIndexOf ~search:"ok" ~start:6 "bookseller" = 2;; + lastIndexOf ~search:"ee" ~start:8 "beekeeper" = 4;; + lastIndexOf ~search:"ee" ~start:3 "beekeeper" = 1;; + lastIndexOf ~search:"xyz" ~start:4 "abcdefg" = -1;; +``` +``` +val localeCompare : other:t -> t -> float +``` +`localeCompare ~other:comparison reference` returns: + +- a negative value if `reference` comes before `comparison` in sort order +- zero if `reference` and `comparison` have the same sort order +- a positive value if `reference` comes after `comparison` in sort order +```ocaml + (localeCompare ~other:"ant" "zebra") > 0.0;; + (localeCompare ~other:"zebra" "ant") < 0.0;; + (localeCompare ~other:"cat" "cat") = 0.0;; + (localeCompare ~other:"cat" "CAT") > 0.0;; +``` +``` +val match_ : regexp:Js.re -> t -> t option array option +``` +`match ~regexp str` matches a string against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the `g` modifier, if there is a match, the return value is `Some array` where the array contains: + +- The entire matched string +- Any capture groups if the `regexp` had parentheses +For regular expressions with the `g` modifier, a matched expression returns `Some array` with all the matched substrings and no capture groups. + +```ocaml + match "The better bats" ~regexp:[%re "/b[aeiou]t/"] = Some [|"bet"|] + match "The better bats" ~regexp:[%re "/b[aeiou]t/g"] = Some [|"bet";"bat"|] + match "Today is 2018-04-05." ~regexp:[%re "/(\\d+)-(\\d+)-(\\d+)/"] = Some [|"2018-04-05"; "2018"; "04"; "05"|] + match "The large container." ~regexp:[%re "/b[aeiou]g/"] = None +``` +``` +val normalize : ?form:[ `NFC | `NFD | `NFKC | `NFKD ] -> t -> t +``` +`normalize ~form str` returns the normalized Unicode string using the specified form of normalization, which may be one of: + +- `` `NFC `` — Normalization Form Canonical Composition. +- `` `NFD `` — Normalization Form Canonical Decomposition. +- `` `NFKC `` — Normalization Form Compatibility Composition. +- `` `NFKD `` — Normalization Form Compatibility Decomposition. +If `form` is omitted, `` `NFC `` is used. + +Consider the character `ã`, which can be represented as the single codepoint `\u00e3` or the combination of a lower case letter A `\u0061` and a combining tilde `\u0303`. Normalization ensures that both can be stored in an equivalent binary representation. + +see [https://www.unicode.org/reports/tr15/tr15-45.html](https://www.unicode.org/reports/tr15/tr15-45.html) Unicode technical report for details +``` +val repeat : count:int -> t -> t +``` +`repeat ~count s` returns a string that consists of `count` repetitions of `s`. Raises `RangeError` if `n` is negative. + +```ocaml + repeat ~count:3 "ha" = "hahaha" + repeat ~count:0 "empty" = "" +``` +``` +val replace : search:t -> replacement:t -> t -> t +``` +`replace ~search ~replacement string` returns a new string which is identical to `string` except with the first matching instance of `search` replaced by `replacement`. + +`search` is treated as a verbatim string to match, not a regular expression. + +```ocaml + replace ~search:"old" ~replacement:"new" "old string" = "new string" + replace ~search:"the" ~replacement:"this" "the cat and the dog" = "this cat and the dog" +``` +``` +val replaceByRe : regexp:Js.re -> replacement:t -> t -> t +``` +`replaceByRe ~regexp ~replacement string` returns a new string where occurrences matching `regexp` have been replaced by `replacement`. + +```ocaml + replaceByRe ~regexp:[%re "/[aeiou]/g"] ~replacement:"x" "vowels be gone" = "vxwxls bx gxnx" + replaceByRe ~regexp:[%re "/(\\w+) (\\w+)/"] ~replacement:"$2, $1" "Juan Fulano" = "Fulano, Juan" +``` +``` +val unsafeReplaceBy0 : regexp:Js.re -> f:(t -> int -> t -> t) -> t -> t +``` +`unsafeReplaceBy0 ~regexp ~f s` returns a new string with some or all matches of a pattern with no capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the offset at which the match begins, and the whole string being matched + +```ocaml +let str = "beautiful vowels" +let re = [%re "/[aeiou]/g"] +let matchFn matchPart offset wholeString = Js.String.toUpperCase matchPart + +let replaced = Js.String.unsafeReplaceBy0 ~regexp:re ~f:matchFn str + +let () = Js.log replaced (* prints "bEAUtifUl vOwEls" *) +``` +@see \ MDN + +``` +val unsafeReplaceBy1 : regexp:Js.re -> f:(t -> t -> int -> t -> t) -> t -> t +``` +`unsafeReplaceBy1 ~regexp ~f s` returns a new string with some or all matches of a pattern with one set of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. + +```ocaml +let str = "increment 23" +let re = [%re "/increment (\\d+)/g"] +let matchFn matchPart p1 offset wholeString = + wholeString ^ " is " ^ (string_of_int ((int_of_string p1) + 1)) + +let replaced = Js.String.unsafeReplaceBy1 ~regexp:re ~f:matchFn str + +let () = Js.log replaced (* prints "increment 23 is 24" *) +``` +@see \ MDN + +``` +val unsafeReplaceBy2 : + regexp:Js.re -> + f:(t -> t -> t -> int -> t -> t) -> + t -> + t +``` +`unsafeReplaceBy2 ~regexp ~f s` returns a new string with some or all matches of a pattern with two sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. + +```ocaml +let str = "7 times 6" +let re = [%re "/(\\d+) times (\\d+)/"] +let matchFn matchPart p1 p2 offset wholeString = + string_of_int ((int_of_string p1) * (int_of_string p2)) + +let replaced = Js.String.unsafeReplaceBy2 ~regexp:re ~f:matchFn str + +let () = Js.log replaced (* prints "42" *) +``` +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN +``` +val unsafeReplaceBy3 : + regexp:Js.re -> + f:(t -> t -> t -> t -> int -> t -> t) -> + t -> + t +``` +`unsafeReplaceBy3 ~regexp ~f s` returns a new string with some or all matches of a pattern with three sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN +``` +val search : regexp:Js.re -> t -> int +``` +`search ~regexp str` returns the starting position of the first match of `regexp` in the given `str`, or \-1 if there is no match. + +```ocaml +search ~regexp:[%re "/\\d+/"] "testing 1 2 3" = 8;; +search ~regexp:[%re "/\\d+/"] "no numbers" = -1;; +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`slice ?start ?end str` returns the substring of `str` starting at character `start` up to but not including `end` + +If either `start` or `end` is negative, then it is evaluated as `length str - start` (or `length str - end`). + +If `end` is greater than the length of `str`, then it is treated as `length str`. + +If `start` is greater than `end`, `slice` returns the empty string. + +```ocaml + slice ~start:2 ~end_:5 "abcdefg" = "cde";; + slice ~start:2 ~end_:9 "abcdefg" = "cdefg";; + slice ~start:(-4) ~end_:(-2) "abcdefg" = "de";; + slice ~start:5 ~end_:1 "abcdefg" = "";; +``` +``` +val split : ?sep:t -> ?limit:int -> t -> t array +``` +`split ?sep ?limit str` splits the given `str` at every occurrence of `sep` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. + +```ocaml + split ~sep:"/" ~limit: 3 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"|];; + split ~sep:"/" ~limit: 0 "ant/bee/cat/dog/elk" = [| |];; + split ~sep:"/" ~limit: 9 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"; "dog"; "elk"|];; +``` +``` +val splitByRe : regexp:Js.re -> ?limit:int -> t -> t option array +``` +`splitByRe str ~regexp ?limit ()` splits the given `str` at every occurrence of `regexp` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. + +```ocaml + splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:3 "one: two: three: four" = [|"one"; "two"; "three"|];; + splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:0 "one: two: three: four" = [| |];; + splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:8 "one: two: three: four" = [|"one"; "two"; "three"; "four"|];; +``` +; + +``` +val startsWith : prefix:t -> ?start:int -> t -> bool +``` +`startsWith ~prefix ?start str` returns `true` if the `str` starts with `prefix` starting at position `start`, `false` otherwise. If `start` is negative, the search starts at the beginning of `str`. + +```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;; +``` +``` +val substr : ?start:int -> ?len:int -> t -> t +``` +`substr ?start ?len str` returns the substring of `str` of length `len` starting at position `start`. + +If `start` is less than zero, the starting position is the length of `str` + +- `start`. +If `start` is greater than or equal to the length of `str`, returns the empty string. + +If `len` is less than or equal to zero, returns the empty string. + +```ocaml + substr ~start:3 ~len:4 "abcdefghij" = "defghij" + substr ~start:(-3) ~len:4 "abcdefghij" = "hij" + substr ~start:12 ~len:2 "abcdefghij" = "" +``` +deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/substr\#sect1 +``` +val substring : ?start:int -> ?end_:int -> t -> t +``` +`substring ~start ~end_ str` returns characters `start` up to but not including `end_` from `str`. + +If `start` is less than zero, it is treated as zero. + +If `end_` is zero or negative, the empty string is returned. + +If `start` is greater than `end_`, the start and finish points are swapped. + +```ocaml + substring ~start:3 ~end_:6 "playground" = "ygr";; + substring ~start:6 ~end_:3 "playground" = "ygr";; + substring ~start:4 ~end_:12 "playground" = "ground";; +``` +``` +val toLowerCase : t -> t +``` +`toLowerCase str` converts `str` to lower case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can give different results depending upon context, for example with the Greek letter sigma, which has two different lower case forms when it is the last character in a string or not. + +```ocaml + toLowerCase "ABC" = "abc";; + toLowerCase {js|ΣΠ|js} = {js|σπ|js};; + toLowerCase {js|ΠΣ|js} = {js|πς|js};; +``` +``` +val toLocaleLowerCase : t -> t +``` +`toLocaleLowerCase str` converts `str` to lower case using the current locale + +``` +val toUpperCase : t -> t +``` +`toUpperCase str` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can expand the number of letters in the result; for example the German `ß` capitalizes to two `S`es in a row. + +```ocaml + toUpperCase "abc" = "ABC";; + toUpperCase {js|Straße|js} = {js|STRASSE|js};; + toUpperCase {js|πς|js} = {js|ΠΣ|js};; +``` +``` +val toLocaleUpperCase : t -> t +``` +`toLocaleUpperCase str` converts `str` to upper case using the current locale + +``` +val trim : t -> t +``` +`trim str` returns a string that is `str` with whitespace stripped from both ends. Internal whitespace is not removed. + +```ocaml + trim " abc def " = "abc def" + trim "\n\r\t abc def \n\n\t\r " = "abc def" +``` +``` +val anchor : name:t -> t -> t +``` +`anchor ~name:anchorName anchorText` creates a string with an HTML `` element with `name` attribute of `anchorName` and `anchorText` as its content. + +```ocaml + anchor ~name:"page1" "Page One" = "Page One" +``` +deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/anchor\#sect1 +``` +val link : href:t -> t -> t +``` +`link ~href:urlText linkText` creates a string with an HTML `` element with `href` attribute of `urlText` and `linkText` as its content. + +```ocaml + link ~href:"page2.html" "Go to page two" = "Go to page two" +``` +deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/link\#sect1 +``` +val unsafeToArrayLike : t -> t Js.array_like +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-ArrayBuffer.md b/docs/api/re/melange/Js-Typed_array-ArrayBuffer.md new file mode 100644 index 000000000..3331025db --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-ArrayBuffer.md @@ -0,0 +1,20 @@ + +# Module `Typed_array.ArrayBuffer` + +The underlying buffer that the typed arrays provide views of + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) MDN +``` +type t = Js.arrayBuffer +``` +``` +val make : int -> t +``` +takes length. initializes elements to 0 + +``` +val byteLength : t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> Js.arrayBuffer +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-DataView.md b/docs/api/re/melange/Js-Typed_array-DataView.md new file mode 100644 index 000000000..1d1ad1f0f --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-DataView.md @@ -0,0 +1,108 @@ + +# Module `Typed_array.DataView` + +The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) MDN +``` +type t +``` +``` +val make : Js.arrayBuffer -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val getInt8 : int -> t -> int +``` +``` +val getUint8 : int -> t -> int +``` +``` +val getInt16 : int -> t -> int +``` +``` +val getInt16LittleEndian : int -> t -> int +``` +``` +val getUint16 : int -> t -> int +``` +``` +val getUint16LittleEndian : int -> t -> int +``` +``` +val getInt32 : int -> t -> int +``` +``` +val getInt32LittleEndian : int -> t -> int +``` +``` +val getUint32 : int -> t -> int +``` +``` +val getUint32LittleEndian : int -> t -> int +``` +``` +val getFloat32 : int -> t -> float +``` +``` +val getFloat32LittleEndian : int -> t -> float +``` +``` +val getFloat64 : int -> t -> float +``` +``` +val getFloat64LittleEndian : int -> t -> float +``` +``` +val setInt8 : int -> int -> t -> unit +``` +``` +val setUint8 : int -> int -> t -> unit +``` +``` +val setInt16 : int -> int -> t -> unit +``` +``` +val setInt16LittleEndian : int -> int -> t -> unit +``` +``` +val setUint16 : int -> int -> t -> unit +``` +``` +val setUint16LittleEndian : int -> int -> t -> unit +``` +``` +val setInt32 : int -> int -> t -> unit +``` +``` +val setInt32LittleEndian : int -> int -> t -> unit +``` +``` +val setUint32 : int -> int -> t -> unit +``` +``` +val setUint32LittleEndian : int -> int -> t -> unit +``` +``` +val setFloat32 : int -> float -> t -> unit +``` +``` +val setFloat32LittleEndian : int -> float -> t -> unit +``` +``` +val setFloat64 : int -> float -> t -> unit +``` +``` +val setFloat64LittleEndian : int -> float -> t -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Float32Array.md b/docs/api/re/melange/Js-Typed_array-Float32Array.md new file mode 100644 index 000000000..77ea7f873 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Float32Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Float32Array` + +``` +type elt = float +``` +``` +type 'a typed_array = Js.float32Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Float64Array.md b/docs/api/re/melange/Js-Typed_array-Float64Array.md new file mode 100644 index 000000000..47a2c9062 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Float64Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Float64Array` + +``` +type elt = float +``` +``` +type 'a typed_array = Js.float64Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Int16Array.md b/docs/api/re/melange/Js-Typed_array-Int16Array.md new file mode 100644 index 000000000..efd85abba --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Int16Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Int16Array` + +``` +type elt = int +``` +``` +type 'a typed_array = Js.int16Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Int32Array.md b/docs/api/re/melange/Js-Typed_array-Int32Array.md new file mode 100644 index 000000000..459de0957 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Int32Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Int32Array` + +``` +type elt = int32 +``` +``` +type 'a typed_array = Js.int32Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Int8Array.md b/docs/api/re/melange/Js-Typed_array-Int8Array.md new file mode 100644 index 000000000..fd129f858 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Int8Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Int8Array` + +``` +type elt = int +``` +``` +type 'a typed_array = Js.int8Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint16Array.md b/docs/api/re/melange/Js-Typed_array-Uint16Array.md new file mode 100644 index 000000000..44568a6d6 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Uint16Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Uint16Array` + +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint16Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint32Array.md b/docs/api/re/melange/Js-Typed_array-Uint32Array.md new file mode 100644 index 000000000..2faa8f753 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Uint32Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Uint32Array` + +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint32Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint8Array.md b/docs/api/re/melange/Js-Typed_array-Uint8Array.md new file mode 100644 index 000000000..e3a3890d2 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Uint8Array.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Uint8Array` + +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint8Array +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md b/docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md new file mode 100644 index 000000000..27966ace2 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md @@ -0,0 +1,165 @@ + +# Module `Typed_array.Uint8ClampedArray` + +``` +type elt = int +``` +``` +type 'a typed_array = Js.uint8ClampedArray +``` +``` +type t = elt typed_array +``` +``` +val unsafe_get : t -> int -> elt +``` +``` +val unsafe_set : t -> int -> elt -> unit +``` +``` +val buffer : t -> Js.arrayBuffer +``` +``` +val byteLength : t -> int +``` +``` +val byteOffset : t -> int +``` +``` +val setArray : elt array -> t -> unit +``` +``` +val setArrayOffset : elt array -> int -> t -> unit +``` +``` +val length : t -> int +``` +``` +val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t +``` +``` +val fill : elt -> ?start:int -> ?end_:int -> t -> t +``` +``` +val reverseInPlace : t -> t +``` +``` +val sortInPlace : t -> t +``` +``` +val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t +``` +``` +val includes : value:elt -> t -> bool +``` +``` +val indexOf : value:elt -> ?start:int -> t -> int +``` +``` +val join : ?sep:string -> t -> string +``` +``` +val lastIndexOf : value:elt -> t -> int +``` +``` +val lastIndexOfFrom : value:elt -> from:int -> t -> int +``` +``` +val slice : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val copy : t -> t +``` +``` +val subarray : ?start:int -> ?end_:int -> t -> t +``` +`start` is inclusive, `end_` exclusive + +``` +val toString : t -> string +``` +``` +val toLocaleString : t -> string +``` +``` +val entries : t -> (int * elt) Js.iterator +``` +``` +val every : f:(elt -> bool) -> t -> bool +``` +``` +val everyi : f:(elt -> int -> bool) -> t -> bool +``` +``` +val filter : f:(elt -> bool) -> t -> t +``` +``` +val filteri : f:(elt -> int -> bool) -> t -> t +``` +``` +val find : f:(elt -> bool) -> t -> elt Js.undefined +``` +``` +val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined +``` +``` +val findIndex : f:(elt -> bool) -> t -> int +``` +``` +val findIndexi : f:(elt -> int -> bool) -> t -> int +``` +``` +val forEach : f:(elt -> unit) -> t -> unit +``` +``` +val forEachi : f:(elt -> int -> unit) -> t -> unit +``` +``` +val keys : t -> int Js.iterator +``` +``` +val map : f:(elt -> 'b) -> t -> 'b typed_array +``` +``` +val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array +``` +``` +val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b +``` +``` +val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b +``` +``` +val some : f:(elt -> bool) -> t -> bool +``` +``` +val somei : f:(elt -> int -> bool) -> t -> bool +``` +``` +val _BYTES_PER_ELEMENT : int +``` +``` +val make : elt array -> t +``` +``` +val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t +``` +raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception +parameter offset is in bytes, length in elements +``` +val fromLength : int -> t +``` +``` +val from : elt Js.array_like -> t +``` +``` +val values : t -> elt Js.iterator +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array.md b/docs/api/re/melange/Js-Typed_array.md new file mode 100644 index 000000000..4716bb636 --- /dev/null +++ b/docs/api/re/melange/Js-Typed_array.md @@ -0,0 +1,44 @@ + +# Module `Js.Typed_array` + +Bindings to the functions in `TypedArray.prototype` + +JavaScript Typed Array API + +see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) MDN +``` +module ArrayBuffer : sig ... end +``` +The underlying buffer that the typed arrays provide views of + +``` +module Int8Array : sig ... end +``` +``` +module Uint8Array : sig ... end +``` +``` +module Uint8ClampedArray : sig ... end +``` +``` +module Int16Array : sig ... end +``` +``` +module Uint16Array : sig ... end +``` +``` +module Int32Array : sig ... end +``` +``` +module Uint32Array : sig ... end +``` +``` +module Float32Array : sig ... end +``` +``` +module Float64Array : sig ... end +``` +``` +module DataView : sig ... end +``` +The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. diff --git a/docs/api/re/melange/Js-Types.md b/docs/api/re/melange/Js-Types.md new file mode 100644 index 000000000..d9e8e32ab --- /dev/null +++ b/docs/api/re/melange/Js-Types.md @@ -0,0 +1,109 @@ + +# Module `Js.Types` + +Utility functions for runtime reflection on JS types + +``` +type symbol +``` +Js symbol type only available in ES6 + +``` +type bigint_val +``` +Js bigint type only available in ES2020 + +``` +type obj_val +``` +``` +type undefined_val +``` +This type has only one value `undefined` + +``` +type null_val +``` +This type has only one value `null` + +``` +type function_val +``` +``` +type _ t = +``` +``` +| Undefined : undefined_val t +``` +``` +| Null : null_val t +``` +``` +| Boolean : bool t +``` +``` +| Number : float t +``` +``` +| String : string t +``` +``` +| Function : function_val t +``` +``` +| Object : obj_val t +``` +``` +| Symbol : symbol t +``` +``` +| BigInt : bigint_val t +``` +``` + +``` +``` +val test : 'a -> 'b t -> bool +``` +```ocaml +test "x" String = true +``` +``` +type tagged_t = +``` +``` +| JSFalse +``` +``` +| JSTrue +``` +``` +| JSNull +``` +``` +| JSUndefined +``` +``` +| JSNumber of float +``` +``` +| JSString of string +``` +``` +| JSFunction of function_val +``` +``` +| JSObject of obj_val +``` +``` +| JSSymbol of symbol +``` +``` +| JSBigInt of bigint_val +``` +``` + +``` +``` +val classify : 'a -> tagged_t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Undefined.md b/docs/api/re/melange/Js-Undefined.md new file mode 100644 index 000000000..749c64f50 --- /dev/null +++ b/docs/api/re/melange/Js-Undefined.md @@ -0,0 +1,79 @@ + +# Module `Js.Undefined` + +Utility functions on [`undefined`](./Js.md#type-undefined) + +Provides functionality for dealing with the `'a Js.undefined` type + +``` +type +'a t = 'a Js.undefined +``` +Local alias for `'a Js.undefined` + +``` +val return : 'a -> 'a t +``` +Constructs a value of `'a Js.undefined` containing a value of `'a` + +``` +val testAny : 'a -> bool +``` +Returns `true` if the given value is `empty` (`undefined`) + +``` +val empty : 'a t +``` +The empty value, `undefined` + +``` +val getUnsafe : 'a t -> 'a +``` +``` +val getExn : 'a t -> 'a +``` +``` +val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t +``` +``` +val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t +``` +Bind the contained value using the given function + +If `'a Js.undefined` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.undefined` + +```ocaml +let maybeGreetWorld (maybeGreeting: string Js.undefined) = + Js.Undefined.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") +``` +``` +val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit +``` +Iterates over the contained value with the given function + +If `'a Js.undefined` contains a value, that value is unwrapped and applied to the given function. + +```ocaml +let maybeSay (maybeMessage: string Js.undefined) = + Js.Undefined.iter maybeMessage ~f:(fun message -> Js.log message) +``` +``` +val fromOption : 'a option -> 'a t +``` +Maps `'a option` to `'a Js.undefined` + + + +
Some a -> return a +
None -> empty +
+ +``` +val toOption : 'a t -> 'a option +``` +Maps `'a Js.undefined` to `'a option` + + + +
return a -> Some a +
empty -> None +
diff --git a/docs/api/re/melange/Js-WeakMap.md b/docs/api/re/melange/Js-WeakMap.md new file mode 100644 index 000000000..a997042d8 --- /dev/null +++ b/docs/api/re/melange/Js-WeakMap.md @@ -0,0 +1,25 @@ + +# Module `Js.WeakMap` + +Bindings to functions in `WeakMap` + +ES6 WeakMap API + +``` +type ('k, 'v) t +``` +``` +val make : unit -> ('k, 'v) t +``` +``` +val get : key:'k Js.dict -> ('k, 'v) t -> 'v option +``` +``` +val has : key:'k Js.dict -> ('k, 'v) t -> bool +``` +``` +val set : key:'k Js.dict -> value:'v -> ('k, 'v) t -> ('k, 'v) t +``` +``` +val delete : key:'k Js.dict -> ('k, 'v) t -> bool +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-WeakSet.md b/docs/api/re/melange/Js-WeakSet.md new file mode 100644 index 000000000..a7f07d2ea --- /dev/null +++ b/docs/api/re/melange/Js-WeakSet.md @@ -0,0 +1,22 @@ + +# Module `Js.WeakSet` + +Bindings to functions in `WeakSet` + +ES6 WeakSet API + +``` +type 'a t +``` +``` +val make : unit -> 'a t +``` +``` +val add : value:'a Js.dict -> 'a t -> 'a t +``` +``` +val delete : value:'a Js.dict -> 'a t -> bool +``` +``` +val has : value:'a Js.dict -> 'a t -> bool +``` \ No newline at end of file diff --git a/docs/api/re/melange/Js.md b/docs/api/re/melange/Js.md new file mode 100644 index 000000000..06b1fd244 --- /dev/null +++ b/docs/api/re/melange/Js.md @@ -0,0 +1,320 @@ + +# Module `Js` + +``` +type +'a null +``` +A value of this type can be either `null` or `'a`. This type is the same as type `t` in [`Null`](./Js-Null.md) + +``` +type +'a undefined +``` +A value of this type can be either `undefined` or `'a`. This type is the same as type `t` in [`Undefined`](./Js-Undefined.md) + +``` +type +'a nullable +``` +A value of this type can be `undefined`, `null` or `'a`. This type is the same as type `t` n [`Nullable`](./Js-Nullable.md) + +``` +type re +``` +The type for JavaScript `RegExp` + +``` +type 'a dict +``` +The type for a simple key-value dictionary abstraction over native JavaScript objects + +``` +type 'a iterator +``` +The type for JavaScript iterators + +``` +type 'a array_like +``` +The type for array-like objects in JavaScript + +``` +type bigint +``` +The type for JavaScript BigInt + +``` +type +'a promise +``` +The type for JavaScript Promise + +``` +type blob +``` +The type for JavaScript [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + +``` +type file +``` +The type for JavaScript [File](https://developer.mozilla.org/en-US/docs/Web/API/File) + +``` +type arrayBuffer +``` +``` +type int8Array +``` +``` +type uint8Array +``` +``` +type uint8ClampedArray +``` +``` +type int16Array +``` +``` +type uint16Array +``` +``` +type int32Array +``` +``` +type uint32Array +``` +``` +type float32Array +``` +``` +type float64Array +``` +``` +val toOption : 'a nullable -> 'a option +``` +``` +val undefinedToOption : 'a undefined -> 'a option +``` +``` +val nullToOption : 'a null -> 'a option +``` +``` +val isNullable : 'a nullable -> bool +``` +``` +val import : 'a -> 'a promise +``` +TODO(anmonteiro): document + +``` +val testAny : 'a -> bool +``` +The same as [`isNullable`](./#val-isNullable) except that it is more permissive on the types of input + +``` +val null : 'a null +``` +The same as `empty` in [`Js.Null`](./Js-Null.md) will be compiled as `null` + +``` +val undefined : 'a undefined +``` +The same as `empty` [`Js.Undefined`](./Js-Undefined.md) will be compiled as `undefined` + +``` +val typeof : 'a -> string +``` +`typeof x` will be compiled as `typeof x` in JS Please consider functions in [`Types`](./Js-Types.md) for a type safe way of reflection + +``` +val log : 'a -> unit +``` +A convenience function to log everything + +``` +val log2 : 'a -> 'b -> unit +``` +``` +val log3 : 'a -> 'b -> 'c -> unit +``` +``` +val log4 : 'a -> 'b -> 'c -> 'd -> unit +``` +``` +val logMany : 'a array -> unit +``` +A convenience function to log more than 4 arguments + +``` +val eqNull : 'a -> 'a null -> bool +``` +``` +val eqUndefined : 'a -> 'a undefined -> bool +``` +``` +val eqNullable : 'a -> 'a nullable -> bool +``` + +##### Operators + +``` +val unsafe_lt : 'a -> 'a -> bool +``` +`unsafe_lt a b` will be compiled as `a < b`. It is marked as unsafe, since it is impossible to give a proper semantics for comparision which applies to any type + +``` +val unsafe_le : 'a -> 'a -> bool +``` +`unsafe_le a b` will be compiled as `a <= b`. See also [`unsafe_lt`](./#val-unsafe_lt) + +``` +val unsafe_gt : 'a -> 'a -> bool +``` +`unsafe_gt a b` will be compiled as `a > b`. See also [`unsafe_lt`](./#val-unsafe_lt) + +``` +val unsafe_ge : 'a -> 'a -> bool +``` +`unsafe_ge a b` will be compiled as `a >= b`. See also [`unsafe_lt`](./#val-unsafe_lt) + +Types for JS objects + +``` +type 'a t +``` +This used to be mark a Js object type. + +``` +module Exn : sig ... end +``` +Utilities for dealing with Js exceptions + +``` +module String : sig ... end +``` +Bindings to the functions in `String.prototype` + +``` +module Null : sig ... end +``` +Utility functions on [`null`](./#type-null) + +``` +module Undefined : sig ... end +``` +Utility functions on [`undefined`](./#type-undefined) + +``` +module Nullable : sig ... end +``` +Utility functions on [`nullable`](./#type-nullable) + +``` +module Array : sig ... end +``` +Bindings to the functions in `Array.prototype` + +``` +module Re : sig ... end +``` +Bindings to the functions in `RegExp.prototype` + +``` +module Promise : sig ... end +``` +Bindings to JS `Promise` functions + +``` +module Date : sig ... end +``` +Bindings to the functions in JS's `Date.prototype` + +``` +module Dict : sig ... end +``` +Utility functions to treat a JS object as a dictionary + +``` +module Global : sig ... end +``` +Bindings to functions in the JS global namespace + +``` +module Json : sig ... end +``` +Utility functions to manipulate JSON values + +``` +module Math : sig ... end +``` +Bindings to the functions in the `Math` object + +``` +module Obj : sig ... end +``` +Utility functions on \`Js.t\` JS objects + +``` +module Typed_array : sig ... end +``` +Bindings to the functions in `TypedArray.prototype` + +``` +module Types : sig ... end +``` +Utility functions for runtime reflection on JS types + +``` +module Float : sig ... end +``` +Bindings to functions in JavaScript's `Number` that deal with floats + +``` +module Int : sig ... end +``` +Bindings to functions in JavaScript's `Number` that deal with ints + +``` +module Bigint : sig ... end +``` +Bindings to functions in JavaScript's `BigInt` + +``` +module Console : sig ... end +``` +``` +module Set : sig ... end +``` +Bindings to functions in `Set` + +``` +module WeakSet : sig ... end +``` +Bindings to functions in `WeakSet` + +``` +module Map : sig ... end +``` +Bindings to functions in `Map` + +``` +module WeakMap : sig ... end +``` +Bindings to functions in `WeakMap` + +``` +module Iterator : sig ... end +``` +Bindings to functions on `Iterator` + +``` +module Blob : sig ... end +``` +Bindings to Blob + +``` +module File : sig ... end +``` +Bindings to File + +``` +module FormData : sig ... end +``` +Bindings to FormData diff --git a/docs/api/re/melange/Node-Buffer.md b/docs/api/re/melange/Node-Buffer.md new file mode 100644 index 000000000..3488b30f6 --- /dev/null +++ b/docs/api/re/melange/Node-Buffer.md @@ -0,0 +1,56 @@ + +# Module `Node.Buffer` + +Node Buffer API + +``` +type t = Node.buffer +``` +``` +type encoding = [ +``` +``` +| `ascii +``` +``` +| `utf8 +``` +``` +| `utf16le +``` +``` +| `ucs2 +``` +``` +| `base64 +``` +``` +| `base64url +``` +``` +| `latin1 +``` +``` +| `binary +``` +``` +| `hex +``` +``` + ] +``` +``` +val isBuffer : 'a -> bool +``` +``` +val fromString : string -> t +``` +``` +val fromStringWithEncoding : string -> encoding:encoding -> t +``` +``` +val toString : ?encoding:encoding -> t -> string +``` +``` +val concat : t array -> t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Child_process.md b/docs/api/re/melange/Node-Child_process.md new file mode 100644 index 000000000..5a3630c8c --- /dev/null +++ b/docs/api/re/melange/Node-Child_process.md @@ -0,0 +1,30 @@ + +# Module `Node.Child_process` + +Node Child Process API + +``` +type option +``` +``` +val option : ?cwd:string -> ?encoding:string -> unit -> option +``` +``` +val execSync : string -> option -> string +``` +``` +type spawnResult +``` +``` +val spawnSync : string -> spawnResult +``` +``` +val readAs : + spawnResult -> + < pid : int + ; status : int Js.null + ; signal : string Js.null + ; stdout : Node.string_buffer Js.null + ; stderr : Node.string_buffer Js.null > + Js.t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Fs-Watch.md b/docs/api/re/melange/Node-Fs-Watch.md new file mode 100644 index 000000000..581d242fa --- /dev/null +++ b/docs/api/re/melange/Node-Fs-Watch.md @@ -0,0 +1,33 @@ + +# Module `Fs.Watch` + +``` +type t +``` +``` +type config +``` +``` +val config : + ?persistent:bool -> + ?recursive:bool -> + ?encoding:Js.String.t -> + unit -> + config +``` +``` +val watch : string -> ?config:config -> unit -> t +``` +there is no need to accept listener, since we return a `watcher` back it can register event listener there. Currently we introduce a type `string_buffer`, for the `filename`, it will be `Buffer` when the encoding is `` `utf8 ``. This is dependent type which can be tracked by GADT in some way, but to make things simple, let's just introduce an or type + +``` +val on : + t -> + f: + [ `change of (string -> Node.string_buffer -> unit) Js.Fn.arity2 + | `error of unit Js.Fn.arity0 ] -> + t +``` +``` +val close : t -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Fs.md b/docs/api/re/melange/Node-Fs.md new file mode 100644 index 000000000..b437a848f --- /dev/null +++ b/docs/api/re/melange/Node-Fs.md @@ -0,0 +1,110 @@ + +# Module `Node.Fs` + +Node FS API + +see [https://blogs.janestreet.com/a-and-a/](https://blogs.janestreet.com/a-and-a/) refernce documentation +``` +val readdirSync : string -> string array +``` +Most fs functions let you omit the callback argument. If you do, a default callback is used that rethrows errors. To get a trace to the original call site, set the \`NODE\_DEBUG\` environment variable. + +``` +val renameSync : string -> string -> unit +``` +``` +type fd = private int +``` +``` +type path = string +``` +The relative path to a filename can be used. Remember, however, that this path will be relative to `process.cwd()`. + +``` +module Watch : sig ... end +``` +``` +val ftruncateSync : fd -> int -> unit +``` +``` +val truncateSync : string -> int -> unit +``` +``` +val chownSync : string -> uid:int -> gid:int -> unit +``` +``` +val fchownSync : fd -> uid:int -> gid:int -> unit +``` +``` +val readlinkSync : string -> string +``` +``` +val unlinkSync : string -> unit +``` +``` +val rmdirSync : string -> unit +``` +``` +val openSync : + path -> + [ `Read + | `Read_write + | `Read_write_sync + | `Write + | `Write_fail_if_exists + | `Write_read + | `Write_read_fail_if_exists + | `Append + | `Append_fail_if_exists + | `Append_read + | `Append_read_fail_if_exists ] -> + unit +``` +``` +type encoding = [ +``` +``` +| `hex +``` +``` +| `utf8 +``` +``` +| `ascii +``` +``` +| `latin1 +``` +``` +| `base64 +``` +``` +| `ucs2 +``` +``` +| `base64 +``` +``` +| `binary +``` +``` +| `utf16le +``` +``` + ] +``` +``` +val readFileSync : string -> encoding -> string +``` +``` +val readFileAsUtf8Sync : string -> string +``` +``` +val existsSync : string -> bool +``` +``` +val writeFileSync : string -> string -> encoding -> unit +``` +``` +val writeFileAsUtf8Sync : string -> string -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Module.md b/docs/api/re/melange/Node-Module.md new file mode 100644 index 000000000..26dbe1439 --- /dev/null +++ b/docs/api/re/melange/Node-Module.md @@ -0,0 +1,8 @@ + +# Module `Node.Module` + +Node Module API + +``` +val module_ : < __cache : Node.node_module Js.Dict.t > Js.t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Path.md b/docs/api/re/melange/Node-Path.md new file mode 100644 index 000000000..0d7ebfd71 --- /dev/null +++ b/docs/api/re/melange/Node-Path.md @@ -0,0 +1,56 @@ + +# Module `Node.Path` + +Node Path API + +``` +val basename : string -> string +``` +``` +val basename_ext : string -> string -> string +``` +``` +val delimiter : string +``` +``` +val dirname : string -> string +``` +``` +val dirname_ext : string -> string -> string +``` +``` +type pathObject = + < dir : string + ; root : string + ; base : string + ; name : string + ; ext : string > + Js.t +``` +``` +val format : pathObject -> string +``` +``` +val isAbsolute : string -> bool +``` +``` +val join2 : string -> string -> string +``` +``` +val join : string array -> string +``` +``` +val normalize : string -> string +``` +``` +val parse : string -> pathObject +``` +``` +val relative : from:string -> to_:string -> unit -> string +``` +``` +val resolve : string -> string -> string +``` +``` +val sep : string +``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Process.md b/docs/api/re/melange/Node-Process.md new file mode 100644 index 000000000..f2714be7b --- /dev/null +++ b/docs/api/re/melange/Node-Process.md @@ -0,0 +1,38 @@ + +# Module `Node.Process` + +``` +type t = + < argv : string array + ; arch : string + ; abort : unit Js.OO.Meth.arity0 + ; chdir : (string -> unit) Js.OO.Meth.arity1 + ; cwd : string Js.OO.Meth.arity0 + ; disconnect : unit Js.OO.Meth.arity0 + ; platform : string + ; env : string Js.Dict.t > + Js.t +``` +``` +val process : t +``` +``` +val argv : string array +``` +``` +val exit : int -> 'a +``` +``` +val cwd : unit -> string +``` +``` +val uptime : t -> unit -> float +``` +The process.uptime() method returns the number of seconds the current Node.js process has been running.) + +``` +val putEnvVar : string -> string -> unit +``` +``` +val deleteEnvVar : string -> unit +``` \ No newline at end of file diff --git a/docs/api/re/melange/Node.md b/docs/api/re/melange/Node.md new file mode 100644 index 000000000..2730c44a9 --- /dev/null +++ b/docs/api/re/melange/Node.md @@ -0,0 +1,73 @@ + +# Module `Node` + +``` +type node_exports +``` +``` +type node_module = + < id : string + ; exports : node_exports + ; parent : node_module Js.nullable + ; filename : string + ; loaded : bool + ; children : node_module array + ; paths : string array > + Js.t +``` +``` +type node_require = + < main : node_module Js.undefined + ; resolve : (string -> string) Js.Fn.arity1 > + Js.t +``` +``` +type string_buffer +``` +``` +type buffer +``` +``` +type _ string_buffer_kind = +``` +``` +| String : string string_buffer_kind +``` +``` +| Buffer : buffer string_buffer_kind +``` +``` + +``` +``` +val test : string_buffer -> 't string_buffer_kind * 't +``` +We expect a good inliner will eliminate such boxing in the future + +``` +module Path : sig ... end +``` +Node Path API + +``` +module Fs : sig ... end +``` +Node FS API + +``` +module Process : sig ... end +``` +``` +module Module : sig ... end +``` +Node Module API + +``` +module Buffer : sig ... end +``` +Node Buffer API + +``` +module Child_process : sig ... end +``` +Node Child Process API diff --git a/docs/api/re/melange/Stdlib-Arg.md b/docs/api/re/melange/Stdlib-Arg.md new file mode 100644 index 000000000..9688b86ce --- /dev/null +++ b/docs/api/re/melange/Stdlib-Arg.md @@ -0,0 +1,261 @@ + +# Module `Stdlib.Arg` + +Parsing of command line arguments. + +This module provides a general mechanism for extracting options and arguments from the command line to the program. For example: + +```ocaml + let usage_msg = "append [-verbose] [] ... -o " + let verbose = ref false + let input_files = ref [] + let output_file = ref "" + + let anon_fun filename = + input_files := filename::!input_files + + let speclist = + [("-verbose", Arg.Set verbose, "Output debug information"); + ("-o", Arg.Set_string output_file, "Set output file name")] + + let () = + Arg.parse speclist anon_fun usage_msg; + (* Main functionality here *) +``` +Syntax of command lines: A keyword is a character string starting with a `-`. An option is a keyword alone or followed by an argument. The types of keywords are: `Unit`, `Bool`, `Set`, `Clear`, `String`, `Set_string`, `Int`, `Set_int`, `Float`, `Set_float`, `Tuple`, `Symbol`, `Rest`, `Rest_all` and `Expand`. + +`Unit`, `Set` and `Clear` keywords take no argument. + +A `Rest` or `Rest_all` keyword takes the remainder of the command line as arguments. (More explanations below.) + +Every other keyword takes the following word on the command line as argument. For compatibility with GNU getopt\_long, `keyword=arg` is also allowed. Arguments not preceded by a keyword are called anonymous arguments. + +Examples (`cmd` is assumed to be the command name): + +- `cmd -flag `(a unit option) +- `cmd -int 1 `(an int option with argument `1`) +- `cmd -string foobar `(a string option with argument `"foobar"`) +- `cmd -float 12.34 `(a float option with argument `12.34`) +- `cmd a b c `(three anonymous arguments: `"a"`, `"b"`, and `"c"`) +- `cmd a b -- c d `(two anonymous arguments and a rest option with two arguments) +`Rest` takes a function that is called repeatedly for each remaining command line argument. `Rest_all` takes a function that is called once, with the list of all remaining arguments. + +Note that if no arguments follow a `Rest` keyword then the function is not called at all whereas the function for a `Rest_all` keyword is called with an empty list. + +alert unsynchronized\_access The Arg module relies on a mutable global state, parsing functions should only be called from a single domain. +``` +type spec = +``` +``` +| Unit of unit -> unit +``` +Call the function with unit argument + +``` +| Bool of bool -> unit +``` +Call the function with a bool argument + +``` +| Set of bool ref +``` +Set the reference to true + +``` +| Clear of bool ref +``` +Set the reference to false + +``` +| String of string -> unit +``` +Call the function with a string argument + +``` +| Set_string of string ref +``` +Set the reference to the string argument + +``` +| Int of int -> unit +``` +Call the function with an int argument + +``` +| Set_int of int ref +``` +Set the reference to the int argument + +``` +| Float of float -> unit +``` +Call the function with a float argument + +``` +| Set_float of float ref +``` +Set the reference to the float argument + +``` +| Tuple of spec list +``` +Take several arguments according to the spec list + +``` +| Symbol of string list * string -> unit +``` +Take one of the symbols as argument and call the function with the symbol + +``` +| Rest of string -> unit +``` +Stop interpreting keywords and call the function with each remaining argument + +``` +| Rest_all of string list -> unit +``` +Stop interpreting keywords and call the function with all remaining arguments + +``` +| Expand of string -> string array +``` +If the remaining arguments to process are of the form `["-foo"; "arg"] @ rest` where "foo" is registered as `Expand f`, then the arguments `f "arg" @ rest` are processed. Only allowed in `parse_and_expand_argv_dynamic`. + +``` + +``` +The concrete type describing the behavior associated with a keyword. + +``` +type key = string +``` +``` +type doc = string +``` +``` +type usage_msg = string +``` +``` +type anon_fun = string -> unit +``` +``` +val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit +``` +`Arg.parse speclist anon_fun usage_msg` parses the command line. `speclist` is a list of triples `(key, spec, doc)`. `key` is the option keyword, it must start with a `'-'` character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon_fun` is called on anonymous arguments. The functions in `spec` and `anon_fun` are called in the same order as their arguments appear on the command line. + +If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows: + +- The reason for the error: unknown option, invalid or missing argument, etc. +- `usage_msg` +- The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list. +For the user to be able to specify anonymous arguments starting with a `-`, include for example `("-", String anon_fun, doc)` in `speclist`. + +By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage_msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`. + +``` +val parse_dynamic : + (key * spec * doc) list ref -> + anon_fun -> + usage_msg -> + unit +``` +Same as [`Arg.parse`](./#val-parse), except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form: + +- command subcommand `options` where the list of options depends on the value of the subcommand argument. +since 4.01 +``` +val parse_argv : + ?current:int ref -> + string array -> + (key * spec * doc) list -> + anon_fun -> + usage_msg -> + unit +``` +`Arg.parse_argv ~current args speclist anon_fun usage_msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or [`Arg.current`](./#val-current). You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises [`Arg.Bad`](./#exception-Bad) with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises [`Arg.Help`](./#exception-Help) with the help message as argument. + +``` +val parse_argv_dynamic : + ?current:int ref -> + string array -> + (key * spec * doc) list ref -> + anon_fun -> + string -> + unit +``` +Same as [`Arg.parse_argv`](./#val-parse_argv), except that the `speclist` argument is a reference and may be updated during the parsing. See [`Arg.parse_dynamic`](./#val-parse_dynamic). + +since 4.01 +``` +val parse_and_expand_argv_dynamic : + int ref -> + string array ref -> + (key * spec * doc) list ref -> + anon_fun -> + string -> + unit +``` +Same as [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic), except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic). + +since 4.05 +``` +val parse_expand : (key * spec * doc) list -> anon_fun -> usage_msg -> unit +``` +Same as [`Arg.parse`](./#val-parse), except that the `Expand` arguments are allowed and the [`current`](./#val-current) reference is not updated. + +since 4.05 +``` +exception Help of string +``` +Raised by `Arg.parse_argv` when the user asks for help. + +``` +exception Bad of string +``` +Functions in `spec` or `anon_fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by [`Arg.parse_argv`](./#val-parse_argv) in case of an error. + +``` +val usage : (key * spec * doc) list -> usage_msg -> unit +``` +`Arg.usage speclist usage_msg` prints to standard error an error message that includes the list of valid options. This is the same message that [`Arg.parse`](./#val-parse) prints in case of error. `speclist` and `usage_msg` are the same as for [`Arg.parse`](./#val-parse). + +``` +val usage_string : (key * spec * doc) list -> usage_msg -> string +``` +Returns the message that would have been printed by [`Arg.usage`](./#val-usage), if provided with the same parameters. + +``` +val align : ?limit:int -> (key * spec * doc) list -> (key * spec * doc) list +``` +Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line. + +parameter limit options with keyword and message longer than limit will not be used to compute the alignment. +``` +val current : int ref +``` +Position (in [`Sys.argv`](./Stdlib-Sys.md#val-argv)) of the argument being processed. You can change this value, e.g. to force [`Arg.parse`](./#val-parse) to skip some arguments. [`Arg.parse`](./#val-parse) uses the initial value of [`Arg.current`](./#val-current) as the index of argument 0 (the program name) and starts parsing arguments at the next element. + +``` +val read_arg : string -> string array +``` +`Arg.read_arg file` reads newline-terminated command line arguments from file `file`. + +since 4.05 +``` +val read_arg0 : string -> string array +``` +Identical to [`Arg.read_arg`](./#val-read_arg) but assumes null character terminated command line arguments. + +since 4.05 +``` +val write_arg : string -> string array -> unit +``` +`Arg.write_arg file args` writes the arguments `args` newline-terminated into the file `file`. If any of the arguments in `args` contains a newline, use [`Arg.write_arg0`](./#val-write_arg0) instead. + +since 4.05 +``` +val write_arg0 : string -> string array -> unit +``` +Identical to [`Arg.write_arg`](./#val-write_arg) but uses the null character for terminator instead of newline. + +since 4.05 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Array.md b/docs/api/re/melange/Stdlib-Array.md new file mode 100644 index 000000000..9653f6b3d --- /dev/null +++ b/docs/api/re/melange/Stdlib-Array.md @@ -0,0 +1,373 @@ + +# Module `Stdlib.Array` + +Array operations. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + +``` +type 'a t = 'a array +``` +An alias for the type of arrays. + +``` +val length : 'a array -> int +``` +Return the length (number of elements) of the given array. + +``` +val get : 'a array -> int -> 'a +``` +`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val set : 'a array -> int -> 'a -> unit +``` +`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. +``` +val make : int -> 'a -> 'a array +``` +`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val create_float : int -> float array +``` +`create_float n` returns a fresh float array of length `n`, with uninitialized data. + +since 4.03 +``` +val init : int -> (int -> 'a) -> 'a array +``` +`init n f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +``` +val make_matrix : int -> int -> 'a -> 'a array array +``` +`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val init_matrix : int -> int -> (int -> int -> 'a) -> 'a array array +``` +`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +since 5.2 +``` +val append : 'a array -> 'a array -> 'a array +``` +`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. +``` +val concat : 'a array list -> 'a array +``` +Same as [`append`](./#val-append), but concatenates a list of arrays. + +``` +val sub : 'a array -> int -> int -> 'a array +``` +`sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. +``` +val copy : 'a array -> 'a array +``` +`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. + +``` +val fill : 'a array -> int -> int -> 'a -> unit +``` +`fill a pos len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. +``` +val blit : 'a array -> int -> 'a array -> int -> int -> unit +``` +`blit src src_pos dst dst_pos len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. +``` +val to_list : 'a array -> 'a list +``` +`to_list a` returns the list of all the elements of `a`. + +``` +val of_list : 'a list -> 'a array +``` +`of_list l` returns a fresh array containing the elements of `l`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. + +## Iterators + +``` +val iter : ('a -> unit) -> 'a array -> unit +``` +`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. + +``` +val iteri : (int -> 'a -> unit) -> 'a array -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +``` +val map : ('a -> 'b) -> 'a array -> 'b array +``` +`map f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. + +``` +val map_inplace : ('a -> 'a) -> 'a array -> unit +``` +`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. + +since 5.1 +``` +val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +``` +val mapi_inplace : (int -> 'a -> 'a) -> 'a array -> unit +``` +Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +since 5.1 +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a array -> 'acc +``` +`fold_left f init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. + +``` +val fold_left_map : + ('acc -> 'a -> 'acc * 'b) -> + 'acc -> + 'a array -> + 'acc * 'b array +``` +`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. + +since 4.13 +``` +val fold_right : ('a -> 'acc -> 'acc) -> 'a array -> 'acc -> 'acc +``` +`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. + + +## Iterators on two arrays + +``` +val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit +``` +`iter2 f a b` applies function `f` to all the elements of `a` and `b`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) +``` +val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array +``` +`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) + +## Array scanning + +``` +val for_all : ('a -> bool) -> 'a array -> bool +``` +`for_all f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. + +since 4.03 +``` +val exists : ('a -> bool) -> 'a array -> bool +``` +`exists f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. + +since 4.03 +``` +val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val mem : 'a -> 'a array -> bool +``` +`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). + +since 4.03 +``` +val memq : 'a -> 'a array -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. + +since 4.03 +``` +val find_opt : ('a -> bool) -> 'a array -> 'a option +``` +`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. + +since 4.13 +``` +val find_index : ('a -> bool) -> 'a array -> int option +``` +`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + +It returns `None` if there is no such element. + +since 5.1 +``` +val find_map : ('a -> 'b option) -> 'a array -> 'b option +``` +`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. + +since 4.13 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a array -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 5.1 + +## Arrays of pairs + +``` +val split : ('a * 'b) array -> 'a array * 'b array +``` +`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. + +since 4.13 +``` +val combine : 'a array -> 'b array -> ('a * 'b) array +``` +`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. + +since 4.13 + +## Sorting and shuffling + +``` +val sort : ('a -> 'a -> int) -> 'a array -> unit +``` +Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. + +The current implementation uses Heap Sort. It runs in constant stack space. + +Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : + +- `cmp x y` \> 0 if and only if `cmp y x` \< 0 +- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 +When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : + +- `cmp a.(i) a.(j)` \>= 0 if i \>= j +``` +val stable_sort : ('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. + +The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). + +``` +val fast_sort : ('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + +``` +val shuffle : rand:(int -> int) -> 'a array -> unit +``` +`shuffle rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. + +`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). + +since 5.2 + +## Arrays and Sequences + +``` +val to_seq : 'a array -> 'a Seq.t +``` +Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. + +since 4.07 +``` +val to_seqi : 'a array -> (int * 'a) Seq.t +``` +Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. + +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a array +``` +Create an array from the generator + +since 4.07 + +## Arrays and concurrency safety + +Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + +### Atomicity + +Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. + +For example, consider the following program: + +```ocaml +let size = 100_000_000 +let a = Array.make size 1 +let d1 = Domain.spawn (fun () -> + Array.iteri (fun i x -> a.(i) <- x + 1) a +) +let d2 = Domain.spawn (fun () -> + Array.iteri (fun i x -> a.(i) <- 2 * x + 1) a +) +let () = Domain.join d1; Domain.join d2 +``` +After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +### Data races + +If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + +A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. + +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). + + +### Float arrays + +Float arrays have two supplementary caveats in the presence of data races. + +First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. + +For instance, at the end of + +```ocaml + let zeros = Array.make size 0. +let max_floats = Array.make size Float.max_float +let res = Array.copy zeros +let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) +let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) +let () = Domain.join d1; Domain.join d2 +``` +the `res` array might contain values that are neither `0.` nor `max_float`. + +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/re/melange/Stdlib-ArrayLabels.md b/docs/api/re/melange/Stdlib-ArrayLabels.md new file mode 100644 index 000000000..22c66dcff --- /dev/null +++ b/docs/api/re/melange/Stdlib-ArrayLabels.md @@ -0,0 +1,383 @@ + +# Module `Stdlib.ArrayLabels` + +Array operations. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + +``` +type 'a t = 'a array +``` +An alias for the type of arrays. + +``` +val length : 'a array -> int +``` +Return the length (number of elements) of the given array. + +``` +val get : 'a array -> int -> 'a +``` +`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val set : 'a array -> int -> 'a -> unit +``` +`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. +``` +val make : int -> 'a -> 'a array +``` +`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val create_float : int -> float array +``` +`create_float n` returns a fresh float array of length `n`, with uninitialized data. + +since 4.03 +``` +val init : int -> f:(int -> 'a) -> 'a array +``` +`init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +``` +val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array +``` +`make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. +``` +val init_matrix : + dimx:int -> + dimy:int -> + f:(int -> int -> 'a) -> + 'a array array +``` +`init_matrix ~dimx ~dimy ~f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. +since 5.2 +``` +val append : 'a array -> 'a array -> 'a array +``` +`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. +``` +val concat : 'a array list -> 'a array +``` +Same as [`append`](./#val-append), but concatenates a list of arrays. + +``` +val sub : 'a array -> pos:int -> len:int -> 'a array +``` +`sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. +``` +val copy : 'a array -> 'a array +``` +`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. + +``` +val fill : 'a array -> pos:int -> len:int -> 'a -> unit +``` +`fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. +``` +val blit : + src:'a array -> + src_pos:int -> + dst:'a array -> + dst_pos:int -> + len:int -> + unit +``` +`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. +``` +val to_list : 'a array -> 'a list +``` +`to_list a` returns the list of all the elements of `a`. + +``` +val of_list : 'a list -> 'a array +``` +`of_list l` returns a fresh array containing the elements of `l`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. + +## Iterators + +``` +val iter : f:('a -> unit) -> 'a array -> unit +``` +`iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. + +``` +val iteri : f:(int -> 'a -> unit) -> 'a array -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +``` +val map : f:('a -> 'b) -> 'a array -> 'b array +``` +`map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. + +``` +val map_inplace : f:('a -> 'a) -> 'a array -> unit +``` +`map_inplace ~f a` applies function `f` to all elements of `a`, and updates their values in place. + +since 5.1 +``` +val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +``` +val mapi_inplace : f:(int -> 'a -> 'a) -> 'a array -> unit +``` +Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +since 5.1 +``` +val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'acc +``` +`fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. + +``` +val fold_left_map : + f:('acc -> 'a -> 'acc * 'b) -> + init:'acc -> + 'a array -> + 'acc * 'b array +``` +`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. + +since 4.13 +``` +val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> init:'acc -> 'acc +``` +`fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. + + +## Iterators on two arrays + +``` +val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit +``` +`iter2 ~f a b` applies function `f` to all the elements of `a` and `b`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) +``` +val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array +``` +`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. +since 4.03 (4.05 in ArrayLabels) + +## Array scanning + +``` +val for_all : f:('a -> bool) -> 'a array -> bool +``` +`for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. + +since 4.03 +``` +val exists : f:('a -> bool) -> 'a array -> bool +``` +`exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. + +since 4.03 +``` +val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. +since 4.11 +``` +val mem : 'a -> set:'a array -> bool +``` +`mem a ~set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). + +since 4.03 +``` +val memq : 'a -> set:'a array -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. + +since 4.03 +``` +val find_opt : f:('a -> bool) -> 'a array -> 'a option +``` +`find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. + +since 4.13 +``` +val find_index : f:('a -> bool) -> 'a array -> int option +``` +`find_index ~f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + +It returns `None` if there is no such element. + +since 5.1 +``` +val find_map : f:('a -> 'b option) -> 'a array -> 'b option +``` +`find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. + +since 4.13 +``` +val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 5.1 + +## Arrays of pairs + +``` +val split : ('a * 'b) array -> 'a array * 'b array +``` +`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. + +since 4.13 +``` +val combine : 'a array -> 'b array -> ('a * 'b) array +``` +`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. + +since 4.13 + +## Sorting and shuffling + +``` +val sort : cmp:('a -> 'a -> int) -> 'a array -> unit +``` +Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. + +The current implementation uses Heap Sort. It runs in constant stack space. + +Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : + +- `cmp x y` \> 0 if and only if `cmp y x` \< 0 +- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 +When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : + +- `cmp a.(i) a.(j)` \>= 0 if i \>= j +``` +val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. + +The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). + +``` +val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + +``` +val shuffle : rand:(int -> int) -> 'a array -> unit +``` +`shuffle ~rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. + +`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). + +since 5.2 + +## Arrays and Sequences + +``` +val to_seq : 'a array -> 'a Seq.t +``` +Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. + +since 4.07 +``` +val to_seqi : 'a array -> (int * 'a) Seq.t +``` +Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. + +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a array +``` +Create an array from the generator + +since 4.07 + +## Arrays and concurrency safety + +Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + +### Atomicity + +Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. + +For example, consider the following program: + +```ocaml +let size = 100_000_000 +let a = ArrayLabels.make size 1 +let d1 = Domain.spawn (fun () -> + ArrayLabels.iteri ~f:(fun i x -> a.(i) <- x + 1) a +) +let d2 = Domain.spawn (fun () -> + ArrayLabels.iteri ~f:(fun i x -> a.(i) <- 2 * x + 1) a +) +let () = Domain.join d1; Domain.join d2 +``` +After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +### Data races + +If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + +A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. + +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). + + +### Float arrays + +Float arrays have two supplementary caveats in the presence of data races. + +First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. + +For instance, at the end of + +```ocaml + let zeros = Array.make size 0. +let max_floats = Array.make size Float.max_float +let res = Array.copy zeros +let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) +let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) +let () = Domain.join d1; Domain.join d2 +``` +the `res` array might contain values that are neither `0.` nor `max_float`. + +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/re/melange/Stdlib-Atomic.md b/docs/api/re/melange/Stdlib-Atomic.md new file mode 100644 index 000000000..1fc036d20 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Atomic.md @@ -0,0 +1,144 @@ + +# Module `Stdlib.Atomic` + +Atomic references. + +See [the examples](./#examples) below. See 'Memory model: The hard bits' chapter in the manual. + +since 4.12 +``` +type !'a t +``` +An atomic (mutable) reference to a value of type `'a`. + +``` +val make : 'a -> 'a t +``` +Create an atomic reference. + +Create an atomic reference that is alone on a cache line. It occupies 4-16x the memory of one allocated with `make v`. + +The primary purpose is to prevent false-sharing and the resulting performance degradation. When a CPU performs an atomic operation, it temporarily takes ownership of an entire cache line that contains the atomic reference. If multiple atomic references share the same cache line, modifying these disjoint memory regions simultaneously becomes impossible, which can create a bottleneck. Hence, as a general guideline, if an atomic reference is experiencing contention, assigning it its own cache line may enhance performance. + +``` +val get : 'a t -> 'a +``` +Get the current value of the atomic reference. + +``` +val set : 'a t -> 'a -> unit +``` +Set a new value for the atomic reference. + +``` +val exchange : 'a t -> 'a -> 'a +``` +Set a new value for the atomic reference, and return the current value. + +``` +val compare_and_set : 'a t -> 'a -> 'a -> bool +``` +`compare_and_set r seen v` sets the new value of `r` to `v` only if its current value is physically equal to `seen` \-- the comparison and the set occur atomically. Returns `true` if the comparison succeeded (so the set happened) and `false` otherwise. + +``` +val fetch_and_add : int t -> int -> int +``` +`fetch_and_add r n` atomically increments the value of `r` by `n`, and returns the current value (before the increment). + +``` +val incr : int t -> unit +``` +`incr r` atomically increments the value of `r` by `1`. + +``` +val decr : int t -> unit +``` +`decr r` atomically decrements the value of `r` by `1`. + + +## Examples + + +### Basic Thread Coordination + +A basic use case is to have global counters that are updated in a thread-safe way, for example to keep some sorts of metrics over IOs performed by the program. Another basic use case is to coordinate the termination of threads in a given program, for example when one thread finds an answer, or when the program is shut down by the user. + +Here, for example, we're going to try to find a number whose hash satisfies a basic property. To do that, we'll run multiple threads which will try random numbers until they find one that works. + +Of course the output below is a sample run and will change every time the program is run. + +```ocaml +(* use for termination *) +let stop_all_threads = Atomic.make false + +(* total number of individual attempts to find a number *) +let num_attempts = Atomic.make 0 + +(* find a number that satisfies [p], by... trying random numbers + until one fits. *) +let find_number_where (p:int -> bool) = + let rand = Random.State.make_self_init() in + while not (Atomic.get stop_all_threads) do + + let n = Random.State.full_int rand max_int in + ignore (Atomic.fetch_and_add num_attempts 1 : int); + + if p (Hashtbl.hash n) then ( + Printf.printf "found %d (hash=%d)\n%!" n (Hashtbl.hash n); + Atomic.set stop_all_threads true; (* signal all threads to stop *) + ) + done;; + + +(* run multiple domains to search for a [n] where [hash n <= 100] *) +let () = + let criterion n = n <= 100 in + let threads = + Array.init 8 + (fun _ -> Domain.spawn (fun () -> find_number_where criterion)) + in + Array.iter Domain.join threads; + Printf.printf "total number of attempts: %d\n%!" + (Atomic.get num_attempts) ;; + +- : unit = () +found 1651745641680046833 (hash=33) +total number of attempts: 30230350 +``` + +### Treiber Stack + +Another example is a basic [Treiber stack](https://en.wikipedia.org/wiki/Treiber_stack) (a thread-safe stack) that can be safely shared between threads. + +Note how both `push` and `pop` are recursive, because they attempt to swap the new stack (with one more, or one fewer, element) with the old stack. This is optimistic concurrency: each iteration of, say, `push stack x` gets the old stack `l`, and hopes that by the time it tries to replace `l` with `x::l`, nobody else has had time to modify the list. If the `compare_and_set` fails it means we were too optimistic, and must try again. + +```ocaml +type 'a stack = 'a list Atomic.t + +let rec push (stack: _ stack) elt : unit = + let cur = Atomic.get stack in + let success = Atomic.compare_and_set stack cur (elt :: cur) in + if not success then + push stack elt + +let rec pop (stack: _ stack) : _ option = + let cur = Atomic.get stack in + match cur with + | [] -> None + | x :: tail -> + let success = Atomic.compare_and_set stack cur tail in + if success then Some x + else pop stack + +# let st = Atomic.make [] +# push st 1 +- : unit = () +# push st 2 +- : unit = () +# pop st +- : int option = Some 2 +# pop st +- : int option = Some 1 +# pop st +- : int option = None +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Bool.md b/docs/api/re/melange/Stdlib-Bool.md new file mode 100644 index 000000000..d6f379425 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Bool.md @@ -0,0 +1,83 @@ + +# Module `Stdlib.Bool` + +Boolean values. + +since 4.08 + +## Booleans + +``` +type t = bool = +``` +``` +| false +``` +``` +| true +``` +``` + +``` +The type of booleans (truth values). + +The constructors `false` and `true` are included here so that they have paths, but they are not intended to be used in user-defined data types. + +``` +val not : bool -> bool +``` +`not b` is the boolean negation of `b`. + +``` +val (&&) : bool -> bool -> bool +``` +`e0 && e1` is the lazy boolean conjunction of expressions `e0` and `e1`. If `e0` evaluates to `false`, `e1` is not evaluated. Right-associative operator at precedence level 3/11. + +``` +val (||) : bool -> bool -> bool +``` +`e0 || e1` is the lazy boolean disjunction of expressions `e0` and `e1`. If `e0` evaluates to `true`, `e1` is not evaluated. Right-associative operator at precedence level 2/11. + + +## Predicates and comparisons + +``` +val equal : bool -> bool -> bool +``` +`equal b0 b1` is `true` if and only if `b0` and `b1` are both `true` or both `false`. + +``` +val compare : bool -> bool -> int +``` +`compare b0 b1` is a total order on boolean values. `false` is smaller than `true`. + + +## Converting + +``` +val to_int : bool -> int +``` +`to_int b` is `0` if `b` is `false` and `1` if `b` is `true`. + +``` +val to_float : bool -> float +``` +`to_float b` is `0.` if `b` is `false` and `1.` if `b` is `true`. + +``` +val to_string : bool -> string +``` +`to_string b` is `"true"` if `b` is `true` and `"false"` if `b` is `false`. + +``` +val seeded_hash : int -> bool -> int +``` +A seeded hash function for booleans, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.1 +``` +val hash : bool -> int +``` +An unseeded hash function for booleans, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Buffer.md b/docs/api/re/melange/Stdlib-Buffer.md new file mode 100644 index 000000000..9af9a8328 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Buffer.md @@ -0,0 +1,282 @@ + +# Module `Stdlib.Buffer` + +Extensible buffers. + +This module implements buffers that automatically expand as necessary. It provides accumulative concatenation of strings in linear time (instead of quadratic time when strings are concatenated pairwise). For example: + +```ocaml + let concat_strings ss = + let b = Buffer.create 16 in + List.iter (Buffer.add_string b) ss; + Buffer.contents b + +``` +**Unsynchronized accesses** + +Unsynchronized accesses to a buffer may lead to an invalid buffer state. Thus, concurrent accesses to a buffer must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + +``` +type t +``` +The abstract type of buffers. + +``` +val create : int -> t +``` +`create n` returns a fresh buffer, initially empty. The `n` parameter is the initial size of the internal byte sequence that holds the buffer contents. That byte sequence is automatically reallocated when more than `n` characters are stored in the buffer, but shrinks back to `n` characters when `reset` is called. For best performance, `n` should be of the same order of magnitude as the number of characters that are expected to be stored in the buffer (for instance, 80 for a buffer that holds one output line). Nothing bad will happen if the buffer grows beyond that limit, however. In doubt, take `n = 16` for instance. If `n` is not between 1 and [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length), it will be clipped to that interval. + +``` +val contents : t -> string +``` +Return a copy of the current contents of the buffer. The buffer itself is unchanged. + +``` +val to_bytes : t -> bytes +``` +Return a copy of the current contents of the buffer. The buffer itself is unchanged. + +since 4.02 +``` +val sub : t -> int -> int -> string +``` +`Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off and len do not designate a valid range of b. +``` +val blit : t -> int -> bytes -> int -> int -> unit +``` +`Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if srcoff and len do not designate a valid range of src, or if dstoff and len do not designate a valid range of dst. +since 3.11.2 +``` +val nth : t -> int -> char +``` +Get the n-th character of the buffer. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if index out of bounds +``` +val length : t -> int +``` +Return the number of characters currently contained in the buffer. + +``` +val clear : t -> unit +``` +Empty the buffer. + +``` +val reset : t -> unit +``` +Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by [`Buffer.create`](./#val-create) `n`. For long-lived buffers that may have grown a lot, `reset` allows faster reclamation of the space used by the buffer. + +``` +val output_buffer : out_channel -> t -> unit +``` +`output_buffer oc b` writes the current contents of buffer `b` on the output channel `oc`. + +``` +val truncate : t -> int -> unit +``` +`truncate b len` truncates the length of `b` to `len` Note: the internal byte sequence is not shortened. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> length b. +since 4.05 + +## Appending + +Note: all `add_*` operations can raise `Failure` if the internal byte sequence of the buffer would need to grow beyond [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length). + +``` +val add_char : t -> char -> unit +``` +`add_char b c` appends the character `c` at the end of buffer `b`. + +``` +val add_utf_8_uchar : t -> Uchar.t -> unit +``` +`add_utf_8_uchar b u` appends the [UTF-8](https://tools.ietf.org/html/rfc3629) encoding of `u` at the end of buffer `b`. + +since 4.06 +``` +val add_utf_16le_uchar : t -> Uchar.t -> unit +``` +`add_utf_16le_uchar b u` appends the [UTF-16LE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. + +since 4.06 +``` +val add_utf_16be_uchar : t -> Uchar.t -> unit +``` +`add_utf_16be_uchar b u` appends the [UTF-16BE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. + +since 4.06 +``` +val add_string : t -> string -> unit +``` +`add_string b s` appends the string `s` at the end of buffer `b`. + +``` +val add_bytes : t -> bytes -> unit +``` +`add_bytes b s` appends the byte sequence `s` at the end of buffer `b`. + +since 4.02 +``` +val add_substring : t -> string -> int -> int -> unit +``` +`add_substring b s ofs len` takes `len` characters from offset `ofs` in string `s` and appends them at the end of buffer `b`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. +``` +val add_subbytes : t -> bytes -> int -> int -> unit +``` +`add_subbytes b s ofs len` takes `len` characters from offset `ofs` in byte sequence `s` and appends them at the end of buffer `b`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. +since 4.02 +``` +val add_substitute : t -> (string -> string) -> string -> unit +``` +`add_substitute b f s` appends the string pattern `s` at the end of buffer `b` with substitution. The substitution process looks for variable references in the pattern and substitutes each variable reference with its value, as obtained by applying the mapping `f` to the variable name. Inside the string pattern, a variable reference is a non-escaped `$` immediately followed by a variable name, which is one of the following: + +- a non empty sequence of alphanumeric or `_` characters, +- an arbitrary sequence of characters enclosed by a pair of matching parentheses or curly brackets. An escaped `$` character is a `$` that immediately follows a backslash character; the two characters together stand for a plain `$`. +``` +val add_buffer : t -> t -> unit +``` +`add_buffer b1 b2` appends the current contents of buffer `b2` at the end of buffer `b1`. `b2` is not modified. + +``` +val add_channel : t -> in_channel -> int -> unit +``` +`add_channel b ic n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`. + +raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if the channel contains fewer than n characters. In this case, the characters are still added to the buffer, so as to avoid loss of data. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> Sys.max\_string\_length. + +## Buffers and Sequences + +``` +val to_seq : t -> char Seq.t +``` +Iterate on the buffer, in increasing order. + +The behavior is not specified if the buffer is modified during iteration. + +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +Iterate on the buffer, in increasing order, yielding indices along chars. + +The behavior is not specified if the buffer is modified during iteration. + +since 4.07 +``` +val add_seq : t -> char Seq.t -> unit +``` +Add chars to the buffer + +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +Create a buffer from the generator + +since 4.07 + +## Binary encoding of integers + +The functions in this section append binary encodings of integers to buffers. + +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. Functions that encode these values truncate their inputs to their least significant bytes. + +``` +val add_uint8 : t -> int -> unit +``` +`add_uint8 b i` appends a binary unsigned 8-bit integer `i` to `b`. + +since 4.08 +``` +val add_int8 : t -> int -> unit +``` +`add_int8 b i` appends a binary signed 8-bit integer `i` to `b`. + +since 4.08 +``` +val add_uint16_ne : t -> int -> unit +``` +`add_uint16_ne b i` appends a binary native-endian unsigned 16-bit integer `i` to `b`. + +since 4.08 +``` +val add_uint16_be : t -> int -> unit +``` +`add_uint16_be b i` appends a binary big-endian unsigned 16-bit integer `i` to `b`. + +since 4.08 +``` +val add_uint16_le : t -> int -> unit +``` +`add_uint16_le b i` appends a binary little-endian unsigned 16-bit integer `i` to `b`. + +since 4.08 +``` +val add_int16_ne : t -> int -> unit +``` +`add_int16_ne b i` appends a binary native-endian signed 16-bit integer `i` to `b`. + +since 4.08 +``` +val add_int16_be : t -> int -> unit +``` +`add_int16_be b i` appends a binary big-endian signed 16-bit integer `i` to `b`. + +since 4.08 +``` +val add_int16_le : t -> int -> unit +``` +`add_int16_le b i` appends a binary little-endian signed 16-bit integer `i` to `b`. + +since 4.08 +``` +val add_int32_ne : t -> int32 -> unit +``` +`add_int32_ne b i` appends a binary native-endian 32-bit integer `i` to `b`. + +since 4.08 +``` +val add_int32_be : t -> int32 -> unit +``` +`add_int32_be b i` appends a binary big-endian 32-bit integer `i` to `b`. + +since 4.08 +``` +val add_int32_le : t -> int32 -> unit +``` +`add_int32_le b i` appends a binary little-endian 32-bit integer `i` to `b`. + +since 4.08 +``` +val add_int64_ne : t -> int64 -> unit +``` +`add_int64_ne b i` appends a binary native-endian 64-bit integer `i` to `b`. + +since 4.08 +``` +val add_int64_be : t -> int64 -> unit +``` +`add_int64_be b i` appends a binary big-endian 64-bit integer `i` to `b`. + +since 4.08 +``` +val add_int64_le : t -> int64 -> unit +``` +`add_int64_ne b i` appends a binary little-endian 64-bit integer `i` to `b`. + +since 4.08 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Bytes.md b/docs/api/re/melange/Stdlib-Bytes.md new file mode 100644 index 000000000..28c026643 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Bytes.md @@ -0,0 +1,683 @@ + +# Module `Stdlib.Bytes` + +Byte sequence operations. + +A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. + +Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. + +Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. + +Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. + +Bytes are represented by the OCaml type `char`. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + +since 4.02 +``` +val length : bytes -> int +``` +Return the length (number of bytes) of the argument. + +``` +val get : bytes -> int -> char +``` +`get s n` returns the byte at index `n` in argument `s`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val set : bytes -> int -> char -> unit +``` +`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val create : int -> bytes +``` +`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val make : int -> char -> bytes +``` +`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> (int -> char) -> bytes +``` +`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val empty : bytes +``` +A byte sequence of size 0. + +``` +val copy : bytes -> bytes +``` +Return a new byte sequence that contains the same bytes as the argument. + +``` +val of_string : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. + +``` +val to_string : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. + +``` +val sub : bytes -> int -> int -> bytes +``` +`sub s pos len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val sub_string : bytes -> int -> int -> string +``` +Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. + +``` +val extend : bytes -> int -> int -> bytes +``` +`extend s left right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val fill : bytes -> int -> int -> char -> unit +``` +`fill s pos len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val blit : bytes -> int -> bytes -> int -> int -> unit +``` +`blit src src_pos dst dst_pos len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +``` +val blit_string : string -> int -> bytes -> int -> int -> unit +``` +`blit_string src src_pos dst dst_pos len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +since 4.05 in BytesLabels +``` +val concat : bytes -> bytes list -> bytes +``` +`concat sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : bytes -> bytes -> bytes +``` +`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val iter : (char -> unit) -> bytes -> unit +``` +`iter f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. + +``` +val iteri : (int -> char -> unit) -> bytes -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. + +``` +val map : (char -> char) -> bytes -> bytes +``` +`map f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + +``` +val mapi : (int -> char -> char) -> bytes -> bytes +``` +`mapi f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + +``` +val fold_left : ('acc -> char -> 'acc) -> 'acc -> bytes -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. + +since 4.13 +``` +val fold_right : (char -> 'acc -> 'acc) -> bytes -> 'acc -> 'acc +``` +`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. + +since 4.13 +``` +val for_all : (char -> bool) -> bytes -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. + +since 4.13 +``` +val exists : (char -> bool) -> bytes -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. + +since 4.13 +``` +val trim : bytes -> bytes +``` +Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. + +``` +val escaped : bytes -> bytes +``` +Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val index : bytes -> char -> int +``` +`index s c` returns the index of the first occurrence of byte `c` in `s`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val index_opt : bytes -> char -> int option +``` +`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + +since 4.05 +``` +val rindex : bytes -> char -> int +``` +`rindex s c` returns the index of the last occurrence of byte `c` in `s`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val rindex_opt : bytes -> char -> int option +``` +`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + +since 4.05 +``` +val index_from : bytes -> int -> char -> int +``` +`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +``` +val index_from_opt : bytes -> int -> char -> int option +``` +`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : bytes -> int -> char -> int +``` +`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +``` +val rindex_from_opt : bytes -> int -> char -> int option +``` +`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val contains : bytes -> char -> bool +``` +`contains s c` tests if byte `c` appears in `s`. + +``` +val contains_from : bytes -> int -> char -> bool +``` +`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : bytes -> int -> char -> bool +``` +`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val uppercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +val lowercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +val capitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +val uncapitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +type t = bytes +``` +An alias for the type of byte sequences. + +``` +val compare : t -> t -> int +``` +The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + +``` +val equal : t -> t -> bool +``` +The equality function for byte sequences. + +since 4.03 (4.05 in BytesLabels) +``` +val starts_with : prefix:bytes -> bytes -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + +since 4.13 +``` +val ends_with : suffix:bytes -> bytes -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + +since 4.13 + +## Unsafe conversions (for advanced users) + +This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. + +``` +val unsafe_to_string : bytes -> string +``` +Unsafely convert a byte sequence into a string. + +To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: + +- Unique ownership: the data may be accessed and mutated +- Shared ownership: the data has several owners, that may only access it, not mutate it. +Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. + +`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. + +There are two valid use-cases that respect this ownership discipline: + +1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. + +```ocaml +let string_init len f : string = + let s = Bytes.create len in + for i = 0 to len - 1 do Bytes.set s i (f i) done; + Bytes.unsafe_to_string s +``` +This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. + +Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. + +We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. + +2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. + +```ocaml +let bytes_length (s : bytes) = + String.length (Bytes.unsafe_to_string s) +``` +In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. + +The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. + +``` +val unsafe_of_string : string -> bytes +``` +Unsafely convert a shared string to a byte sequence that should not be mutated. + +The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. + +In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. + +For example, string literals are implicitly shared by the compiler, so you never uniquely own them. + +```ocaml +let incorrect = Bytes.unsafe_of_string "hello" +let s = Bytes.of_string "hello" +``` +The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. + +Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. + +The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. + +``` +val split_on_char : char -> bytes -> bytes list +``` +`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. + +The function's output is specified by the following invariants: + +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). +- No byte sequence in the result contains the `sep` character. +since 4.13 + +## Iterators + +``` +val to_seq : t -> char Seq.t +``` +Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. + +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +Iterate on the string, in increasing order, yielding indices along chars + +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +Create a string from the generator + +since 4.07 + +## UTF codecs and validations + +since 4.14 + +### UTF-8 + +``` +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`. + +``` +val set_utf_8_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + +### UTF-16BE + +``` +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`. + +``` +val set_utf_16be_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + +### UTF-16LE + +``` +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`. + +``` +val set_utf_16le_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + +## Binary encoding/decoding of integers + +The functions in this section binary encode and decode integers to and from byte sequences. + +All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. + +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: + +- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. +- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. +``` +val get_uint8 : bytes -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int8 : bytes -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_uint16_ne : bytes -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_uint16_be : bytes -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_uint16_le : bytes -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int16_ne : bytes -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int16_be : bytes -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int16_le : bytes -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int32_ne : bytes -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int32_be : bytes -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int32_le : bytes -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int64_ne : bytes -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int64_be : bytes -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int64_le : bytes -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. + +since 4.08 +``` +val set_uint8 : bytes -> int -> int -> unit +``` +`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int8 : bytes -> int -> int -> unit +``` +`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_uint16_ne : bytes -> int -> int -> unit +``` +`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_uint16_be : bytes -> int -> int -> unit +``` +`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_uint16_le : bytes -> int -> int -> unit +``` +`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int16_ne : bytes -> int -> int -> unit +``` +`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int16_be : bytes -> int -> int -> unit +``` +`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int16_le : bytes -> int -> int -> unit +``` +`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int32_ne : bytes -> int -> int32 -> unit +``` +`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int32_be : bytes -> int -> int32 -> unit +``` +`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int32_le : bytes -> int -> int32 -> unit +``` +`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int64_ne : bytes -> int -> int64 -> unit +``` +`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int64_be : bytes -> int -> int64 -> unit +``` +`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int64_le : bytes -> int -> int64 -> unit +``` +`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. + +since 4.08 + +## Byte sequences and concurrency safety + +Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + +### Atomicity + +Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. + +For example, consider the following program: + +```ocaml +let size = 100_000_000 +let b = Bytes.make size ' ' +let update b f () = + Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b +let d1 = Domain.spawn (update b (fun x -> x + 1)) +let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) +let () = Domain.join d1; Domain.join d2 +``` +the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. + +After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +### Data races + +If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + +A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. + +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. + + +### Mixed-size accesses + +Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index + +```ocaml +let b = Bytes.make 10 '\000' +let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) +``` +In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/re/melange/Stdlib-BytesLabels.md b/docs/api/re/melange/Stdlib-BytesLabels.md new file mode 100644 index 000000000..ece55c1e0 --- /dev/null +++ b/docs/api/re/melange/Stdlib-BytesLabels.md @@ -0,0 +1,695 @@ + +# Module `Stdlib.BytesLabels` + +Byte sequence operations. + +A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. + +Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. + +Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. + +Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. + +Bytes are represented by the OCaml type `char`. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + +since 4.02 +``` +val length : bytes -> int +``` +Return the length (number of bytes) of the argument. + +``` +val get : bytes -> int -> char +``` +`get s n` returns the byte at index `n` in argument `s`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val set : bytes -> int -> char -> unit +``` +`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. +``` +val create : int -> bytes +``` +`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val make : int -> char -> bytes +``` +`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> f:(int -> char) -> bytes +``` +`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val empty : bytes +``` +A byte sequence of size 0. + +``` +val copy : bytes -> bytes +``` +Return a new byte sequence that contains the same bytes as the argument. + +``` +val of_string : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. + +``` +val to_string : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. + +``` +val sub : bytes -> pos:int -> len:int -> bytes +``` +`sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val sub_string : bytes -> pos:int -> len:int -> string +``` +Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. + +``` +val extend : bytes -> left:int -> right:int -> bytes +``` +`extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val fill : bytes -> pos:int -> len:int -> char -> unit +``` +`fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. +``` +val blit : + src:bytes -> + src_pos:int -> + dst:bytes -> + dst_pos:int -> + len:int -> + unit +``` +`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +``` +val blit_string : + src:string -> + src_pos:int -> + dst:bytes -> + dst_pos:int -> + len:int -> + unit +``` +`blit_string ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. +since 4.05 in BytesLabels +``` +val concat : sep:bytes -> bytes list -> bytes +``` +`concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : bytes -> bytes -> bytes +``` +`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.05 in BytesLabels +``` +val iter : f:(char -> unit) -> bytes -> unit +``` +`iter ~f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. + +``` +val iteri : f:(int -> char -> unit) -> bytes -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. + +``` +val map : f:(char -> char) -> bytes -> bytes +``` +`map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + +``` +val mapi : f:(int -> char -> char) -> bytes -> bytes +``` +`mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. + +``` +val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> bytes -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. + +since 4.13 +``` +val fold_right : f:(char -> 'acc -> 'acc) -> bytes -> init:'acc -> 'acc +``` +`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. + +since 4.13 +``` +val for_all : f:(char -> bool) -> bytes -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. + +since 4.13 +``` +val exists : f:(char -> bool) -> bytes -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. + +since 4.13 +``` +val trim : bytes -> bytes +``` +Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. + +``` +val escaped : bytes -> bytes +``` +Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val index : bytes -> char -> int +``` +`index s c` returns the index of the first occurrence of byte `c` in `s`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val index_opt : bytes -> char -> int option +``` +`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + +since 4.05 +``` +val rindex : bytes -> char -> int +``` +`rindex s c` returns the index of the last occurrence of byte `c` in `s`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. +``` +val rindex_opt : bytes -> char -> int option +``` +`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. + +since 4.05 +``` +val index_from : bytes -> int -> char -> int +``` +`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +``` +val index_from_opt : bytes -> int -> char -> int option +``` +`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : bytes -> int -> char -> int +``` +`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +``` +val rindex_from_opt : bytes -> int -> char -> int option +``` +`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val contains : bytes -> char -> bool +``` +`contains s c` tests if byte `c` appears in `s`. + +``` +val contains_from : bytes -> int -> char -> bool +``` +`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : bytes -> int -> char -> bool +``` +`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val uppercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +val lowercase_ascii : bytes -> bytes +``` +Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +val capitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +val uncapitalize_ascii : bytes -> bytes +``` +Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in BytesLabels) +``` +type t = bytes +``` +An alias for the type of byte sequences. + +``` +val compare : t -> t -> int +``` +The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + +``` +val equal : t -> t -> bool +``` +The equality function for byte sequences. + +since 4.03 (4.05 in BytesLabels) +``` +val starts_with : prefix:bytes -> bytes -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + +since 4.13 +``` +val ends_with : suffix:bytes -> bytes -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + +since 4.13 + +## Unsafe conversions (for advanced users) + +This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. + +``` +val unsafe_to_string : bytes -> string +``` +Unsafely convert a byte sequence into a string. + +To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: + +- Unique ownership: the data may be accessed and mutated +- Shared ownership: the data has several owners, that may only access it, not mutate it. +Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. + +`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. + +There are two valid use-cases that respect this ownership discipline: + +1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. + +```ocaml +let string_init len f : string = + let s = Bytes.create len in + for i = 0 to len - 1 do Bytes.set s i (f i) done; + Bytes.unsafe_to_string s +``` +This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. + +Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. + +We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. + +2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. + +```ocaml +let bytes_length (s : bytes) = + String.length (Bytes.unsafe_to_string s) +``` +In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. + +The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. + +``` +val unsafe_of_string : string -> bytes +``` +Unsafely convert a shared string to a byte sequence that should not be mutated. + +The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. + +In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. + +For example, string literals are implicitly shared by the compiler, so you never uniquely own them. + +```ocaml +let incorrect = Bytes.unsafe_of_string "hello" +let s = Bytes.of_string "hello" +``` +The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. + +Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. + +The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. + +``` +val split_on_char : sep:char -> bytes -> bytes list +``` +`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. + +The function's output is specified by the following invariants: + +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). +- No byte sequence in the result contains the `sep` character. +since 4.13 + +## Iterators + +``` +val to_seq : t -> char Seq.t +``` +Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. + +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +Iterate on the string, in increasing order, yielding indices along chars + +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +Create a string from the generator + +since 4.07 + +## UTF codecs and validations + +since 4.14 + +### UTF-8 + +``` +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`. + +``` +val set_utf_8_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + +### UTF-16BE + +``` +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`. + +``` +val set_utf_16be_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + +### UTF-16LE + +``` +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`. + +``` +val set_utf_16le_uchar : t -> int -> Uchar.t -> int +``` +`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. + +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + +## Binary encoding/decoding of integers + +The functions in this section binary encode and decode integers to and from byte sequences. + +All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. + +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: + +- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. +- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. +``` +val get_uint8 : bytes -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int8 : bytes -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_uint16_ne : bytes -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_uint16_be : bytes -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_uint16_le : bytes -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int16_ne : bytes -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int16_be : bytes -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int16_le : bytes -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int32_ne : bytes -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int32_be : bytes -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int32_le : bytes -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int64_ne : bytes -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int64_be : bytes -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. + +since 4.08 +``` +val get_int64_le : bytes -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. + +since 4.08 +``` +val set_uint8 : bytes -> int -> int -> unit +``` +`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int8 : bytes -> int -> int -> unit +``` +`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_uint16_ne : bytes -> int -> int -> unit +``` +`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_uint16_be : bytes -> int -> int -> unit +``` +`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_uint16_le : bytes -> int -> int -> unit +``` +`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int16_ne : bytes -> int -> int -> unit +``` +`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int16_be : bytes -> int -> int -> unit +``` +`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int16_le : bytes -> int -> int -> unit +``` +`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int32_ne : bytes -> int -> int32 -> unit +``` +`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int32_be : bytes -> int -> int32 -> unit +``` +`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int32_le : bytes -> int -> int32 -> unit +``` +`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int64_ne : bytes -> int -> int64 -> unit +``` +`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int64_be : bytes -> int -> int64 -> unit +``` +`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. + +since 4.08 +``` +val set_int64_le : bytes -> int -> int64 -> unit +``` +`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. + +since 4.08 + +## Byte sequences and concurrency safety + +Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + +### Atomicity + +Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. + +For example, consider the following program: + +```ocaml +let size = 100_000_000 +let b = Bytes.make size ' ' +let update b f () = + Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b +let d1 = Domain.spawn (update b (fun x -> x + 1)) +let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) +let () = Domain.join d1; Domain.join d2 +``` +the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. + +After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +### Data races + +If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + +A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. + +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. + + +### Mixed-size accesses + +Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index + +```ocaml +let b = Bytes.make 10 '\000' +let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) +``` +In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/re/melange/Stdlib-Char.md b/docs/api/re/melange/Stdlib-Char.md new file mode 100644 index 000000000..31c382bda --- /dev/null +++ b/docs/api/re/melange/Stdlib-Char.md @@ -0,0 +1,61 @@ + +# Module `Stdlib.Char` + +Character operations. + +``` +val code : char -> int +``` +Return the ASCII code of the argument. + +``` +val chr : int -> char +``` +Return the character with the given ASCII code. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is outside the range 0--255. +``` +val escaped : char -> string +``` +Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote. + +``` +val lowercase_ascii : char -> char +``` +Convert the given character to its equivalent lowercase character, using the US-ASCII character set. + +since 4.03 +``` +val uppercase_ascii : char -> char +``` +Convert the given character to its equivalent uppercase character, using the US-ASCII character set. + +since 4.03 +``` +type t = char +``` +An alias for the type of characters. + +``` +val compare : t -> t -> int +``` +The comparison function for characters, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Char` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + +``` +val equal : t -> t -> bool +``` +The equal function for chars. + +since 4.03 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for characters, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for characters, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Complex.md b/docs/api/re/melange/Stdlib-Complex.md new file mode 100644 index 000000000..e751d99b7 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Complex.md @@ -0,0 +1,106 @@ + +# Module `Stdlib.Complex` + +Complex numbers. + +This module provides arithmetic operations on complex numbers. Complex numbers are represented by their real and imaginary parts (cartesian representation). Each part is represented by a double-precision floating-point number (type `float`). + +``` +type t = { +``` +`re : float;` +`im : float;` +``` +} +``` +The type of complex numbers. `re` is the real part and `im` the imaginary part. + +``` +val zero : t +``` +The complex number `0`. + +``` +val one : t +``` +The complex number `1`. + +``` +val i : t +``` +The complex number `i`. + +``` +val neg : t -> t +``` +Unary negation. + +``` +val conj : t -> t +``` +Conjugate: given the complex `x + i.y`, returns `x - i.y`. + +``` +val add : t -> t -> t +``` +Addition + +``` +val sub : t -> t -> t +``` +Subtraction + +``` +val mul : t -> t -> t +``` +Multiplication + +``` +val inv : t -> t +``` +Multiplicative inverse (`1/z`). + +``` +val div : t -> t -> t +``` +Division + +``` +val sqrt : t -> t +``` +Square root. The result `x + i.y` is such that `x > 0` or `x = 0` and `y >= 0`. This function has a discontinuity along the negative real axis. + +``` +val norm2 : t -> float +``` +Norm squared: given `x + i.y`, returns `x^2 + y^2`. + +``` +val norm : t -> float +``` +Norm: given `x + i.y`, returns `sqrt(x^2 + y^2)`. + +``` +val arg : t -> float +``` +Argument. The argument of a complex number is the angle in the complex plane between the positive real axis and a line passing through zero and the number. This angle ranges from `-pi` to `pi`. This function has a discontinuity along the negative real axis. + +``` +val polar : float -> float -> t +``` +`polar norm arg` returns the complex having norm `norm` and argument `arg`. + +``` +val exp : t -> t +``` +Exponentiation. `exp z` returns `e` to the `z` power. + +``` +val log : t -> t +``` +Natural logarithm (in base `e`). + +``` +val pow : t -> t -> t +``` +Power function. `pow z1 z2` returns `z1` to the `z2` power. diff --git a/docs/api/re/melange/Stdlib-Digest-BLAKE128.md b/docs/api/re/melange/Stdlib-Digest-BLAKE128.md new file mode 100644 index 000000000..d066e1e33 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Digest-BLAKE128.md @@ -0,0 +1,78 @@ + +# Module `Digest.BLAKE128` + +`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. + +since 5.2 +``` +type t = string +``` +The type of digests. + +``` +val hash_length : int +``` +The length of digests, in bytes. + +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + +``` +val equal : t -> t -> bool +``` +Test two digests for equality. + +``` +val string : string -> t +``` +Return the digest of the given string. + +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. + +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + +``` +val file : string -> t +``` +Return the digest of the file whose name is given. + +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. + +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. + +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-BLAKE256.md b/docs/api/re/melange/Stdlib-Digest-BLAKE256.md new file mode 100644 index 000000000..ee9952c96 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Digest-BLAKE256.md @@ -0,0 +1,78 @@ + +# Module `Digest.BLAKE256` + +`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + +since 5.2 +``` +type t = string +``` +The type of digests. + +``` +val hash_length : int +``` +The length of digests, in bytes. + +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + +``` +val equal : t -> t -> bool +``` +Test two digests for equality. + +``` +val string : string -> t +``` +Return the digest of the given string. + +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. + +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + +``` +val file : string -> t +``` +Return the digest of the file whose name is given. + +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. + +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. + +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-BLAKE512.md b/docs/api/re/melange/Stdlib-Digest-BLAKE512.md new file mode 100644 index 000000000..a22b0bc72 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Digest-BLAKE512.md @@ -0,0 +1,78 @@ + +# Module `Digest.BLAKE512` + +`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + +since 5.2 +``` +type t = string +``` +The type of digests. + +``` +val hash_length : int +``` +The length of digests, in bytes. + +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + +``` +val equal : t -> t -> bool +``` +Test two digests for equality. + +``` +val string : string -> t +``` +Return the digest of the given string. + +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. + +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + +``` +val file : string -> t +``` +Return the digest of the file whose name is given. + +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. + +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. + +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-MD5.md b/docs/api/re/melange/Stdlib-Digest-MD5.md new file mode 100644 index 000000000..9909a727e --- /dev/null +++ b/docs/api/re/melange/Stdlib-Digest-MD5.md @@ -0,0 +1,78 @@ + +# Module `Digest.MD5` + +`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. + +since 5.2 +``` +type t = string +``` +The type of digests. + +``` +val hash_length : int +``` +The length of digests, in bytes. + +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + +``` +val equal : t -> t -> bool +``` +Test two digests for equality. + +``` +val string : string -> t +``` +Return the digest of the given string. + +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. + +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + +``` +val file : string -> t +``` +Return the digest of the file whose name is given. + +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. + +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. + +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-module-type-S.md b/docs/api/re/melange/Stdlib-Digest-module-type-S.md new file mode 100644 index 000000000..8e6095b8a --- /dev/null +++ b/docs/api/re/melange/Stdlib-Digest-module-type-S.md @@ -0,0 +1,78 @@ + +# Module type `Digest.S` + +The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. + +since 5.2 +``` +type t = string +``` +The type of digests. + +``` +val hash_length : int +``` +The length of digests, in bytes. + +``` +val compare : t -> t -> int +``` +Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). + +``` +val equal : t -> t -> bool +``` +Test two digests for equality. + +``` +val string : string -> t +``` +Return the digest of the given string. + +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. + +``` +val substring : string -> int -> int -> t +``` +`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + +``` +val subbytes : bytes -> int -> int -> t +``` +`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + +``` +val channel : in_channel -> int -> t +``` +Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. + +``` +val file : string -> t +``` +Return the digest of the file whose name is given. + +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. + +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. + +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest.md b/docs/api/re/melange/Stdlib-Digest.md new file mode 100644 index 000000000..6ef661f6d --- /dev/null +++ b/docs/api/re/melange/Stdlib-Digest.md @@ -0,0 +1,120 @@ + +# Module `Stdlib.Digest` + +Message digest. + +This module provides functions to compute 'digests', also known as 'hashes', of arbitrary-length strings or files. The supported hashing algorithms are BLAKE2 and MD5. + + +## Basic functions + +The functions in this section use the MD5 hash function to produce 128-bit digests (16 bytes). MD5 is not cryptographically secure. Hence, these functions should not be used for security-sensitive applications. The BLAKE2 functions below are cryptographically secure. + +``` +type t = string +``` +The type of digests: 16-byte strings. + +``` +val compare : t -> t -> int +``` +The comparison function for 16-byte digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare) and the implementation shared with [`String.compare`](./Stdlib-String.md#val-compare). Along with the type `t`, this function `compare` allows the module `Digest` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + +since 4.00 +``` +val equal : t -> t -> bool +``` +The equal function for 16-byte digests. + +since 4.03 +``` +val string : string -> t +``` +Return the digest of the given string. + +``` +val bytes : bytes -> t +``` +Return the digest of the given byte sequence. + +since 4.02 +``` +val substring : string -> int -> int -> t +``` +`Digest.substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. + +``` +val subbytes : bytes -> int -> int -> t +``` +`Digest.subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. + +since 4.02 +``` +val channel : in_channel -> int -> t +``` +If `len` is nonnegative, `Digest.channel ic len` reads `len` characters from channel `ic` and returns their digest, or raises `End_of_file` if end-of-file is reached before `len` characters are read. If `len` is negative, `Digest.channel ic len` reads all characters from `ic` until end-of-file is reached and return their digest. + +``` +val file : string -> t +``` +Return the digest of the file whose name is given. + +``` +val output : out_channel -> t -> unit +``` +Write a digest on the given output channel. + +``` +val input : in_channel -> t +``` +Read a digest from the given input channel. + +``` +val to_hex : t -> string +``` +Return the printable hexadecimal representation of the given digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 16 bytes. +``` +val of_hex : string -> t +``` +Convert a hexadecimal representation back into the corresponding digest. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 32 hexadecimal characters. +since 5.2 +``` +val from_hex : string -> t +``` +Same function as [`Digest.of_hex`](./#val-of_hex). + +since 4.00 + +## Generic interface + +``` +module type S = sig ... end +``` +The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. + + +## Specific hash functions + +``` +module BLAKE128 : S +``` +`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. + +``` +module BLAKE256 : S +``` +`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + +``` +module BLAKE512 : S +``` +`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. + +``` +module MD5 : S +``` +`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. diff --git a/docs/api/re/melange/Stdlib-Domain-DLS.md b/docs/api/re/melange/Stdlib-Domain-DLS.md new file mode 100644 index 000000000..5c29e70ee --- /dev/null +++ b/docs/api/re/melange/Stdlib-Domain-DLS.md @@ -0,0 +1,45 @@ + +# Module `Domain.DLS` + +Domain-local Storage + +``` +type 'a key +``` +Type of a DLS key + +``` +val new_key : ?split_from_parent:('a -> 'a) -> (unit -> 'a) -> 'a key +``` +`new_key f` returns a new key bound to initialiser `f` for accessing domain-local variables. + +If `split_from_parent` is not provided, the value for a new domain will be computed on-demand by the new domain: the first `get` call will call the initializer `f` and store that value. + +**Warning.** `f` may be called several times if another call to `get` occurs during initialization on the same domain. Only the 'first' value computed will be used, the other now-useless values will be discarded. Your initialization function should support this situation, or contain logic to detect this case and fail. + +If `split_from_parent` is provided, spawning a domain will derive the child value (for this key) from the parent value. This computation happens in the parent domain and it always happens, regardless of whether the child domain will use it. If the splitting function is expensive or requires child-side computation, consider using `'a Lazy.t key`: + +```ocaml +let init () = ... + +let split_from_parent parent_value = + ... parent-side computation ...; + lazy ( + ... child-side computation ... + ) + +let key = Domain.DLS.new_key ~split_from_parent init + +let get () = Lazy.force (Domain.DLS.get key) +``` +In this case a part of the computation happens on the child domain; in particular, it can access `parent_value` concurrently with the parent domain, which may require explicit synchronization to avoid data races. + +``` +val get : 'a key -> 'a +``` +`get k` returns `v` if a value `v` is associated to the key `k` on the calling domain's domain-local state. Sets `k`'s value with its initialiser and returns it otherwise. + +``` +val set : 'a key -> 'a -> unit +``` +`set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. It overwrites any previous values associated to `k`, which cannot be restored later. diff --git a/docs/api/re/melange/Stdlib-Domain.md b/docs/api/re/melange/Stdlib-Domain.md new file mode 100644 index 000000000..5a038a823 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Domain.md @@ -0,0 +1,89 @@ + +# Module `Stdlib.Domain` + +alert unstable The Domain interface may change in incompatible ways in the future. +Domains. + +See 'Parallel programming' chapter in the manual. + +since 5.0 +alert unstable The Domain interface may change in incompatible ways in the future. +``` +type !'a t +``` +A domain of type `'a t` runs independently, eventually producing a result of type 'a, or an exception + +``` +val spawn : (unit -> 'a) -> 'a t +``` +`spawn f` creates a new domain that runs in parallel with the current domain. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the program has insufficient resources to create another domain. +``` +val join : 'a t -> 'a Js.Promise.t +``` +`join d` blocks until domain `d` runs to completion. If `d` results in a value, then that is returned by `join d`. If `d` raises an uncaught exception, then that is re-raised by `join d`. + +``` +type id = private int +``` +Domains have unique integer identifiers + +``` +val get_id : 'a t -> id +``` +`get_id d` returns the identifier of the domain `d` + +``` +val self : unit -> id +``` +`self ()` is the identifier of the currently running domain + +``` +val before_first_spawn : (unit -> unit) -> unit +``` +`before_first_spawn f` registers `f` to be called before the first domain is spawned by the program. The functions registered with `before_first_spawn` are called on the main (initial) domain. The functions registered with `before_first_spawn` are called in 'first in, first out' order: the oldest function added with `before_first_spawn` is called first. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the program has already spawned a domain. +``` +val at_exit : (unit -> unit) -> unit +``` +`at_exit f` registers `f` to be called when the current domain exits. Note that `at_exit` callbacks are domain-local and only apply to the calling domain. The registered functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. An example: + +```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) +``` +The snippet above creates a key that when retrieved for the first time will open a temporary file and register an `at_exit` callback to close it, thus guaranteeing the descriptor is not leaked in case the current domain exits. + +``` +val cpu_relax : unit -> unit +``` +If busy-waiting, calling cpu\_relax () between iterations will improve performance on some CPU architectures + +``` +val is_main_domain : unit -> bool +``` +`is_main_domain ()` returns true if called from the initial domain. + +``` +val recommended_domain_count : unit -> int +``` +The recommended maximum number of domains which should be running simultaneously (including domains already running). + +The value returned is at least `1`. + +``` +val self_index : unit -> int +``` +The index of the current domain. It is an integer unique among currently-running domains, in the interval `0; N-1` where N is the peak number of domains running simultaneously so far. + +The index of a terminated domain may be reused for a new domain. Use `(Domain.self () :> int)` instead for an identifier unique among all domains ever created by the program. + +since 5.3 +``` +module DLS : sig ... end +``` +Domain-local Storage diff --git a/docs/api/re/melange/Stdlib-Dynarray.md b/docs/api/re/melange/Stdlib-Dynarray.md new file mode 100644 index 000000000..c278e16be --- /dev/null +++ b/docs/api/re/melange/Stdlib-Dynarray.md @@ -0,0 +1,582 @@ + +# Module `Stdlib.Dynarray` + +Dynamic arrays. + +The [`Array`](./Stdlib-Array.md) module provide arrays of fixed length. [`Dynarray`](#) provides arrays whose length can change over time, by adding or removing elements at the end of the array. + +This is typically used to accumulate elements whose number is not known in advance or changes during computation, while also providing fast access to elements at arbitrary indices. + +```ocaml + let dynarray_of_list li = + let arr = Dynarray.create () in + List.iter (fun v -> Dynarray.add_last arr v) li; + arr +``` +The [`Buffer`](./Stdlib-Buffer.md) module provides similar features, but it is specialized for accumulating characters into a dynamically-resized string. + +The [`Stack`](./Stdlib-Stack.md) module provides a last-in first-out data structure that can be easily implemented on top of dynamic arrays. + +since 5.2 +**Unsynchronized accesses** + +Concurrent accesses to dynamic arrays must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). Unsynchronized accesses to a dynamic array are a programming error that may lead to an invalid dynamic array state, on which some operations would fail with an `Invalid_argument` exception. + + +## Dynamic arrays + +``` +type !'a t +``` +A dynamic array containing values of type `'a`. + +A dynamic array `a` provides constant-time `get` and `set` operations on indices between `0` and `Dynarray.length a - 1` included. Its [`length`](./#val-length) may change over time by adding or removing elements to the end of the array. + +We say that an index into a dynarray `a` is valid if it is in `0 .. length a - 1` and invalid otherwise. + +``` +val create : unit -> 'a t +``` +`create ()` is a new, empty array. + +``` +val make : int -> 'a -> 'a t +``` +`make n x` is a new array of length `n`, filled with `x`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. +``` +val init : int -> (int -> 'a) -> 'a t +``` +`init n f` is a new array `a` of length `n`, such that `get a i` is `f i`. In other words, the elements of `a` are `f 0`, then `f 1`, then `f 2`... and `f (n - 1)` last, evaluated in that order. + +This is similar to [`Array.init`](./Stdlib-Array.md#val-init). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. +``` +val get : 'a t -> int -> 'a +``` +`get a i` is the `i`\-th element of `a`, starting with index `0`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid +``` +val set : 'a t -> int -> 'a -> unit +``` +`set a i x` sets the `i`\-th element of `a` to be `x`. + +`i` must be a valid index. `set` does not add new elements to the array \-- see [`add_last`](./#val-add_last) to add an element. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid. +``` +val length : 'a t -> int +``` +`length a` is the number of elements in the array. + +``` +val is_empty : 'a t -> bool +``` +`is_empty a` is `true` if `a` is empty, that is, if `length a = 0`. + +``` +val get_last : 'a t -> 'a +``` +`get_last a` is the element of `a` at index `length a - 1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if a is empty. +``` +val find_last : 'a t -> 'a option +``` +`find_last a` is `None` if `a` is empty and `Some (get_last a)` otherwise. + +``` +val copy : 'a t -> 'a t +``` +`copy a` is a shallow copy of `a`, a new array containing the same elements as `a`. + + +## Adding elements + +Note: all operations adding elements raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). + +``` +val add_last : 'a t -> 'a -> unit +``` +`add_last a x` adds the element `x` at the end of the array `a`. + +``` +val append_array : 'a t -> 'a array -> unit +``` +`append_array a b` adds all elements of `b` at the end of `a`, in the order they appear in `b`. + +For example: + +```ocaml + let a = Dynarray.of_list [1;2] in + Dynarray.append_array a [|3; 4|]; + assert (Dynarray.to_list a = [1; 2; 3; 4]) +``` +``` +val append_list : 'a t -> 'a list -> unit +``` +Like [`append_array`](./#val-append_array) but with a list. + +``` +val append : 'a t -> 'a t -> unit +``` +`append a b` is like `append_array a b`, but `b` is itself a dynamic array instead of a fixed-size array. + +Warning: `append a a` is a programming error because it iterates on `a` and adds elements to it at the same time \-- see the [Iteration](./#iteration) section below. It fails with `Invalid_argument`. If you really want to append a copy of `a` to itself, you can use `Dynarray.append_array a (Dynarray.to_array a)` which copies `a` into a temporary array. + +``` +val append_seq : 'a t -> 'a Seq.t -> unit +``` +Like [`append_array`](./#val-append_array) but with a sequence. + +Warning: `append_seq a (to_seq_reentrant a)` simultaneously traverses `a` and adds element to it; the ordering of those operations is unspecified, and may result in an infinite loop \-- the new elements may in turn be produced by `to_seq_reentrant a` and get added again and again. + +``` +val append_iter : 'a t -> (('a -> unit) -> 'x -> unit) -> 'x -> unit +``` +`append_iter a iter x` adds each element of `x` to the end of `a`. This is `iter (add_last a) x`. + +For example, `append_iter a List.iter [1;2;3]` would add elements `1`, `2`, and then `3` at the end of `a`. `append_iter a Queue.iter q` adds elements from the queue `q`. + +``` +val blit : + src:'a t -> + src_pos:int -> + dst:'a t -> + dst_pos:int -> + len:int -> + unit +``` +`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from a source dynarray `src`, starting at index `src_pos`, to a destination dynarray `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. + +Unlike [`Array.blit`](./Stdlib-Array.md#val-blit), [`Dynarray.blit`](./#val-blit) can extend the destination array with new elements: it is valid to call `blit` even when `dst_pos + len` is larger than `length dst`. The only requirement is that `dst_pos` must be at most `length dst` (included), so that there is no gap between the current elements and the blit region. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos is strictly below 0 or strictly above length dst. + +## Removing elements + +``` +val pop_last_opt : 'a t -> 'a option +``` +`pop_last_opt a` removes and returns the last element of `a`, or `None` if the array is empty. + +``` +val pop_last : 'a t -> 'a +``` +`pop_last a` removes and returns the last element of `a`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) on an empty array. +``` +val remove_last : 'a t -> unit +``` +`remove_last a` removes the last element of `a`, if any. It does nothing if `a` is empty. + +``` +val truncate : 'a t -> int -> unit +``` +`truncate a n` truncates `a` to have at most `n` elements. + +It removes elements whose index is greater or equal to `n`. It does nothing if `n >= length a`. + +`truncate a n` is equivalent to: + +```ocaml + if n < 0 then invalid_argument "..."; + while length a > n do + remove_last a + done +``` +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. +``` +val clear : 'a t -> unit +``` +`clear a` is `truncate a 0`, it removes all the elements of `a`. + + +## Iteration + +The iteration functions traverse the elements of a dynamic array. Traversals of `a` are computed in increasing index order: from the element of index `0` to the element of index `length a - 1`. + +It is a programming error to change the length of an array (by adding or removing elements) during an iteration on the array. Any iteration function will fail with `Invalid_argument` if it detects such a length change. + +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f a` calls `f` on each element of `a`. + +``` +val iteri : (int -> 'a -> unit) -> 'a t -> unit +``` +`iteri f a` calls `f i x` for each `x` at index `i` in `a`. + +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f a` is a new array of elements of the form `f x` for each element `x` of `a`. + +For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f x0`, `f x1`, `f x2`. + +``` +val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t +``` +`mapi f a` is a new array of elements of the form `f i x` for each element `x` of `a` at index `i`. + +For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f 0 x0`, `f 1 x1`, `f 2 x2`. + +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold_left f acc a` folds `f` over `a` in order, starting with accumulator `acc`. + +For example, if the elements of `a` are `x0`, `x1`, then `fold f acc a` is + +```ocaml + let acc = f acc x0 in + let acc = f acc x1 in + acc +``` +``` +val fold_right : ('a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +`fold_right f a acc` computes `f x0 (f x1 (... (f xn acc) ...))` where `x0`, `x1`, ..., `xn` are the elements of `a`. + +``` +val filter : ('a -> bool) -> 'a t -> 'a t +``` +`filter f a` is a new array of all the elements of `a` that satisfy `f`. In other words, it is an array `b` such that, for each element `x` in `a` in order, `x` is added to `b` if `f x` is `true`. + +For example, `filter (fun x -> x >= 0) a` is a new array of all non-negative elements of `a`, in order. + +``` +val filter_map : ('a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f a` is a new array of elements `y` such that `f x` is `Some y` for an element `x` of `a`. In others words, it is an array `b` such that, for each element `x` of `a` in order: + +- if `f x = Some y`, then `y` is added to `b`, +- if `f x = None`, then no element is added to `b`. +For example, `filter_map int_of_string_opt inputs` returns a new array of integers read from the strings in `inputs`, ignoring strings that cannot be converted to integers. + + +## Dynarray scanning + +``` +val exists : ('a -> bool) -> 'a t -> bool +``` +`exists f a` is `true` if some element of `a` satisfies `f`. + +For example, if the elements of `a` are `x0`, `x1`, `x2`, then `exists f a` is `f x0 || f x1 || f x2`. + +``` +val for_all : ('a -> bool) -> 'a t -> bool +``` +`for_all f a` is `true` if all elements of `a` satisfy `f`. This includes the case where `a` is empty. + +For example, if the elements of `a` are `x0`, `x1`, then `exists f a` is `f x0 && f x1 && f x2`. + +``` +val mem : 'a -> 'a t -> bool +``` +`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). + +since 5.3 +``` +val memq : 'a -> 'a t -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. + +since 5.3 +``` +val find_opt : ('a -> bool) -> 'a t -> 'a option +``` +`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. + +since 5.3 +``` +val find_index : ('a -> bool) -> 'a t -> int option +``` +`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + +It returns `None` if there is no such element. + +since 5.3 +``` +val find_map : ('a -> 'b option) -> 'a t -> 'b option +``` +`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. + +since 5.3 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 5.3 + +## Comparison functions + +Comparison functions iterate over their arguments; it is a programming error to change their length during the iteration, see the [Iteration](./#iteration) section above. + +``` +val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal eq a b` holds when `a` and `b` have the same length, and for all indices `i` we have `eq (get a i) (get b i)`. + +since 5.3 +``` +val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Provided the function `cmp` defines a preorder on elements, `compare cmp a b` compares first `a` and `b` by their length, and then, if equal, by their elements according to the lexicographic preorder. + +For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). + +since 5.3 + +## Conversions to other data structures + +Note: the `of_*` functions raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). + +The `to_*` functions, except those specifically marked "reentrant", iterate on their dynarray argument. In particular it is a programming error if the length of the dynarray changes during their execution, and the conversion functions raise `Invalid_argument` if they observe such a change. + +``` +val of_array : 'a array -> 'a t +``` +`of_array arr` returns a dynamic array corresponding to the fixed-sized array `a`. Operates in `O(n)` time by making a copy. + +``` +val to_array : 'a t -> 'a array +``` +`to_array a` returns a fixed-sized array corresponding to the dynamic array `a`. This always allocate a new array and copies elements into it. + +``` +val of_list : 'a list -> 'a t +``` +`of_list l` is the array containing the elements of `l` in the same order. + +``` +val to_list : 'a t -> 'a list +``` +`to_list a` is a list with the elements contained in the array `a`. + +``` +val of_seq : 'a Seq.t -> 'a t +``` +`of_seq seq` is an array containing the same elements as `seq`. + +It traverses `seq` once and will terminate only if `seq` is finite. + +``` +val to_seq : 'a t -> 'a Seq.t +``` +`to_seq a` is the sequence of elements `get a 0`, `get a 1`... `get a (length a - 1)`. + +``` +val to_seq_reentrant : 'a t -> 'a Seq.t +``` +`to_seq_reentrant a` is a reentrant variant of [`to_seq`](./#val-to_seq), in the sense that one may still access its elements after the length of `a` has changed. + +Demanding the `i`\-th element of the resulting sequence (which can happen zero, one or several times) will access the `i`\-th element of `a` at the time of the demand. The sequence stops if `a` has less than `i` elements at this point. + +``` +val to_seq_rev : 'a t -> 'a Seq.t +``` +`to_seq_rev a` is the sequence of elements `get a (l - 1)`, `get a (l - 2)`... `get a 0`, where `l` is `length a` at the time `to_seq_rev` is invoked. + +``` +val to_seq_rev_reentrant : 'a t -> 'a Seq.t +``` +`to_seq_rev_reentrant a` is a reentrant variant of [`to_seq_rev`](./#val-to_seq_rev), in the sense that one may still access its elements after the length of `a` has changed. + +Elements that have been removed from the array by the time they are demanded in the sequence are skipped. + + +## Advanced topics for performance + + +### Backing array, capacity + +Internally, a dynamic array uses a **backing array** (a fixed-size array as provided by the [`Array`](./Stdlib-Array.md) module) whose length is greater or equal to the length of the dynamic array. We define the **capacity** of a dynamic array as the length of its backing array. + +The capacity of a dynamic array is relevant in advanced scenarios, when reasoning about the performance of dynamic array programs: + +- The memory usage of a dynamic array is proportional to its capacity, rather than its length. +- When there is no empty space left at the end of the backing array, adding elements requires allocating a new, larger backing array. +The implementation uses a standard exponential reallocation strategy which guarantees amortized constant-time operation; in particular, the total capacity of all backing arrays allocated over the lifetime of a dynamic array is at worst proportional to the total number of elements added. + +In other words, users need not care about capacity and reallocations, and they will get reasonable behavior by default. However, in some performance-sensitive scenarios the functions below can help control memory usage or guarantee an optimal number of reallocations. + +``` +val capacity : 'a t -> int +``` +`capacity a` is the length of `a`'s backing array. + +``` +val ensure_capacity : 'a t -> int -> unit +``` +`ensure_capacity a n` makes sure that the capacity of `a` is at least `n`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the requested capacity is outside the range 0 .. Sys.max\_array\_length. +An example would be to reimplement [`of_array`](./#val-of_array) without using [`init`](./#val-init): + +```ocaml +let of_array arr = + let a = Dynarray.create () in + Dynarray.ensure_capacity a (Array.length arr); + Array.iter (fun v -> add_last a v) arr +``` +Using `ensure_capacity` guarantees that at most one reallocation will take place, instead of possibly several. + +Without this `ensure_capacity` hint, the number of resizes would be logarithmic in the length of `arr`, creating a constant-factor slowdown noticeable when `arr` is large. + +``` +val ensure_extra_capacity : 'a t -> int -> unit +``` +`ensure_extra_capacity a n` is `ensure_capacity a (length a + n)`, it makes sure that `a` has room for `n` extra items. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the total requested capacity is outside the range 0 .. Sys.max\_array\_length. +A use case would be to implement [`append_array`](./#val-append_array): + +```ocaml +let append_array a arr = + ensure_extra_capacity a (Array.length arr); + Array.iter (fun v -> add_last a v) arr +``` +``` +val fit_capacity : 'a t -> unit +``` +`fit_capacity a` reallocates a backing array if necessary, so that the resulting capacity is exactly `length a`, with no additional empty space at the end. This can be useful to make sure there is no memory wasted on a long-lived array. + +Note that calling `fit_capacity` breaks the amortized complexity guarantees provided by the default reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. + +If you know that a dynamic array has reached its final length, which will remain fixed in the future, it is sufficient to call `to_array` and only keep the resulting fixed-size array. `fit_capacity` is useful when you need to keep a dynamic array for eventual future resizes. + +``` +val set_capacity : 'a t -> int -> unit +``` +`set_capacity a n` reallocates a backing array if necessary, so that the resulting capacity is exactly `n`. In particular, all elements of index `n` or greater are removed. + +Like [`fit_capacity`](./#val-fit_capacity), this function breaks the amortized complexity guarantees provided by the reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. + +This is an advanced function; in particular, [`ensure_capacity`](./#val-ensure_capacity) should be preferred to increase the capacity, as it preserves those amortized guarantees. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. +``` +val reset : 'a t -> unit +``` +`reset a` clears `a` and replaces its backing array by an empty array. + +It is equivalent to `set_capacity a 0` or `clear a; fit_capacity a`. + + +### No leaks: preservation of memory liveness + +The user-provided values reachable from a dynamic array `a` are exactly the elements in the indices `0` to `length a - 1`. In particular, no user-provided values are "leaked" by being present in the backing array at index `length a` or later. + + +## Code examples + + +### Min-heaps for mutable priority queues + +We can use dynamic arrays to implement a mutable priority queue. A priority queue provides a function to add elements, and a function to extract the minimum element \-- according to some comparison function. + +```ocaml +(* We present our priority queues as a functor + parametrized on the comparison function. *) +module Heap (Elem : Map.OrderedType) : sig + type t + val create : unit -> t + val add : t -> Elem.t -> unit + val pop_min : t -> Elem.t option +end = struct + + (* Our priority queues are implemented using the standard "min heap" + data structure, a dynamic array representing a binary tree. *) + type t = Elem.t Dynarray.t + let create = Dynarray.create + + (* The node of index [i] has as children the nodes of index [2 * i + 1] + and [2 * i + 2] -- if they are valid indices in the dynarray. *) + let left_child i = 2 * i + 1 + let right_child i = 2 * i + 2 + let parent_node i = (i - 1) / 2 + + (* We use indexing operators for convenient notations. *) + let ( .!() ) = Dynarray.get + let ( .!()<- ) = Dynarray.set + + (* Auxiliary functions to compare and swap two elements + in the dynamic array. *) + let order h i j = + Elem.compare h.!(i) h.!(j) + + let swap h i j = + let v = h.!(i) in + h.!(i) <- h.!(j); + h.!(j) <- v + + (* We say that a heap respects the "heap ordering" if the value of + each node is smaller than the value of its children. The + algorithm manipulates arrays that respect the heap algorithm, + except for one node whose value may be too small or too large. + + The auxiliary functions [heap_up] and [heap_down] take + such a misplaced value, and move it "up" (respectively: "down") + the tree by permuting it with its parent value (respectively: + a child value) until the heap ordering is restored. *) + + let rec heap_up h i = + if i = 0 then () else + let parent = parent_node i in + if order h i parent < 0 then + (swap h i parent; heap_up h parent) + + and heap_down h ~len i = + let left, right = left_child i, right_child i in + if left >= len then () (* no child, stop *) else + let smallest = + if right >= len then left (* no right child *) else + if order h left right < 0 then left else right + in + if order h i smallest > 0 then + (swap h i smallest; heap_down h ~len smallest) + + let add h s = + let i = Dynarray.length h in + Dynarray.add_last h s; + heap_up h i + + let pop_min h = + if Dynarray.is_empty h then None + else begin + (* Standard trick: swap the 'best' value at index 0 + with the last value of the array. *) + let last = Dynarray.length h - 1 in + swap h 0 last; + (* At this point [pop_last] returns the 'best' value, + and leaves a heap with one misplaced element at index [0]. *) + let best = Dynarray.pop_last h in + (* Restore the heap ordering -- does nothing if the heap is empty. *) + heap_down h ~len:last 0; + Some best + end +end +``` +The production code from which this example was inspired includes logic to free the backing array when the heap becomes empty, only in the case where the capacity is above a certain threshold. This can be done by calling the following function from `pop`: + +```ocaml +let shrink h = + if Dynarray.length h = 0 && Dynarray.capacity h > 1 lsl 18 then + Dynarray.reset h +``` +The `Heap` functor can be used to implement a sorting function, by adding all elements into a priority queue and then extracting them in order. + +```ocaml +let heap_sort (type a) cmp li = + let module Heap = Heap(struct type t = a let compare = cmp end) in + let heap = Heap.create () in + List.iter (Heap.add heap) li; + List.map (fun _ -> Heap.pop_min heap |> Option.get) li +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Either.md b/docs/api/re/melange/Stdlib-Either.md new file mode 100644 index 000000000..444260295 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Either.md @@ -0,0 +1,115 @@ + +# Module `Stdlib.Either` + +Either type. + +Either is the simplest and most generic sum/variant type: a value of `('a, 'b) Either.t` is either a `Left (v : 'a)` or a `Right (v : 'b)`. + +It is a natural choice in the API of generic functions where values could fall in two different cases, possibly at different types, without assigning a specific meaning to what each case should be. + +For example: + +```ocaml +List.partition_map: + ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list +``` +If you are looking for a parametrized type where one alternative means success and the other means failure, you should use the more specific type [`Result.t`](./Stdlib-Result.md#type-t). + +since 4.12 +``` +type ('a, 'b) t = +``` +``` +| Left of 'a +``` +``` +| Right of 'b +``` +``` + +``` +A value of `('a, 'b) Either.t` contains either a value of `'a` or a value of `'b` + +``` +val left : 'a -> ('a, 'b) t +``` +`left v` is `Left v`. + +``` +val right : 'b -> ('a, 'b) t +``` +`right v` is `Right v`. + +``` +val is_left : ('a, 'b) t -> bool +``` +`is_left (Left v)` is `true`, `is_left (Right v)` is `false`. + +``` +val is_right : ('a, 'b) t -> bool +``` +`is_right (Left v)` is `false`, `is_right (Right v)` is `true`. + +``` +val find_left : ('a, 'b) t -> 'a option +``` +`find_left (Left v)` is `Some v`, `find_left (Right _)` is `None` + +``` +val find_right : ('a, 'b) t -> 'b option +``` +`find_right (Right v)` is `Some v`, `find_right (Left _)` is `None` + +``` +val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t +``` +`map_left f e` is `Left (f v)` if `e` is `Left v` and `e` if `e` is `Right _`. + +``` +val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t +``` +`map_right f e` is `Right (f v)` if `e` is `Right v` and `e` if `e` is `Left _`. + +``` +val map : + left:('a1 -> 'a2) -> + right:('b1 -> 'b2) -> + ('a1, 'b1) t -> + ('a2, 'b2) t +``` +`map ~left ~right (Left v)` is `Left (left v)`, `map ~left ~right (Right v)` is `Right (right v)`. + +``` +val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c +``` +`fold ~left ~right (Left v)` is `left v`, and `fold ~left ~right (Right v)` is `right v`. + +``` +val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit +``` +`iter ~left ~right (Left v)` is `left v`, and `iter ~left ~right (Right v)` is `right v`. + +``` +val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool +``` +`for_all ~left ~right (Left v)` is `left v`, and `for_all ~left ~right (Right v)` is `right v`. + +``` +val equal : + left:('a -> 'a -> bool) -> + right:('b -> 'b -> bool) -> + ('a, 'b) t -> + ('a, 'b) t -> + bool +``` +`equal ~left ~right e0 e1` tests equality of `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. + +``` +val compare : + left:('a -> 'a -> int) -> + right:('b -> 'b -> int) -> + ('a, 'b) t -> + ('a, 'b) t -> + int +``` +`compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _ ` and `Right _`. `Left _` values are smaller than `Right _` values. diff --git a/docs/api/re/melange/Stdlib-Filename.md b/docs/api/re/melange/Stdlib-Filename.md new file mode 100644 index 000000000..f56fdfaec --- /dev/null +++ b/docs/api/re/melange/Stdlib-Filename.md @@ -0,0 +1,167 @@ + +# Module `Stdlib.Filename` + +Operations on file names. + +``` +val current_dir_name : string +``` +The conventional name for the current directory (e.g. `.` in Unix). + +``` +val parent_dir_name : string +``` +The conventional name for the parent of the current directory (e.g. `..` in Unix). + +``` +val dir_sep : string +``` +The directory separator (e.g. `/` in Unix). + +since 3.11.2 +``` +val concat : string -> string -> string +``` +`concat dir file` returns a file name that designates file `file` in directory `dir`. + +``` +val is_relative : string -> bool +``` +Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. in Unix, starts with `/`). + +``` +val is_implicit : string -> bool +``` +Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory. + +``` +val check_suffix : string -> string -> bool +``` +`check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`. + +Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. + +``` +val chop_suffix : string -> string -> string +``` +`chop_suffix name suff` removes the suffix `suff` from the filename `name`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if name does not end with the suffix suff. +``` +val chop_suffix_opt : suffix:string -> string -> string option +``` +`chop_suffix_opt ~suffix filename` removes the suffix from the `filename` if possible, or returns `None` if the filename does not end with the suffix. + +Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. + +since 4.08 +``` +val extension : string -> string +``` +`extension name` is the shortest suffix `ext` of `name0` where: + +- `name0` is the longest suffix of `name` that does not contain a directory separator; +- `ext` starts with a period; +- `ext` is preceded by at least one non-period character in `name0`. +If such a suffix does not exist, `extension name` is the empty string. + +since 4.04 +``` +val remove_extension : string -> string +``` +Return the given file name without its extension, as defined in [`Filename.extension`](./#val-extension). If the extension is empty, the function returns the given file name. + +The following invariant holds for any file name `s`: + +`remove_extension s ^ extension s = s` + +since 4.04 +``` +val chop_extension : string -> string +``` +Same as [`Filename.remove_extension`](./#val-remove_extension), but raise `Invalid_argument` if the given name has an empty extension. + +``` +val basename : string -> string +``` +Split a file name into directory name / base file name. If `name` is a valid file name, then `concat (dirname name) (basename name)` returns a file name which is equivalent to `name`. Moreover, after setting the current directory to `dirname name` (with [`Sys.chdir`](./Stdlib-Sys.md#val-chdir)), references to `basename name` (which is a relative file name) designate the same file as `name` before the call to [`Sys.chdir`](./Stdlib-Sys.md#val-chdir). + +This function conforms to the specification of POSIX.1-2008 for the `basename` utility. + +``` +val dirname : string -> string +``` +See [`Filename.basename`](./#val-basename). This function conforms to the specification of POSIX.1-2008 for the `dirname` utility. + +``` +val null : string +``` +`null` is `"/dev/null"` on POSIX and `"NUL"` on Windows. It represents a file on the OS that discards all writes and returns end of file on reads. + +since 4.10 +``` +val temp_file : ?temp_dir:string -> string -> string -> string +``` +`temp_file prefix suffix` returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary file is created empty, with permissions `0o600` (readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when `temp_file` was called. + +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be created. +before 3.11.2 no ?temp\_dir optional argument +``` +val open_temp_file : + ?mode:open_flag list -> + ?perms:int -> + ?temp_dir:string -> + string -> + string -> + string * out_channel +``` +Same as [`Filename.temp_file`](./#val-temp_file), but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than `temp_file`: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument `mode` is a list of additional flags to control the opening of the file. It can contain one or several of `Open_append`, `Open_binary`, and `Open_text`. The default is `[Open_text]` (open in text mode). The file is created with permissions `perms` (defaults to readable and writable only by the file owner, `0o600`). + +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be opened. +before 4.03 no ?perms optional argument +before 3.11.2 no ?temp\_dir optional argument +``` +val temp_dir : ?temp_dir:string -> ?perms:int -> string -> string -> string +``` +`temp_dir prefix suffix` creates and returns the name of a fresh temporary directory with permissions `perms` (defaults to 0o700) inside `temp_dir`. The base name of the temporary directory is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary directory is created empty, with permissions `0o700` (readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when `temp_dir` was called. + +If temp\_dir does not exist, this function does not create it. Instead, it raises Sys\_error. + +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the directory could not be created. +since 5.1 +``` +val get_temp_dir_name : unit -> string +``` +The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the `TEMP` environment variable, or "." if the variable is not set. The temporary directory can be changed with [`Filename.set_temp_dir_name`](./#val-set_temp_dir_name). + +since 4.00 +``` +val set_temp_dir_name : string -> unit +``` +Change the temporary directory returned by [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name) and used by [`Filename.temp_file`](./#val-temp_file) and [`Filename.open_temp_file`](./#val-open_temp_file). The temporary directory is a domain-local value which is inherited by child domains. + +since 4.00 +``` +val quote : string -> string +``` +Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions. + +``` +val quote_command : + string -> + ?stdin:string -> + ?stdout:string -> + ?stderr:string -> + string list -> + string +``` +`quote_command cmd args` returns a quoted command line, suitable for use as an argument to [`Sys.command`](./Stdlib-Sys.md#val-command), `Unix.system`, and the `Unix.open_process` functions. + +The string `cmd` is the command to call. The list `args` is the list of arguments to pass to this command. It can be empty. + +The optional arguments `?stdin` and `?stdout` and `?stderr` are file names used to redirect the standard input, the standard output, or the standard error of the command. If `~stdin:f` is given, a redirection `< f` is performed and the standard input of the command reads from file `f`. If `~stdout:f` is given, a redirection `> f` is performed and the standard output of the command is written to file `f`. If `~stderr:f` is given, a redirection `2> f` is performed and the standard error of the command is written to file `f`. If both `~stdout:f` and `~stderr:f` are given, with the exact same file name `f`, a `2>&1` redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file `f`. + +Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using [`Filename.quote`](./#val-quote), then concatenated. Under Win32, additional quoting is performed as required by the `cmd.exe` shell that is called by [`Sys.command`](./Stdlib-Sys.md#val-command). + +raises [`Failure`](./Stdlib.md#exception-Failure) if the command cannot be escaped on the current platform. +since 4.10 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Float-Array.md b/docs/api/re/melange/Stdlib-Float-Array.md new file mode 100644 index 000000000..99c3234de --- /dev/null +++ b/docs/api/re/melange/Stdlib-Float-Array.md @@ -0,0 +1,330 @@ + +# Module `Float.Array` + +Float arrays with packed representation. + +``` +type t = floatarray +``` +The type of float arrays with packed representation. + +since 4.08 +``` +val length : t -> int +``` +Return the length (number of elements) of the given floatarray. + +``` +val get : t -> int -> float +``` +`get a n` returns the element number `n` of floatarray `a`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val set : t -> int -> float -> unit +``` +`set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). +``` +val make : int -> float -> t +``` +`make n x` returns a fresh floatarray of length `n`, initialized with `x`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. +``` +val create : int -> t +``` +`create n` returns a fresh floatarray of length `n`, with uninitialized data. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. +``` +val init : int -> (int -> float) -> t +``` +`init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers `0` to `n-1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. +``` +val make_matrix : int -> int -> float -> t array +``` +`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where all elements are initialized with `e`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. +since 5.2 +``` +val init_matrix : int -> int -> (int -> int -> float) -> t array +``` +`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. +since 5.2 +``` +val append : t -> t -> t +``` +`append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_floatarray\_length. +``` +val concat : t list -> t +``` +Same as [`append`](./#val-append), but concatenates a list of floatarrays. + +``` +val sub : t -> int -> int -> t +``` +`sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. +``` +val copy : t -> t +``` +`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`. + +``` +val fill : t -> int -> int -> float -> unit +``` +`fill a pos len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. +``` +val blit : t -> int -> t -> int -> int -> unit +``` +`blit src src_pos dst dst_pos len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. +``` +val to_list : t -> float list +``` +`to_list a` returns the list of all the elements of `a`. + +``` +val of_list : float list -> t +``` +`of_list l` returns a fresh floatarray containing the elements of `l`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_floatarray\_length. + +## Iterators + +``` +val iter : (float -> unit) -> t -> unit +``` +`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. + +``` +val iteri : (int -> float -> unit) -> t -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied with the index of the element as first argument, and the element itself as second argument. + +``` +val map : (float -> float) -> t -> t +``` +`map f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. + +``` +val map_inplace : (float -> float) -> t -> unit +``` +`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. + +since 5.1 +``` +val mapi : (int -> float -> float) -> t -> t +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +``` +val mapi_inplace : (int -> float -> float) -> t -> unit +``` +Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. + +since 5.1 +``` +val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc +``` +`fold_left f x init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`. + +``` +val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`. + + +## Iterators on two arrays + +``` +val iter2 : (float -> float -> unit) -> t -> t -> unit +``` +`Array.iter2 f a b` applies function `f` to all the elements of `a` and `b`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. +``` +val map2 : (float -> float -> float) -> t -> t -> t +``` +`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. + +## Array scanning + +``` +val for_all : (float -> bool) -> t -> bool +``` +`for_all f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. + +``` +val exists : (float -> bool) -> t -> bool +``` +`exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. + +``` +val mem : float -> t -> bool +``` +`mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`. + +``` +val mem_ieee : float -> t -> bool +``` +Same as [`mem`](./#val-mem), but uses IEEE equality instead of structural equality. + + +## Array searching + +``` +val find_opt : (float -> bool) -> t -> float option +``` +``` +val find_index : (float -> bool) -> t -> int option +``` +`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. + +It returns `None` if there is no such element. + +since 5.1 +``` +val find_map : (float -> 'a option) -> t -> 'a option +``` +``` +val find_mapi : (int -> float -> 'a option) -> t -> 'a option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 5.1 + +## Sorting and shuffling + +``` +val sort : (float -> float -> int) -> t -> unit +``` +Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. + +The current implementation uses Heap Sort. It runs in constant stack space. + +Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : + +- `cmp x y` \> 0 if and only if `cmp y x` \< 0 +- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 +When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : + +- `cmp a.(i) a.(j)` \>= 0 if i \>= j +``` +val stable_sort : (float -> float -> int) -> t -> unit +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. + +The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of [`sort`](./#val-sort). + +``` +val fast_sort : (float -> float -> int) -> t -> unit +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + +``` +val shuffle : rand:(int -> int) -> t -> unit +``` +`shuffle rand a` randomly permutes `a`'s elements using `rand` for randomness. The distribution of permutations is uniform. + +`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). + +since 5.2 + +## Float arrays and Sequences + +``` +val to_seq : t -> float Seq.t +``` +Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence. + +``` +val to_seqi : t -> (int * float) Seq.t +``` +Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence. + +``` +val of_seq : float Seq.t -> t +``` +Create an array from the generator. + +``` +val map_to_array : (float -> 'a) -> t -> 'a array +``` +`map_to_array f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. + +``` +val map_from_array : ('a -> float) -> 'a array -> t +``` +`map_from_array f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. + + +## Arrays and concurrency safety + +Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. + + +### Atomicity + +Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. + +For example, consider the following program: + +```ocaml +let size = 100_000_000 +let a = Float.Array.make size 1. +let update a f () = + Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a +let d1 = Domain.spawn (update a (fun x -> x +. 1.)) +let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.)) +let () = Domain.join d1; Domain.join d2 +``` +After executing this code, each field of the float array `a` is either `2.`, `3.`, `4.` or `5.`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +### Data races + +If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. + +A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. + +Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. + +Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions. + + +### Tearing + +Float arrays have two supplementary caveats in the presence of data races. + +First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. + +For instance, at the end of + +```ocaml +let zeros = Float.Array.make size 0. +let max_floats = Float.Array.make size Float.max_float +let res = Float.Array.copy zeros +let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size) +let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size) +let () = Domain.join d1; Domain.join d2 +``` +the `res` float array might contain values that are neither `0.` nor `max_float`. + +Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/re/melange/Stdlib-Float.md b/docs/api/re/melange/Stdlib-Float.md new file mode 100644 index 000000000..29ecfd718 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Float.md @@ -0,0 +1,482 @@ + +# Module `Stdlib.Float` + +Floating-point arithmetic. + +OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... + +since 4.07 +``` +val zero : float +``` +The floating point 0. + +since 4.08 +``` +val one : float +``` +The floating-point 1\. + +since 4.08 +``` +val minus_one : float +``` +The floating-point \-1. + +since 4.08 +``` +val neg : float -> float +``` +Unary negation. + +``` +val add : float -> float -> float +``` +Floating-point addition. + +``` +val sub : float -> float -> float +``` +Floating-point subtraction. + +``` +val mul : float -> float -> float +``` +Floating-point multiplication. + +``` +val div : float -> float -> float +``` +Floating-point division. + +``` +val fma : float -> float -> float -> float +``` +`fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation. + +On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters. + +since 4.08 +``` +val rem : float -> float -> float +``` +`rem a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. + +``` +val succ : float -> float +``` +`succ x` returns the floating point number right after `x` i.e., the smallest floating-point number greater than `x`. See also [`next_after`](./#val-next_after). + +since 4.08 +``` +val pred : float -> float +``` +`pred x` returns the floating-point number right before `x` i.e., the greatest floating-point number smaller than `x`. See also [`next_after`](./#val-next_after). + +since 4.08 +``` +val abs : float -> float +``` +`abs f` returns the absolute value of `f`. + +``` +val infinity : float +``` +Positive infinity. + +``` +val neg_infinity : float +``` +Negative infinity. + +``` +val nan : float +``` +A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. Stands for 'not a number'. Any floating-point operation with `nan` as argument returns `nan` as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, `=`, `<`, `<=`, `>` and `>=` return `false` and `<>` returns `true` if one or both of their arguments is `nan`. + +`nan` is `quiet_nan` since 5.1; it was a signaling NaN before. + +``` +val signaling_nan : float +``` +Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries. + +since 5.1 +``` +val quiet_nan : float +``` +Quiet NaN. + +since 5.1 +``` +val pi : float +``` +The constant pi. + +``` +val max_float : float +``` +The largest positive finite value of type `float`. + +``` +val min_float : float +``` +The smallest positive, non-zero, non-denormalized value of type `float`. + +``` +val epsilon : float +``` +The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. + +``` +val is_finite : float -> bool +``` +`is_finite x` is `true` if and only if `x` is finite i.e., not infinite and not [`nan`](./#val-nan). + +since 4.08 +``` +val is_infinite : float -> bool +``` +`is_infinite x` is `true` if and only if `x` is [`infinity`](./#val-infinity) or [`neg_infinity`](./#val-neg_infinity). + +since 4.08 +``` +val is_nan : float -> bool +``` +`is_nan x` is `true` if and only if `x` is not a number (see [`nan`](./#val-nan)). + +since 4.08 +``` +val is_integer : float -> bool +``` +`is_integer x` is `true` if and only if `x` is an integer. + +since 4.08 +``` +val of_int : int -> float +``` +Convert an integer to floating-point. + +``` +val to_int : float -> int +``` +Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. + +``` +val of_string : string -> float +``` +Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The `_` (underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of a float. +``` +val of_string_opt : string -> float option +``` +Same as `of_string`, but returns `None` instead of raising. + +``` +val to_string : float -> string +``` +Return a string representation of a floating-point number. + +This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). + +This function is an alias for [`Stdlib.string_of_float`](./Stdlib.md#val-string_of_float). + +``` +type fpclass = fpclass = +``` +``` +| FP_normal +``` +Normal number, none of the below + +``` +| FP_subnormal +``` +Number very close to 0.0, has reduced precision + +``` +| FP_zero +``` +Number is 0.0 or \-0.0 + +``` +| FP_infinite +``` +Number is positive or negative infinity + +``` +| FP_nan +``` +Not a number: result of an undefined operation + +``` + +``` +The five classes of floating-point numbers, as determined by the [`classify_float`](./#val-classify_float) function. + +``` +val classify_float : float -> fpclass +``` +Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number. + +``` +val pow : float -> float -> float +``` +Exponentiation. + +``` +val sqrt : float -> float +``` +Square root. + +``` +val cbrt : float -> float +``` +Cube root. + +since 4.13 +``` +val exp : float -> float +``` +Exponential. + +``` +val exp2 : float -> float +``` +Base 2 exponential function. + +since 4.13 +``` +val log : float -> float +``` +Natural logarithm. + +``` +val log10 : float -> float +``` +Base 10 logarithm. + +``` +val log2 : float -> float +``` +Base 2 logarithm. + +since 4.13 +``` +val expm1 : float -> float +``` +`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. + +``` +val log1p : float -> float +``` +`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. + +``` +val cos : float -> float +``` +Cosine. Argument is in radians. + +``` +val sin : float -> float +``` +Sine. Argument is in radians. + +``` +val tan : float -> float +``` +Tangent. Argument is in radians. + +``` +val acos : float -> float +``` +Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. + +``` +val asin : float -> float +``` +Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. + +``` +val atan : float -> float +``` +Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. + +``` +val atan2 : float -> float -> float +``` +`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. + +``` +val hypot : float -> float -> float +``` +`hypot x y` returns `sqrt(x *. x +. y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. If one of `x` or `y` is infinite, returns `infinity` even if the other is `nan`. + +``` +val cosh : float -> float +``` +Hyperbolic cosine. Argument is in radians. + +``` +val sinh : float -> float +``` +Hyperbolic sine. Argument is in radians. + +``` +val tanh : float -> float +``` +Hyperbolic tangent. Argument is in radians. + +``` +val acosh : float -> float +``` +Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. + +since 4.13 +``` +val asinh : float -> float +``` +Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. + +since 4.13 +``` +val atanh : float -> float +``` +Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. + +since 4.13 +``` +val erf : float -> float +``` +Error function. The argument ranges over the entire real line. The result is always within `[-1.0, 1.0]`. + +since 4.13 +``` +val erfc : float -> float +``` +Complementary error function (`erfc x = 1 - erf x`). The argument ranges over the entire real line. The result is always within `[0.0, 2.0]`. + +since 4.13 +``` +val trunc : float -> float +``` +`trunc x` rounds `x` to the nearest integer whose absolute value is less than or equal to `x`. + +since 4.08 +``` +val round : float -> float +``` +`round x` rounds `x` to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If `x` is an integer, `+0.`, `-0.`, `nan`, or infinite, `x` itself is returned. + +On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform. + +since 4.08 +``` +val ceil : float -> float +``` +Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. + +``` +val floor : float -> float +``` +Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. + +``` +val next_after : float -> float -> float +``` +`next_after x y` returns the next representable floating-point value following `x` in the direction of `y`. More precisely, if `y` is greater (resp. less) than `x`, it returns the smallest (resp. largest) representable number greater (resp. less) than `x`. If `x` equals `y`, the function returns `y`. If `x` or `y` is `nan`, a `nan` is returned. Note that `next_after max_float infinity = infinity` and that `next_after 0. infinity` is the smallest denormalized positive number. If `x` is the smallest denormalized positive number, `next_after x 0. = 0.` + +since 4.08 +``` +val copy_sign : float -> float -> float +``` +`copy_sign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. + +``` +val sign_bit : float -> bool +``` +`sign_bit x` is `true` if and only if the sign bit of `x` is set. For example `sign_bit 1.` and `signbit 0.` are `false` while `sign_bit (-1.)` and `sign_bit (-0.)` are `true`. + +since 4.08 +``` +val frexp : float -> float * int +``` +`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. + +``` +val ldexp : float -> int -> float +``` +`ldexp x n` returns `x *. 2 ** n`. + +``` +val modf : float -> float * float +``` +`modf f` returns the pair of the fractional and integral part of `f`. + +``` +type t = float +``` +An alias for the type of floating-point numbers. + +``` +val compare : t -> t -> int +``` +`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. + +``` +val equal : t -> t -> bool +``` +The equal function for floating-point numbers, compared using [`compare`](./#val-compare). + +``` +val min : t -> t -> t +``` +`min x y` returns the minimum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `min (-0.) (+0.) = -0.` + +since 4.08 +``` +val max : float -> float -> float +``` +`max x y` returns the maximum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `max (-0.) (+0.) = +0.` + +since 4.08 +``` +val min_max : float -> float -> float * float +``` +`min_max x y` is `(min x y, max x y)`, just more efficient. + +since 4.08 +``` +val min_num : t -> t -> t +``` +`min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `min_num (-0.) (+0.) = -0.` + +since 4.08 +``` +val max_num : t -> t -> t +``` +`max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan` `nan` is returned. Moreover `max_num (-0.) (+0.) = +0.` + +since 4.08 +``` +val min_max_num : float -> float -> float * float +``` +`min_max_num x y` is `(min_num x y, max_num x y)`, just more efficient. Note that in particular `min_max_num x nan = (x, x)` and `min_max_num nan y = (y, y)`. + +since 4.08 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for floats, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for floats, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +``` +module Array : sig ... end +``` +Float arrays with packed representation. diff --git a/docs/api/re/melange/Stdlib-Format.md b/docs/api/re/melange/Stdlib-Format.md new file mode 100644 index 000000000..92440e239 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Format.md @@ -0,0 +1,1401 @@ + +# Module `Stdlib.Format` + +Pretty-printing. + +If you are new to this module, see the [examples](./#examples) below. + +This module implements a pretty-printing facility to format values within ['pretty-printing boxes'](./#boxes) and ['semantic tags'](./#tags) combined with a set of [printf-like functions](./#fpp). The pretty-printer splits lines at specified [break hints](./#breaks), and indents lines according to the box structure. Similarly, [semantic tags](./#tags) can be used to decouple text presentation from its contents. + +This pretty-printing facility is implemented as an overlay on top of abstract [formatters](./#formatter) which provide basic output functions. Some formatters are predefined, notably: + +- [`std_formatter`](./#val-std_formatter) outputs to [stdout](./Stdlib.md#val-stdout) +- [`err_formatter`](./#val-err_formatter) outputs to [stderr](./Stdlib.md#val-stderr) +Most functions in the [`Format`](#) module come in two variants: a short version that operates on the current domain's standard formatter as obtained using [`get_std_formatter`](./#val-get_std_formatter) and the generic version prefixed by `pp_` that takes a formatter as its first argument. For the version that operates on the current domain's standard formatter, the call to [`get_std_formatter`](./#val-get_std_formatter) is delayed until the last argument is received. + +More formatters can be created with [`formatter_of_out_channel`](./#val-formatter_of_out_channel), [`formatter_of_buffer`](./#val-formatter_of_buffer), [`formatter_of_symbolic_output_buffer`](./#val-formatter_of_symbolic_output_buffer) or using [custom formatters](./#formatter). + +**Warning**: Since [formatters](./#formatter) contain mutable state, it is not thread-safe to use the same formatter on multiple domains in parallel without synchronization. + +If multiple domains write to the same output channel using the predefined formatters (as obtained by [`get_std_formatter`](./#val-get_std_formatter) or [`get_err_formatter`](./#val-get_err_formatter)), the output from the domains will be interleaved with each other at points where the formatters are flushed, such as with [`print_flush`](./#val-print_flush). This synchronization is not performed by formatters obtained from [`formatter_of_out_channel`](./#val-formatter_of_out_channel) (on the standard out channels or others). + + +## Introduction + +You may consider this module as providing an extension to the `printf` facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular `printf` format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function [`Format.fprintf`](./#val-fprintf). + +You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise `fprintf` format strings. + +For instance, the sequence `open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()` that prints `x = 1` within a pretty-printing box, can be abbreviated as `printf "@[%s@ %i@]@." "x =" 1`, or even shorter `printf "@[x =@ %i@]@." 1`. + +Rule of thumb for casual users of this library: + +- use simple pretty-printing boxes (as obtained by `open_box 0`); +- use simple break hints as obtained by `print_cut ()` that outputs a simple break hint, or by `print_space ()` that outputs a space indicating a break hint; +- once a pretty-printing box is open, display its material with basic printing functions (e. g. `print_int` and `print_string`); +- when the material for a pretty-printing box has been printed, call `close_box ()` to close the box; +- at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate `print_newline ()`. +The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the `open_` functions below must be closed using `close_box` for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. + +In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer. + +Warning: mixing calls to pretty-printing functions of this module with calls to [`Stdlib`](./Stdlib.md) low level output functions is error prone. + +The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, ` Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT"; ` leads to output `<>PRETTYTEXT`. + + +## Formatters + +``` +type formatter +``` +Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also [Defining formatters](./#formatter). + + +## Pretty-printing boxes + +The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer. + +Each different pretty-printing box kind introduces a specific line splitting policy: + +- within an *horizontal* box, break hints never split the line (but the line may be split in a box nested deeper), +- within a *vertical* box, break hints always split the line, +- within an *horizontal/vertical* box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line, +- within a *compacting* box, a break hint never splits the line, unless there is no more room on the current line. +Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line. + +Moreover, opening a box after the [maximum indentation limit](./#maxindent) splits the line whether or not the box would end up fitting on the line. + +``` +val pp_open_box : formatter -> int -> unit +``` +``` +val open_box : int -> unit +``` +`pp_open_box ppf d` opens a new compacting pretty-printing box with offset `d` in the formatter `ppf`. + +Within this box, the pretty-printer prints as much as possible material on every line. + +A break hint splits the line if there is no more room on the line to print the remainder of the box. + +Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting \``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line). + +This box is the general purpose pretty-printing box. + +If the pretty-printer splits the line in the box, offset `d` is added to the current indentation. + +``` +val pp_close_box : formatter -> unit -> unit +``` +``` +val close_box : unit -> unit +``` +Closes the most recently open pretty-printing box. + +``` +val pp_open_hbox : formatter -> unit -> unit +``` +``` +val open_hbox : unit -> unit +``` +`pp_open_hbox ppf ()` opens a new 'horizontal' pretty-printing box. + +This box prints material on a single line. + +Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper). + +``` +val pp_open_vbox : formatter -> int -> unit +``` +``` +val open_vbox : int -> unit +``` +`pp_open_vbox ppf d` opens a new 'vertical' pretty-printing box with offset `d`. + +This box prints material on as many lines as break hints in the box. + +Every break hint in a vertical box splits the line. + +If the pretty-printer splits the line in the box, `d` is added to the current indentation. + +``` +val pp_open_hvbox : formatter -> int -> unit +``` +``` +val open_hvbox : int -> unit +``` +`pp_open_hvbox ppf d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`. + +This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box. + +If the pretty-printer splits the line in the box, `d` is added to the current indentation. + +``` +val pp_open_hovbox : formatter -> int -> unit +``` +``` +val open_hovbox : int -> unit +``` +`pp_open_hovbox ppf d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`. + +This box prints material as much as possible on every line. + +A break hint splits the line if there is no more room on the line to print the remainder of the box. + +If the pretty-printer splits the line in the box, `d` is added to the current indentation. + + +## Formatting functions + +``` +val pp_print_string : formatter -> string -> unit +``` +``` +val print_string : string -> unit +``` +`pp_print_string ppf s` prints `s` in the current pretty-printing box. + +``` +val pp_print_substring : pos:int -> len:int -> formatter -> string -> unit +``` +``` +val print_substring : pos:int -> len:int -> string -> unit +``` +`pp_print_substring ~pos ~len ppf s` prints the substring of `s` that starts at position `pos` and stops at position `pos+len` in the current pretty-printing box. + +since 5.3 +``` +val pp_print_bytes : formatter -> bytes -> unit +``` +``` +val print_bytes : bytes -> unit +``` +`pp_print_bytes ppf b` prints `b` in the current pretty-printing box. + +since 4.13 +``` +val pp_print_as : formatter -> int -> string -> unit +``` +``` +val print_as : int -> string -> unit +``` +`pp_print_as ppf len s` prints `s` in the current pretty-printing box. The pretty-printer formats `s` as if it were of length `len`. + +``` +val pp_print_substring_as : + pos:int -> + len:int -> + formatter -> + int -> + string -> + unit +``` +``` +val print_substring_as : pos:int -> len:int -> int -> string -> unit +``` +`pp_print_substring_as ~first ~len ppf len_as s` prints the substring of `s` that starts at position `pos` and stop at position `pos+len` in the current pretty-printing box as if it were of length `len_as`. + +since 5.1 +``` +val pp_print_int : formatter -> int -> unit +``` +``` +val print_int : int -> unit +``` +Print an integer in the current pretty-printing box. + +``` +val pp_print_float : formatter -> float -> unit +``` +``` +val print_float : float -> unit +``` +Print a floating point number in the current pretty-printing box. + +``` +val pp_print_char : formatter -> char -> unit +``` +``` +val print_char : char -> unit +``` +Print a character in the current pretty-printing box. + +``` +val pp_print_bool : formatter -> bool -> unit +``` +``` +val print_bool : bool -> unit +``` +Print a boolean in the current pretty-printing box. + +``` +val pp_print_nothing : formatter -> unit -> unit +``` +Print nothing. + +since 5.2 + +## Break hints + +A 'break hint' tells the pretty-printer to output some space or split the line whichever way is more appropriate to the current pretty-printing box splitting rules. + +Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items. + +Simple break hints are: + +- the 'space': output a space or split the line if appropriate, +- the 'cut': split the line if appropriate. +Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, \``output a space'' simply means printing a space character (ASCII code 32) and \``split the line'' means printing a newline character (ASCII code 10). + +``` +val pp_print_space : formatter -> unit -> unit +``` +``` +val print_space : unit -> unit +``` +`pp_print_space ppf ()` emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space. + +`pp_print_space ppf ()` is equivalent to `pp_print_break ppf 1 0`. + +``` +val pp_print_cut : formatter -> unit -> unit +``` +``` +val print_cut : unit -> unit +``` +`pp_print_cut ppf ()` emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing. + +`pp_print_cut ppf ()` is equivalent to `pp_print_break ppf 0 0`. + +``` +val pp_print_break : formatter -> int -> int -> unit +``` +``` +val print_break : int -> int -> unit +``` +`pp_print_break ppf nspaces offset` emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints `nspaces` spaces. + +If the pretty-printer splits the line, `offset` is added to the current indentation. + +``` +val pp_print_custom_break : + formatter -> + fits:(string * int * string) -> + breaks:(string * int * string) -> + unit +``` +`pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4)` emits a custom break hint: the pretty-printer may split the line at this point. + +If it does not split the line, then the `s1` is emitted, then `n` spaces, then `s2`. + +If it splits the line, then it emits the `s3` string, then an indent (according to the box rules), then an offset of `m` spaces, then the `s4` string. + +While `n` and `m` are handled by `formatter_out_functions.out_indent`, the strings will be handled by `formatter_out_functions.out_string`. This allows for a custom formatter that handles indentation distinctly, for example, outputs `
` tags or ` ` entities. + +The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list ` [a; b; c] `, you might want to add a trailing semicolon when it is printed vertically: + +```ocaml +[ + a; + b; + c; +] +``` +You can do this as follows: + +```ocaml +printf "@[[@;<0 2>@[a;@,b;@,c@]%t]@]@\n" + (pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, "")) +``` +since 4.08 +``` +val pp_force_newline : formatter -> unit -> unit +``` +``` +val force_newline : unit -> unit +``` +Force a new line in the current pretty-printing box. + +The pretty-printer must split the line at this point, + +Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative. + +``` +val pp_print_if_newline : formatter -> unit -> unit +``` +``` +val print_if_newline : unit -> unit +``` +Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. + + +## Pretty-printing termination + +``` +val pp_print_flush : formatter -> unit -> unit +``` +``` +val print_flush : unit -> unit +``` +End of pretty-printing: resets the pretty-printer to initial state. + +All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed. + +Note: never use `print_flush` in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering. + +Only consider using `print_flush` when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing. + +Warning: If the output device of the pretty-printer is an output channel, repeated calls to `print_flush` means repeated calls to [`Stdlib.flush`](./Stdlib.md#val-flush) to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency. + +``` +val pp_print_newline : formatter -> unit -> unit +``` +``` +val print_newline : unit -> unit +``` +End of pretty-printing: resets the pretty-printer to initial state. + +All open pretty-printing boxes are closed, all pending text is printed. + +Equivalent to [`print_flush`](./#val-print_flush) with a new line emitted on the pretty-printer low-level output device immediately before the device is flushed. See corresponding words of caution for [`print_flush`](./#val-print_flush). + +Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box. + + +## Margin + +``` +val pp_infinity : int +``` +`pp_infinity` is the maximal size of the margin. Its exact value is implementation dependent but is guaranteed to be greater than 109. + +since 5.2 +``` +val pp_set_margin : formatter -> int -> unit +``` +``` +val set_margin : int -> unit +``` +`pp_set_margin ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to `d` means that the formatting engine aims at printing at most `d-1` characters per line. Nothing happens if `d` is smaller than 2. If `d >= `[`pp_infinity`](./#val-pp_infinity), the right margin is set to [`pp_infinity`](./#val-pp_infinity)` - 1`. If `d` is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio `max_indent/margin>=50%` and if possible the current difference `margin - max_indent`. + +See also [`pp_set_geometry`](./#val-pp_set_geometry). + +``` +val pp_get_margin : formatter -> unit -> int +``` +``` +val get_margin : unit -> int +``` +Returns the position of the right margin. + + +## Maximum indentation limit + +``` +val pp_set_max_indent : formatter -> int -> unit +``` +``` +val set_max_indent : int -> unit +``` +`pp_set_max_indent ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration, + +```ocaml + set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." +``` +yields + +```ocaml + 123456 + 789A +``` +because the nested box `"@[7@]"` is opened after the maximum indentation limit (`7>5`) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line: + +```ocaml + printf "@[123456@[7@]89@]@." +``` +or opening an intermediary box before the maximum indentation limit which fits on the current line + +```ocaml + printf "@[123@[456@[7@]89@]A@]@." +``` +avoids the rejection to the left of the inner boxes and print respectively `"123456789"` and `"123456789A"` . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to `margin - 1`. Note that setting the maximum indentation limit to `margin` is invalid. + +Nothing happens if `d` is smaller than 2. + +If `d` is greater than the current margin, it is ignored, and the current maximum indentation limit is kept. + +See also [`pp_set_geometry`](./#val-pp_set_geometry). + +``` +val pp_get_max_indent : formatter -> unit -> int +``` +``` +val get_max_indent : unit -> int +``` +Return the maximum indentation limit (in characters). + + +## Geometry + +Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maximum indentation limit. + +``` +type geometry = { +``` +`max_indent : int;` +`margin : int;` +``` +} +``` +since 4.08 +``` +val check_geometry : geometry -> bool +``` +Check if the formatter geometry is valid: `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity) + +since 4.08 +``` +val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit +``` +``` +val set_geometry : max_indent:int -> margin:int -> unit +``` +``` +val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit +``` +``` +val safe_set_geometry : max_indent:int -> margin:int -> unit +``` +`pp_set_geometry ppf ~max_indent ~margin` sets both the margin and maximum indentation limit for `ppf`. + +When `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity), `pp_set_geometry ppf ~max_indent ~margin` is equivalent to `pp_set_margin ppf margin; pp_set_max_indent ppf max_indent`; and avoids the subtly incorrect `pp_set_max_indent ppf max_indent; pp_set_margin ppf margin`; + +Outside of this domain, `pp_set_geometry` raises an invalid argument exception whereas `pp_safe_set_geometry` does nothing. + +since 4.08 +``` +val pp_update_geometry : formatter -> (geometry -> geometry) -> unit +``` +`pp_update_geometry ppf (fun geo -> { geo with ... })` lets you update a formatter's geometry in a way that is robust to extension of the `geometry` record with new fields. + +Raises an invalid argument exception if the returned geometry does not satisfy [`check_geometry`](./#val-check_geometry). + +since 4.11 +``` +val update_geometry : (geometry -> geometry) -> unit +``` +``` +val pp_get_geometry : formatter -> unit -> geometry +``` +``` +val get_geometry : unit -> geometry +``` +Return the current geometry of the formatter + +since 4.08 + +## Maximum formatting depth + +The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open. + +Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). + +``` +val pp_set_max_boxes : formatter -> int -> unit +``` +``` +val set_max_boxes : int -> unit +``` +`pp_set_max_boxes ppf max` sets the maximum number of pretty-printing boxes simultaneously open. + +Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). + +Nothing happens if `max` is smaller than 2. + +``` +val pp_get_max_boxes : formatter -> unit -> int +``` +``` +val get_max_boxes : unit -> int +``` +Returns the maximum number of pretty-printing boxes allowed before ellipsis. + +``` +val pp_over_max_boxes : formatter -> unit -> bool +``` +``` +val over_max_boxes : unit -> bool +``` +Tests if the maximum number of pretty-printing boxes allowed have already been opened. + + +## Tabulation boxes + +A *tabulation box* prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text. + +This box features command `set_tab` to define cell boundaries, and command `print_tab` to move from cell to cell and split the line when there is no more cells to print on the line. + +Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module [`Format`](#). + +``` +val pp_open_tbox : formatter -> unit -> unit +``` +``` +val open_tbox : unit -> unit +``` +`open_tbox ()` opens a new tabulation box. + +This box prints lines separated into cells of fixed width. + +Inside a tabulation box, special *tabulation markers* defines points of interest on the line (for instance to delimit cell boundaries). Function [`Format.set_tab`](./#val-set_tab) sets a tabulation marker at insertion point. + +A tabulation box features specific *tabulation breaks* to move to next tabulation marker or split the line. Function [`Format.print_tbreak`](./#val-print_tbreak) prints a tabulation break. + +``` +val pp_close_tbox : formatter -> unit -> unit +``` +``` +val close_tbox : unit -> unit +``` +Closes the most recently opened tabulation box. + +``` +val pp_set_tab : formatter -> unit -> unit +``` +``` +val set_tab : unit -> unit +``` +Sets a tabulation marker at current insertion point. + +``` +val pp_print_tab : formatter -> unit -> unit +``` +``` +val print_tab : unit -> unit +``` +`print_tab ()` emits a 'next' tabulation break hint: if not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. + +It is equivalent to `print_tbreak 0 0`. + +``` +val pp_print_tbreak : formatter -> int -> int -> unit +``` +``` +val print_tbreak : int -> int -> unit +``` +`print_tbreak nspaces offset` emits a 'full' tabulation break hint. + +If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints `nspaces` spaces. + +If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box. + +If the pretty-printer splits the line, `offset` is added to the current indentation. + + +## Ellipsis + +``` +val pp_set_ellipsis_text : formatter -> string -> unit +``` +``` +val set_ellipsis_text : string -> unit +``` +Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, `.`, by default). + +``` +val pp_get_ellipsis_text : formatter -> unit -> string +``` +``` +val get_ellipsis_text : unit -> string +``` +Return the text of the ellipsis. + + +## Semantic tags + +``` +type stag = .. +``` +*Semantic tags* (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities. + +Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so: + +```ocaml +type stag += RGB of {r:int;g:int;b:int} +``` +In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using [`pp_open_stag`](./#val-pp_open_stag) and [`pp_close_stag`](./#val-pp_close_stag). + +Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed *tag-marking* and *tag-printing*: + +- The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation. +- The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations. +Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output). + +More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur: + +- Tag-printing a semantic tag means calling the formatter specific function `print_open_stag` (resp. `print_close_stag`) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation). +- Tag-marking a semantic tag means calling the formatter specific function `mark_open_stag` (resp. `mark_close_stag`) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. \`tag-closing marker') for direct output into the output device of the formatter. +Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting). + +Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once `set_tags` is set to `true`, the pretty-printer engine honors tags and decorates the output accordingly. + +Default tag-marking functions behave the HTML way: [string tags](./#type-tag) are enclosed in "\<" and "\>" while other tags are ignored; hence, opening marker for tag string `"t"` is `""` and closing marker is `""`. + +Default tag-printing functions just do nothing. + +Tag-marking and tag-printing functions are user definable and can be set by calling [`set_formatter_stag_functions`](./#val-set_formatter_stag_functions). + +Semantic tag operations may be set on or off with [`set_tags`](./#val-set_tags). Tag-marking operations may be set on or off with [`set_mark_tags`](./#val-set_mark_tags). Tag-printing operations may be set on or off with [`set_print_tags`](./#val-set_print_tags). + +since 4.08 +``` +type tag = string +``` +``` +type stag += +``` +``` +| String_tag of tag +``` +`String_tag s` is a string tag `s`. String tags can be inserted either by explicitly using the constructor `String_tag` or by using the dedicated format syntax `"@{ ... @}"`. + +since 4.08 +``` + +``` +``` +val pp_open_stag : formatter -> stag -> unit +``` +``` +val open_stag : stag -> unit +``` +`pp_open_stag ppf t` opens the semantic tag named `t`. + +The `print_open_stag` tag-printing function of the formatter is called with `t` as argument; then the opening tag marker for `t`, as given by `mark_open_stag t`, is written into the output device of the formatter. + +since 4.08 +``` +val pp_close_stag : formatter -> unit -> unit +``` +``` +val close_stag : unit -> unit +``` +`pp_close_stag ppf ()` closes the most recently opened semantic tag `t`. + +The closing tag marker, as given by `mark_close_stag t`, is written into the output device of the formatter; then the `print_close_stag` tag-printing function of the formatter is called with `t` as argument. + +since 4.08 +``` +val pp_set_tags : formatter -> bool -> unit +``` +``` +val set_tags : bool -> unit +``` +`pp_set_tags ppf b` turns on or off the treatment of semantic tags (default is off). + +``` +val pp_set_print_tags : formatter -> bool -> unit +``` +``` +val set_print_tags : bool -> unit +``` +`pp_set_print_tags ppf b` turns on or off the tag-printing operations. + +``` +val pp_set_mark_tags : formatter -> bool -> unit +``` +``` +val set_mark_tags : bool -> unit +``` +`pp_set_mark_tags ppf b` turns on or off the tag-marking operations. + +``` +val pp_get_print_tags : formatter -> unit -> bool +``` +``` +val get_print_tags : unit -> bool +``` +Return the current status of tag-printing operations. + +``` +val pp_get_mark_tags : formatter -> unit -> bool +``` +``` +val get_mark_tags : unit -> bool +``` +Return the current status of tag-marking operations. + +``` +val pp_set_formatter_out_channel : formatter -> out_channel -> unit +``` +Redirecting the standard formatter output + +``` +val set_formatter_out_channel : out_channel -> unit +``` +Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.) + +`set_formatter_out_channel` is equivalent to [`pp_set_formatter_out_channel`](./#val-pp_set_formatter_out_channel) `std_formatter`. + +``` +val pp_set_formatter_output_functions : + formatter -> + (string -> int -> int -> unit) -> + (unit -> unit) -> + unit +``` +``` +val set_formatter_output_functions : + (string -> int -> int -> unit) -> + (unit -> unit) -> + unit +``` +`pp_set_formatter_output_functions ppf out flush` redirects the standard pretty-printer output functions to the functions `out` and `flush`. + +The `out` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. + +The `flush` function is called whenever the pretty-printer is flushed (via conversion `%!`, or pretty-printing indications `@?` or `@.`, or using low level functions `print_flush` or `print_newline`). + +``` +val pp_get_formatter_output_functions : + formatter -> + unit -> + (string -> int -> int -> unit) * (unit -> unit) +``` +``` +val get_formatter_output_functions : + unit -> + (string -> int -> int -> unit) * (unit -> unit) +``` +Return the current output functions of the standard pretty-printer. + + +## Redefining formatter output + +The `Format` module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed\! + + +### Redefining output functions + +``` +type formatter_out_functions = { +``` +`out_string : string -> int -> int -> unit;` +`out_flush : unit -> unit;` +`out_newline : unit -> unit;` +`out_spaces : int -> unit;` +`out_indent : int -> unit;` +since 4.06 +``` +} +``` +The set of output functions specific to a formatter: + +- the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. +- the `out_flush` function flushes the pretty-printer output device. +- `out_newline` is called to open a new line when the pretty-printer splits the line. +- the `out_spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output. +- the `out_indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. +By default: + +- fields `out_string` and `out_flush` are output device specific; (e.g. [`Stdlib.output_string`](./Stdlib.md#val-output_string) and [`Stdlib.flush`](./Stdlib.md#val-flush) for a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) device, or `Buffer.add_substring` and [`Stdlib.ignore`](./Stdlib.md#val-ignore) for a `Buffer.t` output device), +- field `out_newline` is equivalent to `out_string "\n" 0 1`; +- fields `out_spaces` and `out_indent` are equivalent to `out_string (String.make n ' ') 0 n`. +since 4.01 +``` +val pp_set_formatter_out_functions : + formatter -> + formatter_out_functions -> + unit +``` +``` +val set_formatter_out_functions : formatter_out_functions -> unit +``` +`pp_set_formatter_out_functions ppf out_funs` Set all the pretty-printer output functions of `ppf` to those of argument `out_funs`, + +This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand). + +Reasonable defaults for functions `out_spaces` and `out_newline` are respectively `out_funs.out_string (String.make n ' ') 0 n` and `out_funs.out_string "\n" 0 1`. + +since 4.01 +``` +val pp_get_formatter_out_functions : + formatter -> + unit -> + formatter_out_functions +``` +``` +val get_formatter_out_functions : unit -> formatter_out_functions +``` +Return the current output functions of the pretty-printer, including line splitting and indentation functions. Useful to record the current setting and restore it afterwards. + +since 4.01 + +## Redefining semantic tag operations + +``` +type formatter_stag_functions = { +``` +`mark_open_stag : stag -> string;` +`mark_close_stag : stag -> string;` +`print_open_stag : stag -> unit;` +`print_close_stag : stag -> unit;` +``` +} +``` +The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. `print` versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened. + +since 4.08 +``` +val pp_set_formatter_stag_functions : + formatter -> + formatter_stag_functions -> + unit +``` +``` +val set_formatter_stag_functions : formatter_stag_functions -> unit +``` +`pp_set_formatter_stag_functions ppf tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`. + +When opening a semantic tag with name `t`, the string `t` is passed to the opening tag-marking function (the `mark_open_stag` field of the record `tag_funs`), that must return the opening tag marker for that name. When the next call to `close_stag ()` happens, the semantic tag name `t` is sent back to the closing tag-marking function (the `mark_close_stag` field of record `tag_funs`), that must return a closing tag marker for that name. + +The `print_` field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue. + +since 4.08 +``` +val pp_get_formatter_stag_functions : + formatter -> + unit -> + formatter_stag_functions +``` +``` +val get_formatter_stag_functions : unit -> formatter_stag_functions +``` +Return the current semantic tag operation functions of the standard pretty-printer. + +since 4.08 + +## Defining formatters + +Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently. + +For instance, given a [`Buffer.t`](./Stdlib-Buffer.md#type-t) buffer `b`, [`formatter_of_buffer`](./#val-formatter_of_buffer) `b` returns a new formatter using buffer `b` as its output device. Similarly, given a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) output channel `oc`, [`formatter_of_out_channel`](./#val-formatter_of_out_channel) `oc` returns a new formatter using channel `oc` as its output device. + +Alternatively, given `out_funs`, a complete set of output functions for a formatter, then [`formatter_of_out_functions`](./#val-formatter_of_out_functions) `out_funs` computes a new formatter using those functions for output. + +``` +val formatter_of_out_channel : out_channel -> formatter +``` +`formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`. + +``` +val synchronized_formatter_of_out_channel : + out_channel -> + formatter Domain.DLS.key +``` +`synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`. + +When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + +alert unstable +``` +val std_formatter : formatter +``` +The initial domain's standard formatter to write to standard output. + +It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stdout`](./Stdlib.md#val-stdout). + +``` +val get_std_formatter : unit -> formatter +``` +`get_std_formatter ()` returns the current domain's standard formatter used to write to standard output. + +since 5.0 +``` +val err_formatter : formatter +``` +The initial domain's formatter to write to standard error. + +It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stderr`](./Stdlib.md#val-stderr). + +``` +val get_err_formatter : unit -> formatter +``` +`get_err_formatter ()` returns the current domain's formatter used to write to standard error. + +since 5.0 +``` +val formatter_of_buffer : Buffer.t -> formatter +``` +`formatter_of_buffer b` returns a new formatter writing to buffer `b`. At the end of pretty-printing, the formatter must be flushed using [`pp_print_flush`](./#val-pp_print_flush) or [`pp_print_newline`](./#val-pp_print_newline), to print all the pending material into the buffer. + +``` +val stdbuf : Buffer.t +``` +The initial domain's string buffer in which `str_formatter` writes. + +``` +val get_stdbuf : unit -> Buffer.t +``` +`get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes. + +since 5.0 +``` +val str_formatter : formatter +``` +The initial domain's formatter to output to the [`stdbuf`](./#val-stdbuf) string buffer. + +`str_formatter` is defined as [`formatter_of_buffer`](./#val-formatter_of_buffer) [`stdbuf`](./#val-stdbuf). + +``` +val get_str_formatter : unit -> formatter +``` +The current domain's formatter to output to the current domains string buffer. + +since 5.0 +``` +val flush_str_formatter : unit -> string +``` +Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer. + +``` +val make_formatter : + (string -> int -> int -> unit) -> + (unit -> unit) -> + formatter +``` +`make_formatter out flush` returns a new formatter that outputs with function `out`, and flushes with function `flush`. + +For instance, + +```ocaml + make_formatter + (Stdlib.output_substring oc) + (fun () -> Stdlib.flush oc) +``` +returns a formatter to the [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) `oc`. + +``` +val make_synchronized_formatter : + (string -> int -> int -> unit) -> + (unit -> unit) -> + formatter Domain.DLS.key +``` +`make_synchronized_formatter out flush` returns the key to the domain-local state that holds the domain-local formatter that outputs with function `out`, and flushes with function `flush`. + +When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + +since 5.0 +alert unstable +``` +val formatter_of_out_functions : formatter_out_functions -> formatter +``` +`formatter_of_out_functions out_funs` returns a new formatter that writes with the set of output functions `out_funs`. + +See definition of type [`formatter_out_functions`](./#type-formatter_out_functions) for the meaning of argument `out_funs`. + +since 4.06 + +### Symbolic pretty-printing + +Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items. + +When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations. + +In practice, first define a symbolic output buffer `b` using: + +- `let sob = make_symbolic_output_buffer ()`. Then define a symbolic formatter with: +- `let ppf = formatter_of_symbolic_output_buffer sob` +Use symbolic formatter `ppf` as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer `sob` with: + +- `flush_symbolic_output_buffer sob`. +``` +type symbolic_output_item = +``` +``` +| Output_flush +``` +symbolic flush command + +``` +| Output_newline +``` +symbolic newline command + +``` +| Output_string of string +``` +`Output_string s`: symbolic output for string `s` + +``` +| Output_spaces of int +``` +`Output_spaces n`: symbolic command to output `n` spaces + +``` +| Output_indent of int +``` +`Output_indent i`: symbolic indentation of size `i` + +``` + +``` +Items produced by symbolic pretty-printers + +since 4.06 +``` +type symbolic_output_buffer +``` +The output buffer of a symbolic pretty-printer. + +since 4.06 +``` +val make_symbolic_output_buffer : unit -> symbolic_output_buffer +``` +`make_symbolic_output_buffer ()` returns a fresh buffer for symbolic output. + +since 4.06 +``` +val clear_symbolic_output_buffer : symbolic_output_buffer -> unit +``` +`clear_symbolic_output_buffer sob` resets buffer `sob`. + +since 4.06 +``` +val get_symbolic_output_buffer : + symbolic_output_buffer -> + symbolic_output_item list +``` +`get_symbolic_output_buffer sob` returns the contents of buffer `sob`. + +since 4.06 +``` +val flush_symbolic_output_buffer : + symbolic_output_buffer -> + symbolic_output_item list +``` +`flush_symbolic_output_buffer sob` returns the contents of buffer `sob` and resets buffer `sob`. `flush_symbolic_output_buffer sob` is equivalent to `let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items` + +since 4.06 +``` +val add_symbolic_output_item : + symbolic_output_buffer -> + symbolic_output_item -> + unit +``` +`add_symbolic_output_item sob itm` adds item `itm` to buffer `sob`. + +since 4.06 +``` +val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter +``` +`formatter_of_symbolic_output_buffer sob` returns a symbolic formatter that outputs to `symbolic_output_buffer` `sob`. + +since 4.06 + +## Convenience formatting functions. + +``` +val pp_print_iter : + ?pp_sep:(formatter -> unit -> unit) -> + (('a -> unit) -> 'b -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'b -> + unit +``` +`pp_print_iter ~pp_sep iter pp_v ppf v` formats on `ppf` the iterations of `iter` over a collection `v` of values using `pp_v`. Iterations are separated by `pp_sep` (defaults to [`pp_print_cut`](./#val-pp_print_cut)). + +since 5.1 +``` +val pp_print_list : + ?pp_sep:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a list -> + unit +``` +`pp_print_list ?pp_sep pp_v ppf l` prints items of list `l`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty lists. + +since 4.02 +``` +val pp_print_array : + ?pp_sep:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a array -> + unit +``` +`pp_print_array ?pp_sep pp_v ppf a` prints items of array `a`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty arrays. + +If `a` is mutated after `pp_print_array` is called, the printed values may not be what is expected because `Format` can delay the printing. This can be avoided by flushing `ppf`. + +since 5.1 +``` +val pp_print_seq : + ?pp_sep:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a Seq.t -> + unit +``` +`pp_print_seq ?pp_sep pp_v ppf s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut). Does nothing on empty sequences. + +This function does not terminate on infinite sequences. + +since 4.12 +``` +val pp_print_text : formatter -> string -> unit +``` +`pp_print_text ppf s` prints `s` with spaces and newlines respectively printed using [`pp_print_space`](./#val-pp_print_space) and [`pp_force_newline`](./#val-pp_force_newline). + +since 4.02 +``` +val pp_print_option : + ?none:(formatter -> unit -> unit) -> + (formatter -> 'a -> unit) -> + formatter -> + 'a option -> + unit +``` +`pp_print_option ?none pp_v ppf o` prints `o` on `ppf` using `pp_v` if `o` is `Some v` and `none` if it is `None`. `none` prints nothing by default. + +since 4.08 +``` +val pp_print_result : + ok:(formatter -> 'a -> unit) -> + error:(formatter -> 'e -> unit) -> + formatter -> + ('a, 'e) result -> + unit +``` +`pp_print_result ~ok ~error ppf r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`. + +since 4.08 +``` +val pp_print_either : + left:(formatter -> 'a -> unit) -> + right:(formatter -> 'b -> unit) -> + formatter -> + ('a, 'b) Either.t -> + unit +``` +`pp_print_either ~left ~right ppf e` prints `e` on `ppf` using `left` if `e` is `Either.Left _` and `right` if `e` is `Either.Right _`. + +since 4.13 + +## Formatted pretty-printing + +Module `Format` provides a complete set of `printf` like functions for pretty-printing using format string specifications. + +Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine. + +Those annotations are introduced in the format strings using the `@` character. For instance, `@ ` means a space break, `@,` means a cut, `@[` opens a new box, and `@]` closes the last open box. + +``` +val fprintf : formatter -> ('a, formatter, unit) format -> 'a +``` +`fprintf ff fmt arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `fmt`, and outputs the resulting string on the formatter `ff`. + +The format string `fmt` is a character string which contains three types of objects: plain characters and conversion specifications as specified in the [`Printf`](./Stdlib-Printf.md) module, and pretty-printing indications specific to the `Format` module. + +The pretty-printing indication characters are introduced by a `@` character, and their meanings are: + +- `@[`: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the `<` character, followed by an optional box type indication, then an optional integer offset, and the closing `>` character. Pretty-printing box type is one of `h`, `v`, `hv`, `b`, or `hov`. '`h`' stands for an 'horizontal' pretty-printing box, '`v`' stands for a 'vertical' pretty-printing box, '`hv`' stands for an 'horizontal/vertical' pretty-printing box, '`b`' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '`hov`' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, `@[` opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with `open_hovbox 2`. For more details about pretty-printing boxes, see the various box opening functions `open_*box`. +- `@]`: close the most recently opened pretty-printing box. +- `@,`: output a 'cut' break hint, as with `print_cut ()`. +- `@ `: output a 'space' break hint, as with `print_space ()`. +- `@;`: output a 'full' break hint as with `print_break`. The `nspaces` and `offset` parameters of the break hint may be optionally specified with the following syntax: the `<` character, followed by an integer `nspaces` value, then an integer `offset`, and a closing `>` character. If no parameters are provided, the full break defaults to a 'space' break hint. +- `@.`: flush the pretty-printer and split the line, as with `print_newline ()`. +- `@`: print the following item as if it were of length `n`. Hence, `printf "@<0>%s" arg` prints `arg` as a zero length string. If `@` is not followed by a conversion specification, then the following character of the format is printed as if it were of length `n`. +- `@\{`: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the `<` character, followed by an optional string specification, and the closing `>` character. The string specification is any character string that does not contain the closing character `'>'`. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions [`open_stag`](./#val-open_stag) and [`close_stag`](./#val-close_stag). +- `@\}`: close the most recently opened semantic tag. +- `@?`: flush the pretty-printer as with `print_flush ()`. This is equivalent to the conversion `%!`. +- `@\n`: force a newline, as with `force_newline ()`, not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box. +Note: To prevent the interpretation of a `@` character as a pretty-printing indication, escape it with a `%` character. Old quotation mode `@@` is deprecated since it is not compatible with formatted input interpretation of character `'@'`. + +Example: `printf "@[%s@ %d@]@." "x =" 1` is equivalent to `open_box (); print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()`. It prints `x = 1` within a pretty-printing 'horizontal-or-vertical' box. + +``` +val printf : ('a, formatter, unit) format -> 'a +``` +Same as `fprintf` above, but output on `get_std_formatter ()`. + +It is defined similarly to `fun fmt -> fprintf (get_std_formatter ()) fmt` but delays calling `get_std_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + +``` +val eprintf : ('a, formatter, unit) format -> 'a +``` +Same as `fprintf` above, but output on `get_err_formatter ()`. + +It is defined similarly to `fun fmt -> fprintf (get_err_formatter ()) fmt` but delays calling `get_err_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). + +``` +val sprintf : ('a, unit, string) format -> 'a +``` +Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of *each call* to `sprintf`. Note that if your format string contains a `%a`, you should use `asprintf`. + +In case of multiple and related calls to `sprintf` to output material on a single string, you should consider using `fprintf` with the predefined formatter `str_formatter` and call `flush_str_formatter ()` to get the final result. + +Alternatively, you can use `Format.fprintf` with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string. + +``` +val asprintf : ('a, formatter, unit, string) format4 -> 'a +``` +Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. The type of `asprintf` is general enough to interact nicely with `%a` conversions. + +since 4.01 +``` +val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a +``` +Same as [`fprintf`](./#val-fprintf), except the formatter is the last argument. `dprintf "..." a b c` is a function of type `formatter -> unit` which can be given to a format specifier `%t`. + +This can be used as a replacement for [`asprintf`](./#val-asprintf) to delay formatting decisions. Using the string returned by [`asprintf`](./#val-asprintf) in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. [`dprintf`](./#val-dprintf) allows delay of formatting decisions until the final formatting context is known. For example: + +```ocaml + let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in + ... + Format.printf "@[%t@]" t +``` +since 4.08 +``` +val ifprintf : formatter -> ('a, formatter, unit) format -> 'a +``` +Same as `fprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + +since 3.10 +Formatted Pretty-Printing with continuations. + +``` +val kfprintf : + (formatter -> 'a) -> + formatter -> + ('b, formatter, unit, 'a) format4 -> + 'b +``` +Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing. + +``` +val kdprintf : + ((formatter -> unit) -> 'a) -> + ('b, formatter, unit, 'a) format4 -> + 'b +``` +Same as [`dprintf`](./#val-dprintf) above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing. + +since 4.08 +``` +val ikfprintf : + (formatter -> 'a) -> + formatter -> + ('b, formatter, unit, 'a) format4 -> + 'b +``` +Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + +since 3.12 +``` +val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b +``` +Same as `sprintf` above, but instead of returning the string, passes it to the first argument. + +``` +val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b +``` +Same as `asprintf` above, but instead of returning the string, passes it to the first argument. + +since 4.03 + +## Examples + +A few warmup examples to get an idea of how Format is used. + +We have a list `l` of pairs `(int * bool)`, which the toplevel prints for us: + +```ocaml +# let l = List.init 20 (fun n -> n, n mod 2 = 0) +val l : (int * bool) list = +[(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); + (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); + (12, true); (13, false); (14, true); (15, false); (16, true); (17, false); + (18, true); (19, false)] +``` +If we want to print it ourself without the toplevel magic, we can try this: + +```ocaml +# let pp_pair out (x,y) = Format.fprintf out "(%d, %b)" x y +val pp_pair : Format.formatter -> int * bool -> unit = +# Format.printf "l: [@[%a@]]@." + Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out ";@ ") pp_pair) l + l: [(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); + (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); + (12, true); (13, false); (14, true); (15, false); (16, true); + (17, false); (18, true); (19, false)] + +``` +What this does, briefly, is: + +- `pp_pair` prints a pair `bool*int` surrounded in "(" ")". It takes a formatter (into which formatting happens), and the pair itself. When printing is done it returns `()`. +- `Format.printf "l = [@[%a@]]@." ... l` is like `printf`, but with additional formatting instructions (denoted with "@"). The pair "`@[`" and "`@]`" is a "horizontal-or-vertical box". +- "@." ends formatting with a newline. It is similar to "\\n" but is also aware of the `Format.formatter`'s state. Do not use "\\n" with `Format`. +- "%a" is a formatting instruction, like "%d" or "%s" for `printf`. However, where "%d" prints an integer and "%s" prints a string, "%a" takes a printer (of type `Format.formatter -> 'a -> unit`) and a value (of type `'a`) and applies the printer to the value. This is key to compositionality of printers. +- We build a list printer using `Format.pp_print_list ~pp_sep:(...) pp_pair`. `pp_print_list` takes an element printer and returns a list printer. The `?pp_sep` optional argument, if provided, is called in between each element to print a separator. +- Here, for a separator, we use `(fun out () -> Format.fprintf out ";@ ")`. It prints ";", and then "@ " which is a breaking space (either it prints " ", or it prints a newline if the box is about to overflow). This "@ " is responsible for the list printing splitting into several lines. +If we omit "@ ", we get an ugly single-line print: + +```ocaml + # Format.printf "l: [@[%a@]]@." + Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out "; ") pp_pair) l + l: [(0, true); (1, false); (2, true); (* ... *); (18, true); (19, false)] +- : unit = () +``` +Generally, it is good practice to define custom printers for important types in your program. If, for example, you were to define basic geometry types like so: + +```ocaml +type point = { + x: float; + y: float; +} + +type rectangle = { + ll: point; (* lower left *) + ur: point; (* upper right *) +} +``` +For debugging purpose, or to display information in logs, or on the console, it would be convenient to define printers for these types. Here is an example of to do it. Note that "%.3f" is a `float` printer up to 3 digits of precision after the dot; "%f" would print as many digits as required, which is somewhat verbose; "%h" is an hexadecimal float printer. + +```ocaml +let pp_point out (p:point) = + Format.fprintf out "{ @[x=%.3f;@ y=%.3f@] }" p.x p.y + +let pp_rectangle out (r:rectangle) = + Format.fprintf out "{ @[ll=%a;@ ur=%a@] }" + pp_point r.ll pp_point r.ur +``` +In the `.mli` file, we could have: + +```ocaml + val pp_point : Format.formatter -> point -> unit + + val pp_rectangle : Format.formatter -> rectangle -> unit +``` +These printers can now be used with "%a" inside other printers. + +```ocaml + # Format.printf "some rectangle: %a@." + (Format.pp_print_option pp_rectangle) + (Some {ll={x=1.; y=2.}; ur={x=42.; y=500.12345}}) +some rectangle: { l={ x=1.000; y=2.000 }; ur={ x=42.000; y=500.123 } } + +# Format.printf "no rectangle: %a@." + (Format.pp_option pp_rectangle) + None +no rectangle: +``` +See how we combine `pp_print_option` (option printer) and our newly defined rectangle printer, like we did with `pp_print_list` earlier. + +For a more extensive tutorial, see ["Using the Format module"](https://caml.inria.fr/resources/doc/guides/format.en.html). + +A final note: the `Format` module is a starting point. The OCaml ecosystem has libraries that makes formatting easier and more expressive, with more combinators, more concise names, etc. An example of such a library is [Fmt](https://erratique.ch/software/fmt). + +Automatic deriving of pretty-printers from type definitions is also possible, using [https://github.com/ocaml-ppx/ppx\_deriving](ppx_deriving.show) or similar ppx derivers. diff --git a/docs/api/re/melange/Stdlib-Fun.md b/docs/api/re/melange/Stdlib-Fun.md new file mode 100644 index 000000000..ce11eb91e --- /dev/null +++ b/docs/api/re/melange/Stdlib-Fun.md @@ -0,0 +1,51 @@ + +# Module `Stdlib.Fun` + +Function manipulation. + +since 4.08 + +## Combinators + +``` +val id : 'a -> 'a +``` +`id` is the identity function. For any argument `x`, `id x` is `x`. + +``` +val const : 'a -> _ -> 'a +``` +`const c` is a function that always returns the value `c`. For any argument `x`, `(const c) x` is `c`. + +``` +val compose : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c +``` +`compose f g` is a function composition of applying `g` then `f`. For any arguments `f`, `g`, and `x`, `compose f g x` is `f (g x)`. + +since 5.2 +``` +val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c +``` +`flip f` reverses the argument order of the binary function `f`. For any arguments `x` and `y`, `(flip f) x y` is `f y x`. + +``` +val negate : ('a -> bool) -> 'a -> bool +``` +`negate p` is the negation of the predicate function `p`. For any argument `x`, `(negate p) x` is `not (p x)`. + + +## Exception handling + +``` +val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a +``` +`protect ~finally work` invokes `work ()` and then `finally ()` before `work ()` returns with its value or an exception. In the latter case the exception is re-raised after `finally ()`. If `finally ()` raises an exception, then the exception [`Finally_raised`](./#exception-Finally_raised) is raised instead. + +`protect` can be used to enforce local invariants whether `work ()` returns normally or raises an exception. However, it does not protect against unexpected exceptions raised inside `finally ()` such as [`Stdlib.Out_of_memory`](./Stdlib.md#exception-Out_of_memory), [`Stdlib.Stack_overflow`](./Stdlib.md#exception-Stack_overflow), or asynchronous exceptions raised by signal handlers (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)). + +Note: It is a *programming error* if other kinds of exceptions are raised by `finally`, as any exception raised in `work ()` will be lost in the event of a [`Finally_raised`](./#exception-Finally_raised) exception. Therefore, one should make sure to handle those inside the finally. + +``` +exception Finally_raised of exn +``` +`Finally_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally_raised` exception except as part of a catch-all handler. diff --git a/docs/api/re/melange/Stdlib-Gc-Memprof.md b/docs/api/re/melange/Stdlib-Gc-Memprof.md new file mode 100644 index 000000000..4258d4511 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Gc-Memprof.md @@ -0,0 +1,113 @@ + +# Module `Gc.Memprof` + +`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. + +Since blocks are composed of several words, a block can potentially be sampled several times. If a block is sampled several times, then each of the callbacks is called once for each event of this block: the multiplicity is given in the `n_samples` field of the `allocation` structure. + +This engine makes it possible to implement a low-overhead memory profiler as an OCaml library. + +Note: this API is EXPERIMENTAL. It may change without prior notice. + +``` +type t +``` +the type of a profile + +``` +type allocation_source = +``` +``` +| Normal +``` +``` +| Marshal +``` +``` +| Custom +``` +``` + +``` +``` +type allocation = private { +``` +`n_samples : int;` +The number of samples in this block (\>= 1\). + +`size : int;` +The size of the block, in words, excluding the header. + +`source : allocation_source;` +The cause of the allocation. + +`callstack : Printexc.raw_backtrace;` +The callstack for the allocation. + +``` +} +``` +The type of metadata associated with allocations. This is the type of records passed to the callback triggered by the sampling of an allocation. + +``` +type ('minor, 'major) tracker = { +``` +`alloc_minor : allocation -> 'minor option;` +`alloc_major : allocation -> 'major option;` +`promote : 'minor -> 'major option;` +`dealloc_minor : 'minor -> unit;` +`dealloc_major : 'major -> unit;` +``` +} +``` +A `('minor, 'major) tracker` describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: `'minor` is the type of metadata to keep for minor blocks, and `'major` the type of metadata for major blocks. + +The member functions in a `tracker` are called callbacks. + +If an allocation or promotion callback raises an exception or returns `None`, memprof stops tracking the corresponding block. + +``` +val null_tracker : ('minor, 'major) tracker +``` +Default callbacks simply return `None` or `()` + +``` +val start : + sampling_rate:float -> + ?callstack_size:int -> + ('minor, 'major) tracker -> + t +``` +Start a profile with the given parameters. Raises an exception if a profile is already sampling in the current domain. + +Sampling begins immediately. The parameter `sampling_rate` is the sampling rate in samples per word (including headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on performance, and 1e-3 causes the program to run a few percent slower. 0.0 \<= sampling\_rate \<= 1\.0. + +The parameter `callstack_size` is the length of the callstack recorded at every sample. Its default is `max_int`. + +The parameter `tracker` determines how to track sampled blocks over their lifetime in the minor and major heap. + +Sampling and running callbacks are temporarily disabled on the current thread when calling a callback, so callbacks do not need to be re-entrant if the program is single-threaded and single-domain. However, if threads or multiple domains are used, it is possible that several callbacks will run in parallel. In this case, callback functions must be re-entrant. + +Note that a callback may be postponed slightly after the actual event. The callstack passed to an allocation callback always accurately reflects the allocation, but the program state may have evolved between the allocation and the call to the callback. + +If a new thread or domain is created when the current domain is sampling for a profile, the child thread or domain joins that profile (using the same `sampling_rate`, `callstack_size`, and `tracker` callbacks). + +An allocation callback is always run by the thread which allocated the block. If the thread exits or the profile is stopped before the callback is called, the allocation callback is not called and the block is not tracked. + +Each subsequent callback is generally run by the domain which allocated the block. If the domain terminates or the profile is stopped before the callback is called, the callback may be run by a different domain. + +Different domains may sample for different profiles simultaneously. + +``` +val stop : unit -> unit +``` +Stop sampling for the current profile. Fails if no profile is sampling in the current domain. Stops sampling in all threads and domains sharing the profile. + +Promotion and deallocation callbacks from a profile may run after `stop` is called, until `discard` is applied to the profile. + +A profile is implicitly stopped (but not discarded) if all domains and threads sampling for it are terminated. + +``` +val discard : t -> unit +``` +Discards all profiling state for a stopped profile, which prevents any more callbacks for it. Raises an exception if called on a profile which has not been stopped. diff --git a/docs/api/re/melange/Stdlib-Gc.md b/docs/api/re/melange/Stdlib-Gc.md new file mode 100644 index 000000000..37e04a556 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Gc.md @@ -0,0 +1,295 @@ + +# Module `Stdlib.Gc` + +Memory management control and statistics; finalised values. + +``` +type stat = { +``` +`minor_words : float;` +Number of words allocated in the minor heap since the program was started. + +`promoted_words : float;` +Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap since the program was started. + +`major_words : float;` +Number of words allocated in the major heap, including the promoted words, since the program was started. + +`minor_collections : int;` +Number of minor collections since the program was started. + +`major_collections : int;` +Number of major collection cycles completed since the program was started. + +`heap_words : int;` +Total size of the major heap, in words. + +`heap_chunks : int;` +Number of contiguous pieces of memory that make up the major heap. This metric is currently not available in OCaml 5: the field value is always `0`. + +`live_words : int;` +Number of words of live data in the major heap, including the header words. + +Note that "live" words refers to every word in the major heap that isn't currently known to be collectable, which includes words that have become unreachable by the program after the start of the previous gc cycle. It is typically much simpler and more predictable to call [`Gc.full_major`](./#val-full_major) (or [`Gc.compact`](./#val-compact)) then computing gc stats, as then "live" words has the simple meaning of "reachable by the program". One caveat is that a single call to [`Gc.full_major`](./#val-full_major) will not reclaim values that have a finaliser from [`Gc.finalise`](./#val-finalise) (this does not apply to [`Gc.finalise_last`](./#val-finalise_last)). If this caveat matters, simply call [`Gc.full_major`](./#val-full_major) twice instead of once. + +`live_blocks : int;` +Number of live blocks in the major heap. + +See `live_words` for a caveat about what "live" means. + +`free_words : int;` +Number of words in the free list. + +`free_blocks : int;` +Number of blocks in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. + +`largest_free : int;` +Size (in words) of the largest block in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. + +`fragments : int;` +Number of wasted words due to fragmentation. These are 1-words free blocks placed between two live blocks. They are not available for allocation. + +`compactions : int;` +Number of heap compactions since the program was started. + +`top_heap_words : int;` +Maximum size reached by the major heap, in words. + +`stack_size : int;` +Current size of the stack, in words. This metric is currently not available in OCaml 5: the field value is always `0`. + +since 3.12 +`forced_major_collections : int;` +Number of forced full major collections completed since the program was started. + +since 4.12 +``` +} +``` +The memory management counters are returned in a `stat` record. These counters give values for the whole program. + +The total amount of memory allocated by the program since it was started is (in words) `minor_words + major_words - promoted_words`. Multiply by the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes. + +``` +type control = { +``` +`minor_heap_size : int;` +The size (in words) of the minor heap. Changing this parameter will trigger a minor collection. The total size of the minor heap used by this program is the sum of the heap sizes of the active domains. Default: 256k. + +`major_heap_increment : int;` +How much to add to the major heap when increasing it. If this number is less than or equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will double the heap size at each increase). If it is more than 1000, it is a fixed number of words that will be added to the heap. + +This field is currently not available in OCaml 5: the field value is always `0`. + +`space_overhead : int;` +The major GC speed is computed from this parameter. This is the memory that will be "wasted" because the GC does not immediately collect unreachable blocks. It is expressed as a percentage of the memory used for live data. The GC will work more (use more CPU time and collect blocks more eagerly) if `space_overhead` is smaller. Default: 120. + +`verbose : int;` +This value controls the GC messages on standard error output. It is a sum of some of the following flags, to print messages on the corresponding events: + +- `0x001` Start and end of major GC cycle. +- `0x002` Minor collection and major GC slice. +- `0x004` Growing and shrinking of the heap. +- `0x008` Resizing of stacks and memory manager tables. +- `0x010` Heap compaction. +- `0x020` Change of GC parameters. +- `0x040` Computation of major GC slice size. +- `0x080` Calling of finalisation functions. +- `0x100` Bytecode executable and shared library search at start-up. +- `0x200` Computation of compaction-triggering condition. +- `0x400` Output GC statistics at program exit. Default: 0. +`max_overhead : int;` +Heap compaction is triggered when the estimated amount of "wasted" memory is more than `max_overhead` percent of the amount of live data. If `max_overhead` is set to 0, heap compaction is triggered at the end of each major GC cycle (this setting is intended for testing purposes only). If `max_overhead >= 1000000`, compaction is never triggered. + +This field is currently not available in OCaml 5: the field value is always `0`. + +`stack_limit : int;` +The maximum size of the fiber stacks (in words). Default: 128M. + +`allocation_policy : int;` +The policy used for allocating in the major heap. + +This field is currently not available in OCaml 5: the field value is always `0`. + +Prior to OCaml 5.0, possible values were 0, 1 and 2. + +- 0 was the next-fit policy +- 1 was the first-fit policy (since OCaml 3.11) +- 2 was the best-fit policy (since OCaml 4.10) +since 3.11 +`window_size : int;` +The size of the window used by the major GC for smoothing out variations in its workload. This is an integer between 1 and 50. + +since 4.03 +This field is currently not available in OCaml 5: the field value is always `0`. + +`custom_major_ratio : int;` +Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. The default value keeps the out-of-heap floating garbage about the same size as the in-heap overhead. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 44. + +since 4.08 +`custom_minor_ratio : int;` +Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 100. + +since 4.08 +`custom_minor_max_size : int;` +Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. Custom values that hold more than this many bytes are allocated on the major heap. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 70000 bytes. + +since 4.08 +``` +} +``` +The GC parameters are given as a `control` record. Note that these parameters can also be initialised by setting the OCAMLRUNPARAM environment variable. See the documentation of `ocamlrun`. + +``` +val stat : unit -> stat +``` +Return the current values of the memory management counters in a `stat` record that represents the program's total memory stats. The `heap_chunks`, `free_blocks`, `largest_free`, and `stack_size` metrics are currently not available in OCaml 5: their returned field values are therefore `0`. This function causes a full major collection. + +``` +val quick_stat : unit -> stat +``` +Returns a record with the current values of the memory management counters like `stat`. Unlike `stat`, `quick_stat` does not perform a full major collection, and hence, is much faster. However, `quick_stat` reports the counters sampled at the last minor collection or at the end of the last major collection cycle (whichever is the latest). Hence, the memory stats returned by `quick_stat` are not instantaneously accurate. + +``` +val counters : unit -> float * float * float +``` +Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. This function is as fast as `quick_stat`. + +``` +val minor_words : unit -> float +``` +Number of words allocated in the minor heap by this domain or potentially previous domains. This number is accurate in byte-code programs, but only an approximation in programs compiled to native code. + +In native code this function does not allocate. + +since 4.04 +``` +val get : unit -> control +``` +Return the current values of the GC parameters in a `control` record. + +The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: their returned field values are therefore `0`. + +alert unsynchronized\_access GC parameters are a mutable global state. +``` +val set : control -> unit +``` +`set r` changes the GC parameters according to the `control` record `r`. The normal usage is: `Gc.set { (Gc.get()) with Gc.verbose = 0x00d }` + +The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: setting them therefore has no effect. + +alert unsynchronized\_access GC parameters are a mutable global state. +``` +val minor : unit -> unit +``` +Trigger a minor collection. + +``` +val major_slice : int -> int +``` +`major_slice n` Do a minor collection and a slice of major collection. `n` is the size of the slice: the GC will do enough work to free (on average) `n` words of memory. If `n` \= 0, the GC will try to do enough work to ensure that the next automatic slice has no work to do. This function returns an unspecified integer (currently: 0). + +``` +val major : unit -> unit +``` +Do a minor collection and finish the current major collection cycle. + +``` +val full_major : unit -> unit +``` +Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. This will collect all currently unreachable blocks. + +``` +val compact : unit -> unit +``` +Perform a full major collection and compact the heap. Note that heap compaction is a lengthy operation. + +``` +val print_stat : out_channel -> unit +``` +Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument. + +``` +val allocated_bytes : unit -> float +``` +Return the number of bytes allocated by this domain and potentially a previous domain. It is returned as a `float` to avoid overflow problems with `int` on 32-bit machines. + +``` +val get_minor_free : unit -> int +``` +Return the current size of the free space inside the minor heap of this domain. + +since 4.03 +``` +val finalise : ('a -> unit) -> 'a -> unit +``` +`finalise f v` registers `f` as a finalisation function for `v`. `v` must be heap-allocated. `f` will be called with `v` as argument at some point between the first time `v` becomes unreachable (including through weak pointers) and the time `v` is collected by the GC. Several functions can be registered for the same value, or even several instances of the same function. Each instance will be called once (or never, if the program terminates before `v` becomes unreachable). + +The GC will call the finalisation functions in the order of deallocation. When several values become unreachable at the same time (i.e. during the same GC cycle), the finalisation functions will be called in the reverse order of the corresponding calls to `finalise`. If `finalise` is called in the same order as the values are allocated, that means each value is finalised before the values it depends upon. Of course, this becomes false if additional dependencies are introduced by assignments. + +In the presence of multiple OCaml threads it should be assumed that any particular finaliser may be executed in any of the threads. + +Anything reachable from the closure of finalisation functions is considered reachable, so the following code will not work as expected: + +- ` let v = ... in Gc.finalise (fun _ -> ...v...) v ` +Instead you should make sure that `v` is not in the closure of the finalisation function by writing: + +- ` let f = fun x -> ... let v = ... in Gc.finalise f v ` +The `f` function can use all features of OCaml, including assignments that make the value reachable again. It can also loop forever (in this case, the other finalisation functions will not be called during the execution of f, unless it calls `finalise_release`). It can call `finalise` on `v` or other values to register other functions or even itself. It can raise an exception; in this case the exception will interrupt whatever the program was doing when the function was called. + +`finalise` will raise `Invalid_argument` if `v` is not guaranteed to be heap-allocated. Some examples of values that are not heap-allocated are integers, constant constructors, booleans, the empty array, the empty list, the unit value. The exact list of what is heap-allocated or not is implementation-dependent. Some constant values can be heap-allocated but never deallocated during the lifetime of the program, for example a list of integer constants; this is also implementation-dependent. Note that values of types `float` are sometimes allocated and sometimes not, so finalising them is unsafe, and `finalise` will also raise `Invalid_argument` for them. Values of type `'a Lazy.t` (for any `'a`) are like `float` in this respect, except that the compiler sometimes optimizes them in a way that prevents `finalise` from detecting them. In this case, it will not raise `Invalid_argument`, but you should still avoid calling `finalise` on lazy values. + +The results of calling [`String.make`](./Stdlib-String.md#val-make), [`Bytes.make`](./Stdlib-Bytes.md#val-make), [`Bytes.create`](./Stdlib-Bytes.md#val-create), [`Array.make`](./Stdlib-Array.md#val-make), and [`Stdlib.ref`](./Stdlib.md#val-ref) are guaranteed to be heap-allocated and non-constant except when the length argument is `0`. + +``` +val finalise_last : (unit -> unit) -> 'a -> unit +``` +same as [`finalise`](./#val-finalise) except the value is not given as argument. So you can't use the given value for the computation of the finalisation function. The benefit is that the function is called after the value is unreachable for the last time instead of the first time. So contrary to [`finalise`](./#val-finalise) the value will never be reachable again or used again. In particular every weak pointer and ephemeron that contained this value as key or data is unset before running the finalisation function. Moreover the finalisation functions attached with [`finalise`](./#val-finalise) are always called before the finalisation functions attached with [`finalise_last`](./#val-finalise_last). + +since 4.04 +``` +val finalise_release : unit -> unit +``` +A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return. + +``` +type alarm +``` +An alarm is a piece of data that calls a user function at the end of major GC cycle. The following functions are provided to create and delete alarms. + +``` +val create_alarm : (unit -> unit) -> alarm +``` +`create_alarm f` will arrange for `f` to be called at the end of major GC cycles, not caused by `f` itself, starting with the current cycle or the next one. `f` will run on the same domain that created the alarm, until the domain exits or `delete_alarm` is called. A value of type `alarm` is returned that you can use to call `delete_alarm`. + +It is not guaranteed that the Gc alarm runs at the end of every major GC cycle, but it is guaranteed that it will run eventually. + +As an example, here is a crude way to interrupt a function if the memory consumption of the program exceeds a given `limit` in MB, suitable for use in the toplevel: + +```ocaml +let run_with_memory_limit (limit : int) (f : unit -> 'a) : 'a = + let limit_memory () = + let mem = Gc.(quick_stat ()).heap_words in + if mem / (1024 * 1024) > limit / (Sys.word_size / 8) then + raise Out_of_memory + in + let alarm = Gc.create_alarm limit_memory in + Fun.protect f ~finally:(fun () -> Gc.delete_alarm alarm ; Gc.compact ()) +``` +``` +val delete_alarm : alarm -> unit +``` +`delete_alarm a` will stop the calls to the function associated to `a`. Calling `delete_alarm a` again has no effect. + +``` +val eventlog_pause : unit -> unit +``` +deprecated Use Runtime\_events.pause instead. +``` +val eventlog_resume : unit -> unit +``` +deprecated Use Runtime\_events.resume instead. +``` +module Memprof : sig ... end +``` +`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. diff --git a/docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md b/docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md new file mode 100644 index 000000000..80efdc53c --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md @@ -0,0 +1,21 @@ + +# Parameter `Make.H` + +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-Make.md b/docs/api/re/melange/Stdlib-Hashtbl-Make.md new file mode 100644 index 000000000..ec79c26fe --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-Make.md @@ -0,0 +1,96 @@ + +# Module `Hashtbl.Make` + +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + + +## Parameters + +``` +module H : HashedType +``` + +## Signature + +``` +type key = H.t +``` +``` +type !'a t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md new file mode 100644 index 000000000..66eb409ed --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md @@ -0,0 +1,17 @@ + +# Parameter `MakeSeeded.H` + +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md b/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md new file mode 100644 index 000000000..23f14bd52 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md @@ -0,0 +1,95 @@ + +# Module `Hashtbl.MakeSeeded` + +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-Hashtbl.md#val-randomize)). + +since 4.00 + +## Parameters + +``` +module H : SeededHashedType +``` + +## Signature + +``` +type key = H.t +``` +``` +type !'a t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md new file mode 100644 index 000000000..6c2dc6de5 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md @@ -0,0 +1,23 @@ + +# Module type `Hashtbl.HashedType` + +The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md new file mode 100644 index 000000000..c4d7f8b23 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md @@ -0,0 +1,87 @@ + +# Module type `Hashtbl.S` + +The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + +``` +type key +``` +``` +type !'a t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md new file mode 100644 index 000000000..63efb5650 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md @@ -0,0 +1,20 @@ + +# Module type `Hashtbl.SeededHashedType` + +The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 4.00 +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md new file mode 100644 index 000000000..da23d5c25 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md @@ -0,0 +1,86 @@ + +# Module type `Hashtbl.SeededS` + +The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 4.00 +``` +type key +``` +``` +type !'a t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key -> 'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key -> 'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl.md b/docs/api/re/melange/Stdlib-Hashtbl.md new file mode 100644 index 000000000..cd0022e7f --- /dev/null +++ b/docs/api/re/melange/Stdlib-Hashtbl.md @@ -0,0 +1,388 @@ + +# Module `Stdlib.Hashtbl` + +Hash tables and hash functions. + +Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-Map.md). + +The functors [`Make`](./Stdlib-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. + +**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. + +The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. + +See [the examples section](./#examples). + +**Unsynchronized accesses** + +Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +## Generic interface + +``` +type (!'a, !'b) t +``` +The type of hash tables from type `'a` to type `'b`. + +``` +val create : ?random:bool -> int -> ('a, 'b) t +``` +`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. + +A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. + +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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. + +before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. +``` +val clear : ('a, 'b) t -> unit +``` +Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. + +``` +val reset : ('a, 'b) t -> unit +``` +Empty a hash table and shrink the size of the bucket table to its initial size. + +since 4.00 +``` +val copy : ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. + +``` +val add : ('a, 'b) t -> 'a -> 'b -> unit +``` +`Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`. + +**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) + +If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). + +``` +val find : ('a, 'b) t -> 'a -> 'b +``` +`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. + +``` +val find_opt : ('a, 'b) t -> 'a -> 'b option +``` +`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. + +since 4.05 +``` +val find_all : ('a, 'b) t -> 'a -> 'b list +``` +`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. + +``` +val mem : ('a, 'b) t -> 'a -> bool +``` +`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. + +``` +val remove : ('a, 'b) t -> 'a -> unit +``` +`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. + +``` +val replace : ('a, 'b) t -> 'a -> 'b -> unit +``` +`Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. + +``` +val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit +``` +`Hashtbl.iter f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. + +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + +The behavior is not specified if the hash table is modified by `f` during the iteration. + +``` +val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit +``` +`Hashtbl.filter_map_inplace f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. + +Other comments for [`iter`](./#val-iter) apply as well. + +since 4.03 +``` +val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc +``` +`Hashtbl.fold f tbl init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. + +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + +The behavior is not specified if the hash table is modified by `f` during the iteration. + +``` +val length : ('a, 'b) t -> int +``` +`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. + +``` +val randomize : unit -> unit +``` +After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. + +It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. + +Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. + +since 4.00 +``` +val is_randomized : unit -> bool +``` +Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. + +since 4.03 +``` +val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. + +[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. + +since 4.12 +``` +type statistics = { +``` +`num_bindings : int;` +Number of bindings present in the table. Same value as returned by [`length`](./#val-length). + +`num_buckets : int;` +Number of buckets in the table. + +`max_bucket_length : int;` +Maximal number of bindings per bucket. + +`bucket_histogram : int array;` +Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. + +``` +} +``` +since 4.00 +``` +val stats : ('a, 'b) t -> statistics +``` +`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. + +since 4.00 + +## Hash tables and Sequences + +``` +val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t +``` +Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. + +The behavior is not specified if the hash table is modified during the iteration. + +since 4.07 +``` +val to_seq_keys : ('a, _) t -> 'a Seq.t +``` +Same as `Seq.map fst (to_seq m)` + +since 4.07 +``` +val to_seq_values : (_, 'b) t -> 'b Seq.t +``` +Same as `Seq.map snd (to_seq m)` + +since 4.07 +``` +val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`add`](./#val-add) + +since 4.07 +``` +val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`replace`](./#val-replace) + +since 4.07 +``` +val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t +``` +Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. + +since 4.07 + +## Functorial interface + +The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. + +For instance, one might want to specialize a table for integer keys: + +```ocaml + module IntHash = + struct + type t = int + let equal i j = i=j + let hash i = i land max_int + end + + module IntHashtbl = Hashtbl.Make(IntHash) + + let h = IntHashtbl.create 17 in + IntHashtbl.add h 12 "hello" +``` +This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. + +Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. + +``` +module type HashedType = sig ... end +``` +The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + +``` +module type S = sig ... end +``` +The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). + +``` +module Make (H : HashedType) : S with type key = H.t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + +``` +module type SeededHashedType = sig ... end +``` +The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +``` +module type SeededS = sig ... end +``` +The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +``` +module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). + + +## The polymorphic hash functions + +``` +val hash : 'a -> int +``` +`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. + +``` +val seeded_hash : int -> 'a -> int +``` +A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. + +since 4.00 +``` +val hash_param : int -> int -> 'a -> int +``` +`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. + +``` +val seeded_hash_param : int -> int -> int -> 'a -> int +``` +A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. + +since 4.00 + +## 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 + 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 +``` + +### Counting Elements + +Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. + +Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. + +```ocaml + # module Char_tbl = Hashtbl.Make(struct + type t = char + let equal = Char.equal + let hash = Hashtbl.hash + end) + + (* count distinct occurrences of chars in [seq] *) + # let count_chars (seq : char Seq.t) : _ list = + let counts = Char_tbl.create 16 in + Seq.iter + (fun c -> + let count_c = + Char_tbl.find_opt counts c + |> Option.value ~default:0 + in + Char_tbl.replace counts c (count_c + 1)) + seq; + (* turn into a list *) + Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] + |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) + val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = + + (* basic seq from a string *) + # let seq = String.to_seq "hello world, and all the camels in it!" + val seq : char Seq.t = + + # count_chars seq + - : (Char.t * int) list = + [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); + ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); + ('s', 1); ('t', 2); ('w', 1)] + + (* "abcabcabc..." *) + # let seq2 = + Seq.cycle (String.to_seq "abc") |> Seq.take 31 + val seq2 : char Seq.t = + + # String.of_seq seq2 + - : String.t = "abcabcabcabcabcabcabcabcabcabca" + + # count_chars seq2 + - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] + +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-In_channel.md b/docs/api/re/melange/Stdlib-In_channel.md new file mode 100644 index 000000000..7f2f9497e --- /dev/null +++ b/docs/api/re/melange/Stdlib-In_channel.md @@ -0,0 +1,238 @@ + +# Module `Stdlib.In_channel` + +Input channels. + +This module provides functions for working with input channels. + +See [the example section](./#examples) below. + +since 4.14 + +## Channels + +``` +type t = in_channel +``` +The type of input channel. + +``` +type open_flag = open_flag = +``` +``` +| Open_rdonly +``` +open for reading. + +``` +| Open_wronly +``` +open for writing. + +``` +| Open_append +``` +open for appending: always write at end of file. + +``` +| Open_creat +``` +create the file if it does not exist. + +``` +| Open_trunc +``` +empty the file if it already exists. + +``` +| Open_excl +``` +fail if Open\_creat and the file already exists. + +``` +| Open_binary +``` +open in binary mode (no conversion). + +``` +| Open_text +``` +open in text mode (may perform conversions). + +``` +| Open_nonblock +``` +open in non-blocking mode. + +``` + +``` +Opening modes for [`open_gen`](./#val-open_gen). + +``` +val stdin : t +``` +The standard input for the process. + +``` +val open_bin : string -> t +``` +Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. + +``` +val open_text : string -> t +``` +Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). + +``` +val open_gen : open_flag list -> int -> string -> t +``` +`open_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. + +``` +val with_open_bin : string -> (t -> 'a) -> 'a +``` +`with_open_bin fn f` opens a channel `ic` on file `fn` and returns `f ic`. After `f` returns, either with a value or by raising an exception, `ic` is guaranteed to be closed. + +``` +val with_open_text : string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). + +``` +val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). + +``` +val close : t -> unit +``` +Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except [`close`](./#val-close), which does nothing when applied to an already closed channel. + +``` +val close_noerr : t -> unit +``` +Same as [`close`](./#val-close), but ignore all errors. + + +## Input + +``` +val input_char : t -> char option +``` +Read one character from the given input channel. Returns `None` if there are no more characters to read. + +``` +val input_byte : t -> int option +``` +Same as [`input_char`](./#val-input_char), but return the 8-bit integer representing the character. Returns `None` if the end of file was reached. + +``` +val input_line : t -> string option +``` +`input_line ic` reads characters from `ic` until a newline or the end of file is reached. Returns the string of all characters read, without the newline (if any). Returns `None` if the end of the file has been reached. In particular, this will be the case if the last line of input is empty. + +A newline is the character `\n` unless the file is open in text mode and [`Sys.win32`](./Stdlib-Sys.md#val-win32) is `true` in which case it is the sequence of characters `\r\n`. + +``` +val really_input_string : t -> int -> string option +``` +`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. Returns `None` if the end of file is reached before `len` characters have been read. + +If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. + +``` +val input_all : t -> string +``` +`input_all ic` reads all remaining data from `ic`. + +If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. + +``` +val input_lines : t -> string list +``` +`input_lines ic` reads lines using [`input_line`](./#val-input_line) until the end of file is reached. It returns the list of all lines read, in the order they were read. The newline characters that terminate lines are not included in the returned strings. Empty lines produce empty strings. + +since 5.1 + +## Advanced input + +``` +val input : t -> bytes -> int -> int -> int +``` +`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. + +Use [`really_input`](./#val-really_input) to read exactly `len` characters. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val really_input : t -> bytes -> int -> int -> unit option +``` +`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. + +Returns `None` if the end of file is reached before `len` characters have been read. + +If the same channel is read concurrently by multiple threads, the bytes read by `really_input` are not guaranteed to be contiguous. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val fold_lines : ('acc -> string -> 'acc) -> 'acc -> t -> 'acc +``` +`fold_lines f init ic` reads lines from `ic` using [`input_line`](./#val-input_line) until the end of file is reached, and successively passes each line to function `f` in the style of a fold. More precisely, if lines `l1, ..., lN` are read, `fold_lines f init ic` computes `f (... (f (f init l1) l2) ...) lN`. If `f` has no side effects, this is equivalent to `List.fold_left f init (In_channel.input_lines ic)`, but is more efficient since it does not construct the list of all lines read. + +since 5.1 + +## Seeking + +``` +val seek : t -> int64 -> unit +``` +`seek chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. + +``` +val pos : t -> int64 +``` +Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + + +## Attributes + +``` +val length : t -> int64 +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. + +``` +val set_binary_mode : t -> bool -> unit +``` +`set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input. + +`set_binary_mode ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. + +This function has no effect under operating systems that do not distinguish between text mode and binary mode. + +``` +val is_binary_mode : t -> bool +``` +`is_binary_mode ic` returns whether the channel `ic` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). + +since 5.2 +``` +val isatty : t -> bool +``` +`isatty ic` is `true` if `ic` refers to a terminal or console window, `false` otherwise. + +since 5.1 + +## Examples + +Reading the contents of a file: + +```ocaml + let read_file file = In_channel.with_open_bin file In_channel.input_all +``` +Reading a line from stdin: + +```ocaml + let user_input () = In_channel.input_line In_channel.stdin +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Int.md b/docs/api/re/melange/Stdlib-Int.md new file mode 100644 index 000000000..cf5344cce --- /dev/null +++ b/docs/api/re/melange/Stdlib-Int.md @@ -0,0 +1,176 @@ + +# Module `Stdlib.Int` + +Integer values. + +Integers are [`Sys.int_size`](./Stdlib-Sys.md#val-int_size) bits wide and use two's complement representation. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. + +since 4.08 + +## Integers + +``` +type t = int +``` +The type for integer values. + +``` +val zero : int +``` +`zero` is the integer `0`. + +``` +val one : int +``` +`one` is the integer `1`. + +``` +val minus_one : int +``` +`minus_one` is the integer `-1`. + +``` +val neg : int -> int +``` +`neg x` is `~-x`. + +``` +val add : int -> int -> int +``` +`add x y` is the addition `x + y`. + +``` +val sub : int -> int -> int +``` +`sub x y` is the subtraction `x - y`. + +``` +val mul : int -> int -> int +``` +`mul x y` is the multiplication `x * y`. + +``` +val div : int -> int -> int +``` +`div x y` is the division `x / y`. See [`Stdlib.(/)`](./Stdlib.md#val-\(/\)) for details. + +``` +val rem : int -> int -> int +``` +`rem x y` is the remainder `x mod y`. See [`Stdlib.(mod)`](./Stdlib.md#val-\(mod\)) for details. + +``` +val succ : int -> int +``` +`succ x` is `add x 1`. + +``` +val pred : int -> int +``` +`pred x` is `sub x 1`. + +``` +val abs : int -> int +``` +`abs x` is the absolute value of `x`. That is `x` if `x` is positive and `neg x` if `x` is negative. **Warning.** This may be negative if the argument is [`min_int`](./#val-min_int). + +``` +val max_int : int +``` +`max_int` is the greatest representable integer, `2``Sys.int_size - 1``-1`. + +``` +val min_int : int +``` +`min_int` is the smallest representable integer, `-2``Sys.int_size - 1`. + +``` +val logand : int -> int -> int +``` +`logand x y` is the bitwise logical and of `x` and `y`. + +``` +val logor : int -> int -> int +``` +`logor x y` is the bitwise logical or of `x` and `y`. + +``` +val logxor : int -> int -> int +``` +`logxor x y` is the bitwise logical exclusive or of `x` and `y`. + +``` +val lognot : int -> int +``` +`lognot x` is the bitwise logical negation of `x`. + +``` +val shift_left : int -> int -> int +``` +`shift_left x n` shifts `x` to the left by `n` bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). + +``` +val shift_right : int -> int -> int +``` +`shift_right x n` shifts `x` to the right by `n` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). + +``` +val shift_right_logical : int -> int -> int +``` +`shift_right x n` shifts `x` to the right by `n` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). + + +## Predicates and comparisons + +``` +val equal : int -> int -> bool +``` +`equal x y` is `true` if and only if `x = y`. + +``` +val compare : int -> int -> int +``` +`compare x y` is [`Stdlib.compare`](./Stdlib.md#val-compare)` x y` but more efficient. + +``` +val min : int -> int -> int +``` +Return the smaller of the two arguments. + +since 4.13 +``` +val max : int -> int -> int +``` +Return the greater of the two arguments. + +since 4.13 + +## Converting + +``` +val to_float : int -> float +``` +`to_float x` is `x` as a floating point number. + +``` +val of_float : float -> int +``` +`of_float x` truncates `x` to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. + +``` +val to_string : int -> string +``` +`to_string x` is the written representation of `x` in decimal. + +``` +val seeded_hash : int -> int -> int +``` +A seeded hash function for ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.1 +``` +val hash : int -> int +``` +An unseeded hash function for ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Int32.md b/docs/api/re/melange/Stdlib-Int32.md new file mode 100644 index 000000000..0f3011b3a --- /dev/null +++ b/docs/api/re/melange/Stdlib-Int32.md @@ -0,0 +1,237 @@ + +# Module `Stdlib.Int32` + +32-bit integers. + +This module provides operations on the type `int32` of signed 32-bit integers. Unlike the built-in `int` type, the type `int32` is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over `int32` are taken modulo 232. + +Performance notice: values of type `int32` occupy more memory space than values of type `int`, and arithmetic operations on `int32` are generally slower than those on `int`. Use `int32` only when the application requires exact 32-bit arithmetic. + +Literals for 32-bit integers are suffixed by l: + +```ocaml + let zero: int32 = 0l + let one: int32 = 1l + let m_one: int32 = -1l +``` +``` +val zero : int32 +``` +The 32-bit integer 0. + +``` +val one : int32 +``` +The 32-bit integer 1\. + +``` +val minus_one : int32 +``` +The 32-bit integer \-1. + +``` +val neg : int32 -> int32 +``` +Unary negation. + +``` +val add : int32 -> int32 -> int32 +``` +Addition. + +``` +val sub : int32 -> int32 -> int32 +``` +Subtraction. + +``` +val mul : int32 -> int32 -> int32 +``` +Multiplication. + +``` +val div : int32 -> int32 -> int32 +``` +Integer division. This division rounds the real quotient of its arguments towards zero, as specified for [`Stdlib.(/)`](./Stdlib.md#val-\(/\)). + +raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. +``` +val unsigned_div : int32 -> int32 -> int32 +``` +Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 32-bit integers. + +since 4.08 +``` +val rem : int32 -> int32 -> int32 +``` +Integer remainder. If `y` is not zero, the result of `Int32.rem x y` satisfies the following property: `x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)`. If `y = 0`, `Int32.rem x y` raises `Division_by_zero`. + +``` +val unsigned_rem : int32 -> int32 -> int32 +``` +Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 32-bit integers. + +since 4.08 +``` +val succ : int32 -> int32 +``` +Successor. `Int32.succ x` is `Int32.add x Int32.one`. + +``` +val pred : int32 -> int32 +``` +Predecessor. `Int32.pred x` is `Int32.sub x Int32.one`. + +``` +val abs : int32 -> int32 +``` +`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. + +``` +val max_int : int32 +``` +The greatest representable 32-bit integer, 231 \- 1\. + +``` +val min_int : int32 +``` +The smallest representable 32-bit integer, \-231. + +``` +val logand : int32 -> int32 -> int32 +``` +Bitwise logical and. + +``` +val logor : int32 -> int32 -> int32 +``` +Bitwise logical or. + +``` +val logxor : int32 -> int32 -> int32 +``` +Bitwise logical exclusive or. + +``` +val lognot : int32 -> int32 +``` +Bitwise logical negation. + +``` +val shift_left : int32 -> int -> int32 +``` +`Int32.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 32`. + +``` +val shift_right : int32 -> int -> int32 +``` +`Int32.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 32`. + +``` +val shift_right_logical : int32 -> int -> int32 +``` +`Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 32`. + +``` +val of_int : int -> int32 +``` +Convert the given integer (type `int`) to a 32-bit integer (type `int32`). On 64-bit platforms, the argument is taken modulo 232. + +``` +val to_int : int32 -> int +``` +Convert the given 32-bit integer (type `int32`) to an integer (type `int`). On 32-bit platforms, the 32-bit integer is taken modulo 231, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. + +``` +val unsigned_to_int : int32 -> int option +``` +Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. + +since 4.08 +``` +val of_float : float -> int32 +``` +Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int32.min_int`](./#val-min_int), [`Int32.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. + +``` +val to_float : int32 -> float +``` +Convert the given 32-bit integer to a floating-point number. + +``` +val of_string : string -> int32 +``` +Convert the given string to a 32-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. + +The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int32.max_int+1]`. If the input exceeds [`Int32.max_int`](./#val-max_int) it is converted to the signed integer `Int32.min_int + input - Int32.max_int - 1`. + +The `_` (underscore) character can appear anywhere in the string and is ignored. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int32. +``` +val of_string_opt : string -> int32 option +``` +Same as `of_string`, but return `None` instead of raising. + +since 4.05 +``` +val to_string : int32 -> string +``` +Return the string representation of its argument, in signed decimal. + +``` +val bits_of_float : float -> int32 +``` +Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa. + +``` +val float_of_bits : int32 -> float +``` +Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`. + +``` +type t = int32 +``` +An alias for the type of 32-bit integers. + +``` +val compare : t -> t -> int +``` +The comparison function for 32-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + +``` +val unsigned_compare : t -> t -> int +``` +Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 32-bit integers. + +since 4.08 +``` +val equal : t -> t -> bool +``` +The equal function for int32s. + +since 4.03 +``` +val min : t -> t -> t +``` +Return the smaller of the two arguments. + +since 4.13 +``` +val max : t -> t -> t +``` +Return the greater of the two arguments. + +since 4.13 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for 32-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for 32-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Int64.md b/docs/api/re/melange/Stdlib-Int64.md new file mode 100644 index 000000000..f7d334e83 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Int64.md @@ -0,0 +1,257 @@ + +# Module `Stdlib.Int64` + +64-bit integers. + +This module provides operations on the type `int64` of signed 64-bit integers. Unlike the built-in `int` type, the type `int64` is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over `int64` are taken modulo 264 + +Performance notice: values of type `int64` occupy more memory space than values of type `int`, and arithmetic operations on `int64` are generally slower than those on `int`. Use `int64` only when the application requires exact 64-bit arithmetic. + +Literals for 64-bit integers are suffixed by L: + +```ocaml + let zero: int64 = 0L + let one: int64 = 1L + let m_one: int64 = -1L +``` +``` +val zero : int64 +``` +The 64-bit integer 0. + +``` +val one : int64 +``` +The 64-bit integer 1\. + +``` +val minus_one : int64 +``` +The 64-bit integer \-1. + +``` +val neg : int64 -> int64 +``` +Unary negation. + +``` +val add : int64 -> int64 -> int64 +``` +Addition. + +``` +val sub : int64 -> int64 -> int64 +``` +Subtraction. + +``` +val mul : int64 -> int64 -> int64 +``` +Multiplication. + +``` +val div : int64 -> int64 -> int64 +``` +Integer division. + +raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/). +``` +val unsigned_div : int64 -> int64 -> int64 +``` +Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 64-bit integers. + +since 4.08 +``` +val rem : int64 -> int64 -> int64 +``` +Integer remainder. If `y` is not zero, the result of `Int64.rem x y` satisfies the following property: `x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)`. If `y = 0`, `Int64.rem x y` raises `Division_by_zero`. + +``` +val unsigned_rem : int64 -> int64 -> int64 +``` +Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 64-bit integers. + +since 4.08 +``` +val succ : int64 -> int64 +``` +Successor. `Int64.succ x` is `Int64.add x Int64.one`. + +``` +val pred : int64 -> int64 +``` +Predecessor. `Int64.pred x` is `Int64.sub x Int64.one`. + +``` +val abs : int64 -> int64 +``` +`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. + +``` +val max_int : int64 +``` +The greatest representable 64-bit integer, 263 \- 1\. + +``` +val min_int : int64 +``` +The smallest representable 64-bit integer, \-263. + +``` +val logand : int64 -> int64 -> int64 +``` +Bitwise logical and. + +``` +val logor : int64 -> int64 -> int64 +``` +Bitwise logical or. + +``` +val logxor : int64 -> int64 -> int64 +``` +Bitwise logical exclusive or. + +``` +val lognot : int64 -> int64 +``` +Bitwise logical negation. + +``` +val shift_left : int64 -> int -> int64 +``` +`Int64.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 64`. + +``` +val shift_right : int64 -> int -> int64 +``` +`Int64.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 64`. + +``` +val shift_right_logical : int64 -> int -> int64 +``` +`Int64.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 64`. + +``` +val of_int : int -> int64 +``` +Convert the given integer (type `int`) to a 64-bit integer (type `int64`). + +``` +val to_int : int64 -> int +``` +Convert the given 64-bit integer (type `int64`) to an integer (type `int`). On 64-bit platforms, the 64-bit integer is taken modulo 263, i.e. the high-order bit is lost during the conversion. On 32-bit platforms, the 64-bit integer is taken modulo 231, i.e. the top 33 bits are lost during the conversion. + +``` +val unsigned_to_int : int64 -> int option +``` +Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. + +since 4.08 +``` +val of_float : float -> int64 +``` +Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int64.min_int`](./#val-min_int), [`Int64.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. + +``` +val to_float : int64 -> float +``` +Convert the given 64-bit integer to a floating-point number. + +``` +val of_int32 : int32 -> int64 +``` +Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`). + +``` +val to_int32 : int64 -> int32 +``` +Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). The 64-bit integer is taken modulo 232, i.e. the top 32 bits are lost during the conversion. + +``` +val of_nativeint : nativeint -> int64 +``` +Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`). + +``` +val to_nativeint : int64 -> nativeint +``` +Convert the given 64-bit integer (type `int64`) to a native integer. On 32-bit platforms, the 64-bit integer is taken modulo 232. On 64-bit platforms, the conversion is exact. + +``` +val of_string : string -> int64 +``` +Convert the given string to a 64-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. + +The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int64.max_int+1]`. If the input exceeds [`Int64.max_int`](./#val-max_int) it is converted to the signed integer `Int64.min_int + input - Int64.max_int - 1`. + +The `_` (underscore) character can appear anywhere in the string and is ignored. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int64. +``` +val of_string_opt : string -> int64 option +``` +Same as `of_string`, but return `None` instead of raising. + +since 4.05 +``` +val to_string : int64 -> string +``` +Return the string representation of its argument, in decimal. + +``` +val bits_of_float : float -> int64 +``` +Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. Bit 63 of the result represents the sign of the float; bits 62 to 52 represent the (biased) exponent; bits 51 to 0 represent the mantissa. + +``` +val float_of_bits : int64 -> float +``` +Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`. + +``` +type t = int64 +``` +An alias for the type of 64-bit integers. + +``` +val compare : t -> t -> int +``` +The comparison function for 64-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int64` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). + +``` +val unsigned_compare : t -> t -> int +``` +Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 64-bit integers. + +since 4.08 +``` +val equal : t -> t -> bool +``` +The equal function for int64s. + +since 4.03 +``` +val min : t -> t -> t +``` +Return the smaller of the two arguments. + +since 4.13 +``` +val max : t -> t -> t +``` +Return the greater of the two arguments. + +since 4.13 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for 64-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.1 +``` +val hash : t -> int +``` +An unseeded hash function for 64-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-LargeFile.md b/docs/api/re/melange/Stdlib-LargeFile.md new file mode 100644 index 000000000..b4e663dc2 --- /dev/null +++ b/docs/api/re/melange/Stdlib-LargeFile.md @@ -0,0 +1,23 @@ + +# Module `Stdlib.LargeFile` + +Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. + +``` +val seek_out : out_channel -> int64 -> unit +``` +``` +val pos_out : out_channel -> int64 +``` +``` +val out_channel_length : out_channel -> int64 +``` +``` +val seek_in : in_channel -> int64 -> unit +``` +``` +val pos_in : in_channel -> int64 +``` +``` +val in_channel_length : in_channel -> int64 +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Lazy.md b/docs/api/re/melange/Stdlib-Lazy.md new file mode 100644 index 000000000..519b7cec5 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Lazy.md @@ -0,0 +1,95 @@ + +# Module `Stdlib.Lazy` + +Deferred computations. + +``` +type 'a t = 'a CamlinternalLazy.t +``` +A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. The special expression syntax `lazy (expr)` makes a suspension of the computation of `expr`, without computing `expr` itself yet. "Forcing" the suspension will then compute `expr` and return its result. Matching a suspension with the special pattern syntax `lazy(pattern)` also computes the underlying expression and tries to bind it to `pattern`: + +```ocaml + let lazy_option_map f x = + match x with + | lazy (Some x) -> Some (Lazy.force f x) + | _ -> None +``` +Note: If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may be forced even outside of the case ultimately selected by the pattern matching. In the example above, the suspension `x` is always computed. + +Note: `lazy_t` is the built-in type constructor used by the compiler for the `lazy` keyword. You should not use it directly. Always use `Lazy.t` instead. + +Note: `Lazy.force` is not concurrency-safe. If you use this module with multiple fibers, systhreads or domains, then you will need to add some locks. The module however ensures memory-safety, and hence, concurrently accessing this module will not lead to a crash but the behaviour is unspecified. + +Note: if the program is compiled with the `-rectypes` option, ill-founded recursive definitions of the form `let rec x = lazy x` or `let rec x = lazy(lazy(...(lazy x)))` are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the `-rectypes` option, such ill-founded recursive definitions are rejected by the type-checker. + +``` +exception Undefined +``` +Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or when the suspension tries to force itself recursively. + +``` +val force : 'a t -> 'a +``` +`force x` forces the suspension `x` and returns its result. If `x` has already been forced, `Lazy.force x` returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. + +raises [`Undefined`](./#exception-Undefined) (see Undefined). + +## Iterators + +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f x` returns a suspension that, when forced, forces `x` and applies `f` to its value. + +It is equivalent to `lazy (f (Lazy.force x))`. + +since 4.13 + +## Reasoning on already-forced suspensions + +``` +val is_val : 'a t -> bool +``` +`is_val x` returns `true` if `x` has already been forced and did not raise an exception. + +since 4.00 +``` +val from_val : 'a -> 'a t +``` +`from_val v` evaluates `v` first (as any function would) and returns an already-forced suspension of its result. It is the same as `let x = v in lazy x`, but uses dynamic tests to optimize suspension creation in some cases. + +since 4.00 +``` +val map_val : ('a -> 'b) -> 'a t -> 'b t +``` +`map_val f x` applies `f` directly if `x` is already forced, otherwise it behaves as `map f x`. + +When `x` is already forced, this behavior saves the construction of a suspension, but on the other hand it performs more work eagerly that may not be useful if you never force the function result. + +If `f` raises an exception, it will be raised immediately when `is_val x`, or raised only when forcing the thunk otherwise. + +If `map_val f x` does not raise an exception, then `is_val (map_val f x)` is equal to `is_val x`. + +since 4.13 + +## Advanced + +The following definitions are for advanced uses only; they require familiarity with the lazy compilation scheme to be used appropriately. + +``` +val from_fun : (unit -> 'a) -> 'a t +``` +`from_fun f` is the same as `lazy (f ())` but slightly more efficient. + +It should only be used if the function `f` is already defined. In particular it is always less efficient to write `from_fun (fun () -> expr)` than `lazy expr`. + +since 4.00 +``` +val force_val : 'a t -> 'a +``` +`force_val x` forces the suspension `x` and returns its result. If `x` has already been forced, `force_val x` returns the same value again without recomputing it. + +If the computation of `x` raises an exception, it is unspecified whether `force_val x` raises the same exception or [`Undefined`](./#exception-Undefined). + +raises [`Undefined`](./#exception-Undefined) if the forcing of x tries to force x itself recursively. +raises [`Undefined`](./#exception-Undefined) (see Undefined). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Lexing.md b/docs/api/re/melange/Stdlib-Lexing.md new file mode 100644 index 000000000..44ca6045c --- /dev/null +++ b/docs/api/re/melange/Stdlib-Lexing.md @@ -0,0 +1,136 @@ + +# Module `Stdlib.Lexing` + +The run-time library for lexers generated by `ocamllex`. + + +## Positions + +``` +type position = { +``` +`pos_fname : string;` +`pos_lnum : int;` +`pos_bol : int;` +`pos_cnum : int;` +``` +} +``` +A value of type `position` describes a point in a source file. `pos_fname` is the file name; `pos_lnum` is the line number; `pos_bol` is the offset of the beginning of the line (number of characters between the beginning of the lexbuf and the beginning of the line); `pos_cnum` is the offset of the position (number of characters between the beginning of the lexbuf and the position). The difference between `pos_cnum` and `pos_bol` is the character offset within the line (i.e. the column number, assuming each character is one column wide). + +See the documentation of type `lexbuf` for information about how the lexing engine will manage positions. + +``` +val dummy_pos : position +``` +A value of type `position`, guaranteed to be different from any valid position. + + +## Lexer buffers + +``` +type lexbuf = { +``` +`refill_buff : lexbuf -> unit;` +`mutable lex_buffer : bytes;` +`mutable lex_buffer_len : int;` +`mutable lex_abs_pos : int;` +`mutable lex_start_pos : int;` +`mutable lex_curr_pos : int;` +`mutable lex_last_pos : int;` +`mutable lex_last_action : int;` +`mutable lex_eof_reached : bool;` +`mutable lex_mem : int array;` +`mutable lex_start_p : position;` +`mutable lex_curr_p : position;` +``` +} +``` +The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input. + +Lexers can optionally maintain the `lex_curr_p` and `lex_start_p` position fields. This "position tracking" mode is the default, and it corresponds to passing `~with_position:true` to functions that create lexer buffers. In this mode, the lexing engine and lexer actions are co-responsible for properly updating the position fields, as described in the next paragraph. When the mode is explicitly disabled (with `~with_position:false`), the lexing engine will not touch the position fields and the lexer actions should be careful not to do it either; the `lex_curr_p` and `lex_start_p` field will then always hold the `dummy_pos` invalid position. Not tracking positions avoids allocations and memory writes and can significantly improve the performance of the lexer in contexts where `lex_start_p` and `lex_curr_p` are not needed. + +Position tracking mode works as follows. At each token, the lexing engine will copy `lex_curr_p` to `lex_start_p`, then change the `pos_cnum` field of `lex_curr_p` by updating it with the number of characters read since the start of the `lexbuf`. The other fields are left unchanged by the lexing engine. In order to keep them accurate, they must be initialised before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end of line \-- see also `new_line`). + +``` +val from_channel : ?with_positions:bool -> in_channel -> lexbuf +``` +Create a lexer buffer on the given input channel. `Lexing.from_channel inchan` returns a lexer buffer which reads from the input channel `inchan`, at the current reading position. + +``` +val from_string : ?with_positions:bool -> string -> lexbuf +``` +Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached. + +``` +val from_function : ?with_positions:bool -> (bytes -> int -> int) -> lexbuf +``` +Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a byte sequence `s` and a byte count `n`. The function should put `n` bytes or fewer in `s`, starting at index 0, and return the number of bytes provided. A return value of 0 means end of input. + +``` +val set_position : lexbuf -> position -> unit +``` +Set the initial tracked input position for `lexbuf` to a custom value. Ignores `pos_fname`. See [`set_filename`](./#val-set_filename) for changing this field. + +since 4.11 +``` +val set_filename : lexbuf -> string -> unit +``` +Set filename in the initial tracked position to `file` in `lexbuf`. + +since 4.11 +``` +val with_positions : lexbuf -> bool +``` +Tell whether the lexer buffer keeps track of position fields `lex_curr_p` / `lex_start_p`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`). + +When `with_positions` is `false`, lexer actions should not modify position fields. Doing it nevertheless could re-enable the `with_position` mode and degrade performances. + + +## Functions for lexer semantic actions + +The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument `lexbuf`, which, in the code generated by `ocamllex`, is bound to the lexer buffer passed to the parsing function. + +``` +val lexeme : lexbuf -> string +``` +`Lexing.lexeme lexbuf` returns the string matched by the regular expression. + +``` +val lexeme_char : lexbuf -> int -> char +``` +`Lexing.lexeme_char lexbuf i` returns character number `i` in the matched string. + +``` +val lexeme_start : lexbuf -> int +``` +`Lexing.lexeme_start lexbuf` returns the offset in the input stream of the first character of the matched string. The first character of the stream has offset 0. + +``` +val lexeme_end : lexbuf -> int +``` +`Lexing.lexeme_end lexbuf` returns the offset in the input stream of the character following the last character of the matched string. The first character of the stream has offset 0. + +``` +val lexeme_start_p : lexbuf -> position +``` +Like `lexeme_start`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. + +``` +val lexeme_end_p : lexbuf -> position +``` +Like `lexeme_end`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. + +``` +val new_line : lexbuf -> unit +``` +Update the `lex_curr_p` field of the lexbuf to reflect the start of a new line. You can call this function in the semantic action of the rule that matches the end-of-line character. The function does nothing when position tracking is disabled. + +since 3.11 + +## Miscellaneous functions + +``` +val flush_input : lexbuf -> unit +``` +Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill. diff --git a/docs/api/re/melange/Stdlib-List.md b/docs/api/re/melange/Stdlib-List.md new file mode 100644 index 000000000..448c79785 --- /dev/null +++ b/docs/api/re/melange/Stdlib-List.md @@ -0,0 +1,482 @@ + +# Module `Stdlib.List` + +List operations. + +Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. + +The above considerations can usually be ignored if your lists are not longer than about 10000 elements. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + +``` +type 'a t = 'a list = +``` +``` +| [] +``` +``` +| :: of 'a * 'a list +``` +``` + +``` +An alias for the type of lists. + +``` +val length : 'a list -> int +``` +Return the length (number of elements) of the given list. + +``` +val compare_lengths : 'a list -> 'b list -> int +``` +Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. + +since 4.05 +``` +val compare_length_with : 'a list -> int -> int +``` +Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. + +since 4.05 +``` +val is_empty : 'a list -> bool +``` +`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. + +since 5.1 +``` +val cons : 'a -> 'a list -> 'a list +``` +`cons x xs` is `x :: xs` + +since 4.03 (4.05 in ListLabels) +``` +val hd : 'a list -> 'a +``` +Return the first element of the given list. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val tl : 'a list -> 'a list +``` +Return the given list without its first element. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val nth : 'a list -> int -> 'a +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +``` +val nth_opt : 'a list -> int -> 'a option +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.05 +``` +val rev : 'a list -> 'a list +``` +List reversal. + +``` +val init : int -> (int -> 'a) -> 'a list +``` +`init len f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. +since 4.06 +``` +val append : 'a list -> 'a list -> 'a list +``` +`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. + +since 5.1 this function is tail-recursive. +``` +val rev_append : 'a list -> 'a list -> 'a list +``` +`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. + +``` +val concat : 'a list list -> 'a list +``` +Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). + +``` +val flatten : 'a list list -> 'a list +``` +Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). + + +## Comparison + +``` +val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool +``` +`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. + +Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. + +since 4.12 +``` +val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int +``` +`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): + +- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` +- the empty list `[]` is strictly smaller than non-empty lists +Note: the `cmp` function will be called even if the lists have different lengths. + +since 4.12 + +## Iterators + +``` +val iter : ('a -> unit) -> 'a list -> unit +``` +`iter f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. + +``` +val iteri : (int -> 'a -> unit) -> 'a list -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 4.00 +``` +val map : ('a -> 'b) -> 'a list -> 'b list +``` +`map f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. + +``` +val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 4.00 +``` +val rev_map : ('a -> 'b) -> 'a list -> 'b list +``` +`rev_map f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. + +``` +val filter_map : ('a -> 'b option) -> 'a list -> 'b list +``` +`filter_map f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. + +since 4.08 +``` +val concat_map : ('a -> 'b list) -> 'a list -> 'b list +``` +`concat_map f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. + +since 4.10 +``` +val fold_left_map : + ('acc -> 'a -> 'acc * 'b) -> + 'acc -> + 'a list -> + 'acc * 'b list +``` +`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. + +since 4.11 +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc +``` +`fold_left f init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. + +``` +val fold_right : ('a -> 'acc -> 'acc) -> 'a list -> 'acc -> 'acc +``` +`fold_right f [a1; ...; an] init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. + + +## Iterators on two lists + +``` +val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit +``` +`iter2 f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`map2 f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`rev_map2 f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. + +``` +val fold_left2 : + ('acc -> 'a -> 'b -> 'acc) -> + 'acc -> + 'a list -> + 'b list -> + 'acc +``` +`fold_left2 f init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val fold_right2 : + ('a -> 'b -> 'acc -> 'acc) -> + 'a list -> + 'b list -> + 'acc -> + 'acc +``` +`fold_right2 f [a1; ...; an] [b1; ...; bn] init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. + +## List scanning + +``` +val for_all : ('a -> bool) -> 'a list -> bool +``` +`for_all f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. + +``` +val exists : ('a -> bool) -> 'a list -> bool +``` +`exists f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. + +``` +val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val mem : 'a -> 'a list -> bool +``` +`mem a set` is true if and only if `a` is equal to an element of `set`. + +``` +val memq : 'a -> 'a list -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. + + +## List searching + +``` +val find : ('a -> bool) -> 'a list -> 'a +``` +`find f l` returns the first element of the list `l` that satisfies the predicate `f`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. +``` +val find_opt : ('a -> bool) -> 'a list -> 'a option +``` +`find f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. + +since 4.05 +``` +val find_index : ('a -> bool) -> 'a list -> int option +``` +`find_index f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. + +It returns `None` if there is no such element. + +since 5.1 +``` +val find_map : ('a -> 'b option) -> 'a list -> 'b option +``` +`find_map f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. + +since 4.10 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a list -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 5.1 +``` +val filter : ('a -> bool) -> 'a list -> 'a list +``` +`filter f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. + +``` +val find_all : ('a -> bool) -> 'a list -> 'a list +``` +`find_all` is another name for [`filter`](./#val-filter). + +``` +val filteri : (int -> 'a -> bool) -> 'a list -> 'a list +``` +Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 4.11 + +## List manipulation + +``` +val take : int -> 'a list -> 'a list +``` +`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. + +`n` must be nonnegative. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val drop : int -> 'a list -> 'a list +``` +`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. + +`n` must be nonnegative. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val take_while : ('a -> bool) -> 'a list -> 'a list +``` +`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. + +since 5.3 +``` +val drop_while : ('a -> bool) -> 'a list -> 'a list +``` +`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. + +since 5.3 +``` +val partition : ('a -> bool) -> 'a list -> 'a list * 'a list +``` +`partition f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. + +``` +val partition_map : ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list +``` +`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: + +- if `f x` is `Left y1`, then `y1` is in `l1`, and +- if `f x` is `Right y2`, then `y2` is in `l2`. +The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. + +In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. + +since 4.12 + +## Association lists + +``` +val assoc : 'a -> ('a * 'b) list -> 'b +``` +`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. +``` +val assoc_opt : 'a -> ('a * 'b) list -> 'b option +``` +`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. + +since 4.05 +``` +val assq : 'a -> ('a * 'b) list -> 'b +``` +Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. + +``` +val assq_opt : 'a -> ('a * 'b) list -> 'b option +``` +Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. + +since 4.05 +``` +val mem_assoc : 'a -> ('a * 'b) list -> bool +``` +Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. + +``` +val mem_assq : 'a -> ('a * 'b) list -> bool +``` +Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. + +``` +val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. + +``` +val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. + + +## Lists of pairs + +``` +val split : ('a * 'b) list -> 'a list * 'b list +``` +Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. + +``` +val combine : 'a list -> 'b list -> ('a * 'b) list +``` +Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. + +## Sorting + +``` +val sort : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. + +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + +``` +val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). + +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + +``` +val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + +``` +val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but also remove duplicates. + +since 4.02 (4.03 in ListLabels) +``` +val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list +``` +Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). + + +## Lists and Sequences + +``` +val to_seq : 'a list -> 'a Seq.t +``` +Iterate on the list. + +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a list +``` +Create a list from a sequence. + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-ListLabels.md b/docs/api/re/melange/Stdlib-ListLabels.md new file mode 100644 index 000000000..03b11df1f --- /dev/null +++ b/docs/api/re/melange/Stdlib-ListLabels.md @@ -0,0 +1,482 @@ + +# Module `Stdlib.ListLabels` + +List operations. + +Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. + +The above considerations can usually be ignored if your lists are not longer than about 10000 elements. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + +``` +type 'a t = 'a list = +``` +``` +| [] +``` +``` +| :: of 'a * 'a list +``` +``` + +``` +An alias for the type of lists. + +``` +val length : 'a list -> int +``` +Return the length (number of elements) of the given list. + +``` +val compare_lengths : 'a list -> 'b list -> int +``` +Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. + +since 4.05 +``` +val compare_length_with : 'a list -> len:int -> int +``` +Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. + +since 4.05 +``` +val is_empty : 'a list -> bool +``` +`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. + +since 5.1 +``` +val cons : 'a -> 'a list -> 'a list +``` +`cons x xs` is `x :: xs` + +since 4.03 (4.05 in ListLabels) +``` +val hd : 'a list -> 'a +``` +Return the first element of the given list. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val tl : 'a list -> 'a list +``` +Return the given list without its first element. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. +``` +val nth : 'a list -> int -> 'a +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. + +raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +``` +val nth_opt : 'a list -> int -> 'a option +``` +Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.05 +``` +val rev : 'a list -> 'a list +``` +List reversal. + +``` +val init : len:int -> f:(int -> 'a) -> 'a list +``` +`init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. +since 4.06 +``` +val append : 'a list -> 'a list -> 'a list +``` +`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. + +since 5.1 this function is tail-recursive. +``` +val rev_append : 'a list -> 'a list -> 'a list +``` +`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. + +``` +val concat : 'a list list -> 'a list +``` +Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). + +``` +val flatten : 'a list list -> 'a list +``` +Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). + + +## Comparison + +``` +val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool +``` +`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. + +Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. + +since 4.12 +``` +val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int +``` +`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): + +- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` +- the empty list `[]` is strictly smaller than non-empty lists +Note: the `cmp` function will be called even if the lists have different lengths. + +since 4.12 + +## Iterators + +``` +val iter : f:('a -> unit) -> 'a list -> unit +``` +`iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. + +``` +val iteri : f:(int -> 'a -> unit) -> 'a list -> unit +``` +Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 4.00 +``` +val map : f:('a -> 'b) -> 'a list -> 'b list +``` +`map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. + +``` +val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list +``` +Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 4.00 +``` +val rev_map : f:('a -> 'b) -> 'a list -> 'b list +``` +`rev_map ~f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. + +``` +val filter_map : f:('a -> 'b option) -> 'a list -> 'b list +``` +`filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. + +since 4.08 +``` +val concat_map : f:('a -> 'b list) -> 'a list -> 'b list +``` +`concat_map ~f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. + +since 4.10 +``` +val fold_left_map : + f:('acc -> 'a -> 'acc * 'b) -> + init:'acc -> + 'a list -> + 'acc * 'b list +``` +`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. + +since 4.11 +``` +val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc +``` +`fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. + +``` +val fold_right : f:('a -> 'acc -> 'acc) -> 'a list -> init:'acc -> 'acc +``` +`fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. + + +## Iterators on two lists + +``` +val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit +``` +`iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list +``` +`rev_map2 ~f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. + +``` +val fold_left2 : + f:('acc -> 'a -> 'b -> 'acc) -> + init:'acc -> + 'a list -> + 'b list -> + 'acc +``` +`fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val fold_right2 : + f:('a -> 'b -> 'acc -> 'acc) -> + 'a list -> + 'b list -> + init:'acc -> + 'acc +``` +`fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. + +## List scanning + +``` +val for_all : f:('a -> bool) -> 'a list -> bool +``` +`for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. + +``` +val exists : f:('a -> bool) -> 'a list -> bool +``` +`exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. + +``` +val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`for_all`](./#val-for_all), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool +``` +Same as [`exists`](./#val-exists), but for a two-argument predicate. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. +``` +val mem : 'a -> set:'a list -> bool +``` +`mem a ~set` is true if and only if `a` is equal to an element of `set`. + +``` +val memq : 'a -> set:'a list -> bool +``` +Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. + + +## List searching + +``` +val find : f:('a -> bool) -> 'a list -> 'a +``` +`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. +``` +val find_opt : f:('a -> bool) -> 'a list -> 'a option +``` +`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. + +since 4.05 +``` +val find_index : f:('a -> bool) -> 'a list -> int option +``` +`find_index ~f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. + +It returns `None` if there is no such element. + +since 5.1 +``` +val find_map : f:('a -> 'b option) -> 'a list -> 'b option +``` +`find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. + +since 4.10 +``` +val find_mapi : f:(int -> 'a -> 'b option) -> 'a list -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 5.1 +``` +val filter : f:('a -> bool) -> 'a list -> 'a list +``` +`filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. + +``` +val find_all : f:('a -> bool) -> 'a list -> 'a list +``` +`find_all` is another name for [`filter`](./#val-filter). + +``` +val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list +``` +Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +since 4.11 + +## List manipulation + +``` +val take : int -> 'a list -> 'a list +``` +`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. + +`n` must be nonnegative. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val drop : int -> 'a list -> 'a list +``` +`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. + +`n` must be nonnegative. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 5.3 +``` +val take_while : f:('a -> bool) -> 'a list -> 'a list +``` +`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. + +since 5.3 +``` +val drop_while : f:('a -> bool) -> 'a list -> 'a list +``` +`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. + +since 5.3 +``` +val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list +``` +`partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. + +``` +val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list +``` +`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: + +- if `f x` is `Left y1`, then `y1` is in `l1`, and +- if `f x` is `Right y2`, then `y2` is in `l2`. +The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. + +In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. + +since 4.12 + +## Association lists + +``` +val assoc : 'a -> ('a * 'b) list -> 'b +``` +`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. +``` +val assoc_opt : 'a -> ('a * 'b) list -> 'b option +``` +`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. + +since 4.05 +``` +val assq : 'a -> ('a * 'b) list -> 'b +``` +Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. + +``` +val assq_opt : 'a -> ('a * 'b) list -> 'b option +``` +Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. + +since 4.05 +``` +val mem_assoc : 'a -> map:('a * 'b) list -> bool +``` +Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. + +``` +val mem_assq : 'a -> map:('a * 'b) list -> bool +``` +Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. + +``` +val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. + +``` +val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list +``` +Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. + + +## Lists of pairs + +``` +val split : ('a * 'b) list -> 'a list * 'b list +``` +Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. + +``` +val combine : 'a list -> 'b list -> ('a * 'b) list +``` +Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. + +## Sorting + +``` +val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. + +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + +``` +val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). + +The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. + +``` +val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. + +``` +val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list +``` +Same as [`sort`](./#val-sort), but also remove duplicates. + +since 4.02 (4.03 in ListLabels) +``` +val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list +``` +Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). + + +## Lists and Sequences + +``` +val to_seq : 'a list -> 'a Seq.t +``` +Iterate on the list. + +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a list +``` +Create a list from a sequence. + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md new file mode 100644 index 000000000..d02ffc06f --- /dev/null +++ b/docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md @@ -0,0 +1,12 @@ + +# Parameter `Make.Ord` + +``` +type t +``` +The type of the map keys. + +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Map-Make.md b/docs/api/re/melange/Stdlib-Map-Make.md new file mode 100644 index 000000000..ce73f7b9a --- /dev/null +++ b/docs/api/re/melange/Stdlib-Map-Make.md @@ -0,0 +1,315 @@ + +# Module `Map.Make` + +Functor building an implementation of the map structure given a totally ordered type. + + +## Parameters + +``` +module Ord : OrderedType +``` + +## Signature + + +## Maps + +``` +type key = Ord.t +``` +The type of the map keys. + +``` +type !+'a t +``` +The type of maps from type `key` to type `'a`. + +``` +val empty : 'a t +``` +The empty map. + +``` +val add : key -> 'a -> 'a t -> 'a t +``` +`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key -> 'a -> 'a list t -> 'a list t +``` +`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + +since 5.1 +``` +val update : key -> ('a option -> 'a option) -> 'a t -> 'a t +``` +`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. + +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +before 4.03 Physical equality was not ensured. +``` +val merge : + (key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + +since 3.12 +``` +val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. + +since 3.12 + +## Bindings + +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). + +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 4.05 + +## Searching + +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + +since 4.05 +``` +val find_first : (key -> bool) -> 'a t -> key * 'a +``` +`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + +since 4.05 +``` +val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 +``` +val find_last : (key -> bool) -> 'a t -> key * 'a +``` +`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +since 4.05 +``` +val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 + +## Traversing + +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + +## Transforming + +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + +``` +val filter : (key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists + +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + +since 4.11 +``` +val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +since 3.12 + +## Predicates and comparisons + +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. + +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + +``` +val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + +``` +val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + +``` +val for_all : (key -> 'a -> bool) -> 'a t -> bool +``` +`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. + +since 3.12 +``` +val exists : (key -> 'a -> bool) -> 'a t -> bool +``` +`exists f m` checks if at least one binding of the map satisfies the predicate `f`. + +since 3.12 + +## Converting + +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. + +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys + +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys + +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. + +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md new file mode 100644 index 000000000..269a6a025 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md @@ -0,0 +1,14 @@ + +# Module type `Map.OrderedType` + +Input signature of the functor [`Make`](./Stdlib-Map-Make.md). + +``` +type t +``` +The type of the map keys. + +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Map-module-type-S.md b/docs/api/re/melange/Stdlib-Map-module-type-S.md new file mode 100644 index 000000000..849b1ff51 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Map-module-type-S.md @@ -0,0 +1,306 @@ + +# Module type `Map.S` + +Output signature of the functor [`Make`](./Stdlib-Map-Make.md). + + +## Maps + +``` +type key +``` +The type of the map keys. + +``` +type !+'a t +``` +The type of maps from type `key` to type `'a`. + +``` +val empty : 'a t +``` +The empty map. + +``` +val add : key -> 'a -> 'a t -> 'a t +``` +`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key -> 'a -> 'a list t -> 'a list t +``` +`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + +since 5.1 +``` +val update : key -> ('a option -> 'a option) -> 'a t -> 'a t +``` +`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. + +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +before 4.03 Physical equality was not ensured. +``` +val merge : + (key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + +since 3.12 +``` +val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. + +since 3.12 + +## Bindings + +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-Map-Make.md). + +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 4.05 + +## Searching + +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + +since 4.05 +``` +val find_first : (key -> bool) -> 'a t -> key * 'a +``` +`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + +since 4.05 +``` +val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 +``` +val find_last : (key -> bool) -> 'a t -> key * 'a +``` +`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +since 4.05 +``` +val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 + +## Traversing + +``` +val iter : (key -> 'a -> unit) -> 'a t -> unit +``` +`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc +``` +`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + +## Transforming + +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + +``` +val filter : (key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists + +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + +since 4.11 +``` +val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +since 3.12 + +## Predicates and comparisons + +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. + +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + +``` +val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + +``` +val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + +``` +val for_all : (key -> 'a -> bool) -> 'a t -> bool +``` +`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. + +since 3.12 +``` +val exists : (key -> 'a -> bool) -> 'a t -> bool +``` +`exists f m` checks if at least one binding of the map satisfies the predicate `f`. + +since 3.12 + +## Converting + +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. + +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys + +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys + +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. + +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Map.md b/docs/api/re/melange/Stdlib-Map.md new file mode 100644 index 000000000..e91aa6845 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Map.md @@ -0,0 +1,39 @@ + +# Module `Stdlib.Map` + +Association tables over ordered types. + +This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + +For instance: + +```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") +``` +This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. + +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-Map-Make.md). + +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-Map-Make.md). + +``` +module Make (Ord : OrderedType) : S with type key = Ord.t +``` +Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-Marshal.md b/docs/api/re/melange/Stdlib-Marshal.md new file mode 100644 index 000000000..b2619652a --- /dev/null +++ b/docs/api/re/melange/Stdlib-Marshal.md @@ -0,0 +1,106 @@ + +# Module `Stdlib.Marshal` + +Marshaling of data structures. + +This module provides functions to encode arbitrary data structures as sequences of bytes, which can then be written on a file or sent over a pipe or network connection. The bytes can then be read back later, possibly in another process, and decoded back into a data structure. The format for the byte sequences is compatible across all machines for a given version of OCaml. + +Warning: marshaling is currently not type-safe. The type of marshaled data is not transmitted along the value of the data, making it impossible to check that the data read back possesses the type expected by the context. In particular, the result type of the `Marshal.from_*` functions is given as `'a`, but this is misleading: the returned OCaml value does not possess type `'a` for all `'a`; it has one, unique type which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax: + +- `(Marshal.from_channel chan : type)`. Anything can happen at run-time if the object in the file does not belong to the given type. +Values of extensible variant types, for example exceptions (of extensible type `exn`), returned by the unmarshaller should not be pattern-matched over through `match ... with` or `try ... with`, because unmarshalling does not preserve the information required for matching their constructors. Structural equalities with other extensible variant values does not work either. Most other uses such as Printexc.to\_string, will still work as expected. + +The representation of marshaled values is not human-readable, and uses bytes that are not printable characters. Therefore, input and output channels used in conjunction with `Marshal.to_channel` and `Marshal.from_channel` must be opened in binary mode, using e.g. `open_out_bin` or `open_in_bin`; channels opened in text mode will cause unmarshaling errors on platforms where text channels behave differently than binary channels, e.g. Windows. + +``` +type extern_flags = +``` +``` +| No_sharing +``` +Don't preserve sharing + +``` +| Closures +``` +Send function closures + +``` +| Compat_32 +``` +Ensure 32-bit compatibility + +``` + +``` +The flags to the `Marshal.to_*` functions below. + +``` +val to_channel : out_channel -> 'a -> extern_flags list -> unit +``` +`Marshal.to_channel chan v flags` writes the representation of `v` on channel `chan`. The `flags` argument is a possibly empty list of flags that governs the marshaling behavior with respect to sharing, functional values, and compatibility between 32- and 64-bit platforms. + +If `flags` does not contain `Marshal.No_sharing`, circularities and sharing inside the value `v` are detected and preserved in the sequence of bytes produced. In particular, this guarantees that marshaling always terminates. Sharing between values marshaled by successive calls to `Marshal.to_channel` is neither detected nor preserved, though. If `flags` contains `Marshal.No_sharing`, sharing is ignored. This results in faster marshaling if `v` contains no shared substructures, but may cause slower marshaling and larger byte representations if `v` actually contains sharing, or even non-termination if `v` contains cycles. + +If `flags` does not contain `Marshal.Closures`, marshaling fails when it encounters a functional value inside `v`: only 'pure' data structures, containing neither functions nor objects, can safely be transmitted between different programs. If `flags` contains `Marshal.Closures`, functional values will be marshaled as a the position in the code of the program together with the values corresponding to the free variables captured in the closure. In this case, the output of marshaling can only be read back in processes that run exactly the same program, with exactly the same compiled code. (This is checked at un-marshaling time, using an MD5 digest of the code transmitted along with the code position.) + +The exact definition of which free variables are captured in a closure is not specified and can vary between bytecode and native code (and according to optimization flags). In particular, a function value accessing a global reference may or may not include the reference in its closure. If it does, unmarshaling the corresponding closure will create a new reference, different from the global one. + +If `flags` contains `Marshal.Compat_32`, marshaling fails when it encounters an integer value outside the range `-2``30`, `2``30``-1` of integers that are representable on a 32-bit platform. This ensures that marshaled data generated on a 64-bit platform can be safely read back on a 32-bit platform. If `flags` does not contain `Marshal.Compat_32`, integer values outside the range `-2``30`, `2``30``-1` are marshaled, and can be read back on a 64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit platform. The `Mashal.Compat_32` flag only matters when marshaling is performed on a 64-bit platform; it has no effect if marshaling is performed on a 32-bit platform. + +raises [`Failure`](./Stdlib.md#exception-Failure) if chan is not in binary mode. +``` +val to_bytes : 'a -> extern_flags list -> bytes +``` +`Marshal.to_bytes v flags` returns a byte sequence containing the representation of `v`. The `flags` argument has the same meaning as for [`Marshal.to_channel`](./#val-to_channel). + +since 4.02 +``` +val to_string : 'a -> extern_flags list -> string +``` +Same as `to_bytes` but return the result as a string instead of a byte sequence. + +``` +val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int +``` +`Marshal.to_buffer buff ofs len v flags` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. It returns the number of bytes actually written to the sequence. If the byte representation of `v` does not fit in `len` characters, the exception `Failure` is raised. + +``` +val from_channel : in_channel -> 'a +``` +`Marshal.from_channel chan` reads from channel `chan` the byte representation of a structured value, as produced by one of the `Marshal.to_*` functions, and reconstructs and returns the corresponding value. + +raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if chan is already at the end of the file. +raises [`Failure`](./Stdlib.md#exception-Failure) if the end of the file is reached during unmarshalling itself or if chan is not in binary mode. +``` +val from_bytes : bytes -> int -> 'a +``` +`Marshal.from_bytes buff ofs` unmarshals a structured value like [`Marshal.from_channel`](./#val-from_channel) does, except that the byte representation is not read from a channel, but taken from the byte sequence `buff`, starting at position `ofs`. The byte sequence is not mutated. + +since 4.02 +``` +val from_string : string -> int -> 'a +``` +Same as `from_bytes` but take a string as argument instead of a byte sequence. + +``` +val header_size : int +``` +The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header. [`Marshal.header_size`](./#val-header_size) is the size, in bytes, of the header. [`Marshal.data_size`](./#val-data_size)` buff ofs` is the size, in bytes, of the data part, assuming a valid header is stored in `buff` starting at position `ofs`. Finally, [`Marshal.total_size`](./#val-total_size) `buff ofs` is the total size, in bytes, of the marshaled value. Both [`Marshal.data_size`](./#val-data_size) and [`Marshal.total_size`](./#val-total_size) raise `Failure` if `buff`, `ofs` does not contain a valid header. + +To read the byte representation of a marshaled value into a byte sequence, the program needs to read first [`Marshal.header_size`](./#val-header_size) bytes into the sequence, then determine the length of the remainder of the representation using [`Marshal.data_size`](./#val-data_size), make sure the sequence is large enough to hold the remaining data, then read it, and finally call [`Marshal.from_bytes`](./#val-from_bytes) to unmarshal the value. + +``` +val data_size : bytes -> int -> int +``` +See [`Marshal.header_size`](./#val-header_size). + +``` +val total_size : bytes -> int -> int +``` +See [`Marshal.header_size`](./#val-header_size). + + +## Marshal and domain safety + +Care must be taken when marshaling a mutable value that may be modified by a different domain. Mutating a value that is being marshaled (i.e., turned into a sequence of bytes) is a programming error and might result in surprising values (when unmarshaling) due to tearing, since marshaling involves byte-per-byte copy. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md new file mode 100644 index 000000000..80efdc53c --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md @@ -0,0 +1,21 @@ + +# Parameter `Make.H` + +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md new file mode 100644 index 000000000..3743681ec --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md @@ -0,0 +1,96 @@ + +# Module `Hashtbl.Make` + +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + + +## Parameters + +``` +module H : HashedType +``` + +## Signature + +``` +type key = H.t +``` +``` +type 'a t = 'a Hashtbl.Make(H).t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md new file mode 100644 index 000000000..d47afa082 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md @@ -0,0 +1,17 @@ + +# Parameter `MakeSeeded.H` + +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md new file mode 100644 index 000000000..3fe6e44f2 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md @@ -0,0 +1,95 @@ + +# Module `Hashtbl.MakeSeeded` + +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-MoreLabels-Hashtbl.md#val-randomize)). + +since 4.00 + +## Parameters + +``` +module H : SeededHashedType +``` + +## Signature + +``` +type key = H.t +``` +``` +type 'a t = 'a Hashtbl.MakeSeeded(H).t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md new file mode 100644 index 000000000..b8aa185ce --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md @@ -0,0 +1,23 @@ + +# Module type `Hashtbl.HashedType` + +The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md new file mode 100644 index 000000000..9843ac29b --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md @@ -0,0 +1,87 @@ + +# Module type `Hashtbl.S` + +The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + +``` +type key +``` +``` +type !'a t +``` +``` +val create : int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +since 4.00 +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +since 4.00 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md new file mode 100644 index 000000000..09e30086f --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md @@ -0,0 +1,20 @@ + +# Module type `Hashtbl.SeededHashedType` + +The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + +since 4.00 +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val seeded_hash : int -> t -> int +``` +A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md new file mode 100644 index 000000000..909c707c6 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md @@ -0,0 +1,86 @@ + +# Module type `Hashtbl.SeededS` + +The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + +since 4.00 +``` +type key +``` +``` +type !'a t +``` +``` +val create : ?random:bool -> int -> 'a t +``` +``` +val clear : 'a t -> unit +``` +``` +val reset : 'a t -> unit +``` +``` +val copy : 'a t -> 'a t +``` +``` +val add : 'a t -> key:key -> data:'a -> unit +``` +``` +val remove : 'a t -> key -> unit +``` +``` +val find : 'a t -> key -> 'a +``` +``` +val find_opt : 'a t -> key -> 'a option +``` +since 4.05 +``` +val find_all : 'a t -> key -> 'a list +``` +``` +val replace : 'a t -> key:key -> data:'a -> unit +``` +``` +val mem : 'a t -> key -> bool +``` +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +``` +val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit +``` +since 4.03 +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +``` +val length : 'a t -> int +``` +``` +val stats : 'a t -> statistics +``` +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +since 4.07 +``` +val to_seq_keys : _ t -> key Seq.t +``` +since 4.07 +``` +val to_seq_values : 'a t -> 'a Seq.t +``` +since 4.07 +``` +val add_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val replace_seq : 'a t -> (key * 'a) Seq.t -> unit +``` +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md new file mode 100644 index 000000000..9a4b5177e --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md @@ -0,0 +1,399 @@ + +# Module `MoreLabels.Hashtbl` + +Hash tables and hash functions. + +Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-MoreLabels-Map.md). + +The functors [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. + +**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. + +The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. + +See [the examples section](./#examples). + +**Unsynchronized accesses** + +Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +## Generic interface + +``` +type (!'a, !'b) t = ('a, 'b) Hashtbl.t +``` +The type of hash tables from type `'a` to type `'b`. + +``` +val create : ?random:bool -> int -> ('a, 'b) t +``` +`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. + +A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. + +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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. + +before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. +``` +val clear : ('a, 'b) t -> unit +``` +Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. + +``` +val reset : ('a, 'b) t -> unit +``` +Empty a hash table and shrink the size of the bucket table to its initial size. + +since 4.00 +``` +val copy : ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. + +``` +val add : ('a, 'b) t -> key:'a -> data:'b -> unit +``` +`Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`. + +**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) + +If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). + +``` +val find : ('a, 'b) t -> 'a -> 'b +``` +`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. + +``` +val find_opt : ('a, 'b) t -> 'a -> 'b option +``` +`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. + +since 4.05 +``` +val find_all : ('a, 'b) t -> 'a -> 'b list +``` +`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. + +``` +val mem : ('a, 'b) t -> 'a -> bool +``` +`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. + +``` +val remove : ('a, 'b) t -> 'a -> unit +``` +`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. + +``` +val replace : ('a, 'b) t -> key:'a -> data:'b -> unit +``` +`Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. + +``` +val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit +``` +`Hashtbl.iter ~f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. + +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + +The behavior is not specified if the hash table is modified by `f` during the iteration. + +``` +val filter_map_inplace : + f:(key:'a -> data:'b -> 'b option) -> + ('a, 'b) t -> + unit +``` +`Hashtbl.filter_map_inplace ~f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. + +Other comments for [`iter`](./#val-iter) apply as well. + +since 4.03 +``` +val fold : + f:(key:'a -> data:'b -> 'acc -> 'acc) -> + ('a, 'b) t -> + init:'acc -> + 'acc +``` +`Hashtbl.fold ~f tbl ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. + +The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. + +If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. + +The behavior is not specified if the hash table is modified by `f` during the iteration. + +``` +val length : ('a, 'b) t -> int +``` +`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. + +``` +val randomize : unit -> unit +``` +After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. + +It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. + +Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. + +since 4.00 +``` +val is_randomized : unit -> bool +``` +Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. + +since 4.03 +``` +val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t +``` +Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. + +[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. + +since 4.12 +``` +type statistics = Hashtbl.statistics = { +``` +`num_bindings : int;` +Number of bindings present in the table. Same value as returned by [`length`](./#val-length). + +`num_buckets : int;` +Number of buckets in the table. + +`max_bucket_length : int;` +Maximal number of bindings per bucket. + +`bucket_histogram : int array;` +Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. + +``` +} +``` +since 4.00 +``` +val stats : ('a, 'b) t -> statistics +``` +`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. + +since 4.00 + +## Hash tables and Sequences + +``` +val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t +``` +Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. + +The behavior is not specified if the hash table is modified during the iteration. + +since 4.07 +``` +val to_seq_keys : ('a, _) t -> 'a Seq.t +``` +Same as `Seq.map fst (to_seq m)` + +since 4.07 +``` +val to_seq_values : (_, 'b) t -> 'b Seq.t +``` +Same as `Seq.map snd (to_seq m)` + +since 4.07 +``` +val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`add`](./#val-add) + +since 4.07 +``` +val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit +``` +Add the given bindings to the table, using [`replace`](./#val-replace) + +since 4.07 +``` +val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t +``` +Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. + +since 4.07 + +## Functorial interface + +The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. + +For instance, one might want to specialize a table for integer keys: + +```ocaml + module IntHash = + struct + type t = int + let equal i j = i=j + let hash i = i land max_int + end + + module IntHashtbl = Hashtbl.Make(IntHash) + + let h = IntHashtbl.create 17 in + IntHashtbl.add h 12 "hello" +``` +This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. + +Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. + +``` +module type HashedType = sig ... end +``` +The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + +``` +module type S = sig ... end +``` +The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). + +``` +module Make + (H : HashedType) : + S with type key = H.t and type 'a t = 'a Hashtbl.Make(H).t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. + +``` +module type SeededHashedType = sig ... end +``` +The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + +``` +module type SeededS = sig ... end +``` +The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). + +``` +module MakeSeeded + (H : SeededHashedType) : + SeededS with type key = H.t and type 'a t = 'a Hashtbl.MakeSeeded(H).t +``` +Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). + + +## The polymorphic hash functions + +``` +val hash : 'a -> int +``` +`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. + +``` +val seeded_hash : int -> 'a -> int +``` +A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. + +since 4.00 +``` +val hash_param : int -> int -> 'a -> int +``` +`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. + +``` +val seeded_hash_param : int -> int -> int -> 'a -> int +``` +A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. + +since 4.00 + +## 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 + 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 +``` + +### Counting Elements + +Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. + +Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. + +```ocaml + # module Char_tbl = Hashtbl.Make(struct + type t = char + let equal = Char.equal + let hash = Hashtbl.hash + end) + + (* count distinct occurrences of chars in [seq] *) + # let count_chars (seq : char Seq.t) : _ list = + let counts = Char_tbl.create 16 in + Seq.iter + (fun c -> + let count_c = + Char_tbl.find_opt counts c + |> Option.value ~default:0 + in + Char_tbl.replace counts c (count_c + 1)) + seq; + (* turn into a list *) + Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] + |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) + val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = + + (* basic seq from a string *) + # let seq = String.to_seq "hello world, and all the camels in it!" + val seq : char Seq.t = + + # count_chars seq + - : (Char.t * int) list = + [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); + ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); + ('s', 1); ('t', 2); ('w', 1)] + + (* "abcabcabc..." *) + # let seq2 = + Seq.cycle (String.to_seq "abc") |> Seq.take 31 + val seq2 : char Seq.t = + + # String.of_seq seq2 + - : String.t = "abcabcabcabcabcabcabcabcabcabca" + + # count_chars seq2 + - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] + +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md new file mode 100644 index 000000000..d02ffc06f --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md @@ -0,0 +1,12 @@ + +# Parameter `Make.Ord` + +``` +type t +``` +The type of the map keys. + +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md new file mode 100644 index 000000000..b876ef70d --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md @@ -0,0 +1,315 @@ + +# Module `Map.Make` + +Functor building an implementation of the map structure given a totally ordered type. + + +## Parameters + +``` +module Ord : OrderedType +``` + +## Signature + + +## Maps + +``` +type key = Ord.t +``` +The type of the map keys. + +``` +type 'a t = 'a Map.Make(Ord).t +``` +The type of maps from type `key` to type `'a`. + +``` +val empty : 'a t +``` +The empty map. + +``` +val add : key:key -> data:'a -> 'a t -> 'a t +``` +`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t +``` +`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + +since 5.1 +``` +val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t +``` +`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. + +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +before 4.03 Physical equality was not ensured. +``` +val merge : + f:(key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + +since 3.12 +``` +val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. + +since 3.12 + +## Bindings + +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). + +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 4.05 + +## Searching + +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + +since 4.05 +``` +val find_first : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + +since 4.05 +``` +val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 +``` +val find_last : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +since 4.05 +``` +val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 + +## Traversing + +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + +## Transforming + +``` +val map : f:('a -> 'b) -> 'a t -> 'b t +``` +`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + +``` +val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists + +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + +since 4.11 +``` +val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +since 3.12 + +## Predicates and comparisons + +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. + +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + +``` +val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + +``` +val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + +``` +val for_all : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. + +since 3.12 +``` +val exists : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. + +since 3.12 + +## Converting + +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. + +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys + +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys + +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. + +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md new file mode 100644 index 000000000..6858e0bdf --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md @@ -0,0 +1,14 @@ + +# Module type `Map.OrderedType` + +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + +``` +type t +``` +The type of the map keys. + +``` +val compare : t -> t -> int +``` +A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md new file mode 100644 index 000000000..83ac73341 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md @@ -0,0 +1,306 @@ + +# Module type `Map.S` + +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + + +## Maps + +``` +type key +``` +The type of the map keys. + +``` +type !+'a t +``` +The type of maps from type `key` to type `'a`. + +``` +val empty : 'a t +``` +The empty map. + +``` +val add : key:key -> data:'a -> 'a t -> 'a t +``` +`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. + +before 4.03 Physical equality was not ensured. +``` +val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t +``` +`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. + +since 5.1 +``` +val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t +``` +`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +since 4.06 +``` +val singleton : key -> 'a -> 'a t +``` +`singleton x y` returns the one-element map that contains a binding `y` for `x`. + +since 3.12 +``` +val remove : key -> 'a t -> 'a t +``` +`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). + +before 4.03 Physical equality was not ensured. +``` +val merge : + f:(key -> 'a option -> 'b option -> 'c option) -> + 'a t -> + 'b t -> + 'c t +``` +`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. + +since 3.12 +``` +val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t +``` +`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where + +- `f' _key None None = None` +- `f' _key (Some v) None = Some v` +- `f' _key None (Some v) = Some v` +- `f' key (Some v1) (Some v2) = f key v1 v2` +since 4.03 +``` +val cardinal : 'a t -> int +``` +Return the number of bindings of a map. + +since 3.12 + +## Bindings + +``` +val bindings : 'a t -> (key * 'a) list +``` +Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-MoreLabels-Map-Make.md). + +since 3.12 +``` +val min_binding : 'a t -> key * 'a +``` +Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. + +since 3.12 +``` +val min_binding_opt : 'a t -> (key * 'a) option +``` +Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. + +since 4.05 +``` +val max_binding : 'a t -> key * 'a +``` +Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. + +since 3.12 +``` +val max_binding_opt : 'a t -> (key * 'a) option +``` +Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. + +since 4.05 +``` +val choose : 'a t -> key * 'a +``` +Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 3.12 +``` +val choose_opt : 'a t -> (key * 'a) option +``` +Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. + +since 4.05 + +## Searching + +``` +val find : key -> 'a t -> 'a +``` +`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. + +``` +val find_opt : key -> 'a t -> 'a option +``` +`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. + +since 4.05 +``` +val find_first : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. + +since 4.05 +``` +val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 +``` +val find_last : f:(key -> bool) -> 'a t -> key * 'a +``` +`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. + +since 4.05 +``` +val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option +``` +`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. + +since 4.05 + +## Traversing + +``` +val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit +``` +`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc +``` +`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. + + +## Transforming + +``` +val map : f:('a -> 'b) -> 'a t -> 'b t +``` +`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. + +``` +val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t +``` +Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. + +``` +val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t +``` +`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) + +since 3.12 +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t +``` +`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: + +- if `f k v` is `None` then `k` is not in the result, +- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. +For example, the following function on maps whose values are lists + +```ocaml +filter_map + (fun _k li -> match li with [] -> None | _::tl -> Some tl) + m +``` +drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. + +since 4.11 +``` +val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. + +since 3.12 +``` +val split : key -> 'a t -> 'a t * 'a option * 'a t +``` +`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. + +since 3.12 + +## Predicates and comparisons + +``` +val is_empty : 'a t -> bool +``` +Test whether a map is empty or not. + +``` +val mem : key -> 'a t -> bool +``` +`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. + +``` +val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool +``` +`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. + +``` +val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int +``` +Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. + +``` +val for_all : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. + +since 3.12 +``` +val exists : f:(key -> 'a -> bool) -> 'a t -> bool +``` +`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. + +since 3.12 + +## Converting + +``` +val to_list : 'a t -> (key * 'a) list +``` +`to_list m` is [`bindings`](./#val-bindings)` m`. + +since 5.1 +``` +val of_list : (key * 'a) list -> 'a t +``` +`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). + +since 5.1 +``` +val to_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in ascending order of keys + +since 4.07 +``` +val to_rev_seq : 'a t -> (key * 'a) Seq.t +``` +Iterate on the whole map, in descending order of keys + +since 4.12 +``` +val to_seq_from : key -> 'a t -> (key * 'a) Seq.t +``` +`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. + +since 4.07 +``` +val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t +``` +Add the given bindings to the map, in order. + +since 4.07 +``` +val of_seq : (key * 'a) Seq.t -> 'a t +``` +Build a map from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map.md b/docs/api/re/melange/Stdlib-MoreLabels-Map.md new file mode 100644 index 000000000..d7033ed13 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Map.md @@ -0,0 +1,41 @@ + +# Module `MoreLabels.Map` + +Association tables over ordered types. + +This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. + +For instance: + +```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") +``` +This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. + +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). + +``` +module Make + (Ord : OrderedType) : + S with type key = Ord.t and type 'a t = 'a Map.Make(Ord).t +``` +Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md new file mode 100644 index 000000000..3abdead73 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md @@ -0,0 +1,12 @@ + +# Parameter `Make.Ord` + +``` +type t +``` +The type of the set elements. + +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md new file mode 100644 index 000000000..df47ebd04 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md @@ -0,0 +1,297 @@ + +# Module `Set.Make` + +Functor building an implementation of the set structure given a totally ordered type. + + +## Parameters + +``` +module Ord : OrderedType +``` + +## Signature + + +## Sets + +``` +type elt = Ord.t +``` +The type of the set elements. + +``` +type t = Set.Make(Ord).t +``` +The type of sets. + +``` +val empty : t +``` +The empty set. + +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. + +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. + +``` +val inter : t -> t -> t +``` +Set intersection. + +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. + +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + +``` +val cardinal : t -> int +``` +Return the number of elements of a set. + + +## Elements + +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). + +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +since 4.05 + +## Searching + +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + +since 4.05 +``` +val find_first : f:(elt -> bool) -> t -> elt +``` +`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + +since 4.05 +``` +val find_first_opt : f:(elt -> bool) -> t -> elt option +``` +`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 +``` +val find_last : f:(elt -> bool) -> t -> elt +``` +`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +since 4.05 +``` +val find_last_opt : f:(elt -> bool) -> t -> elt option +``` +`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 + +## Traversing + +``` +val iter : f:(elt -> unit) -> t -> unit +``` +`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + +``` +val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc +``` +`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + +## Transforming + +``` +val map : f:(elt -> elt) -> t -> t +``` +`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + +since 4.04 +``` +val filter : f:(elt -> bool) -> t -> t +``` +`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(elt -> elt option) -> t -> t +``` +`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + +For example, + +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. + +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + +since 4.11 +``` +val partition : f:(elt -> bool) -> t -> t * t +``` +`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + +## Predicates and comparisons + +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. + +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. + +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. + +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + +``` +val for_all : f:(elt -> bool) -> t -> bool +``` +`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. + +``` +val exists : f:(elt -> bool) -> t -> bool +``` +`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. + + +## Converting + +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. + +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order + +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order + +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. + +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md new file mode 100644 index 000000000..4f07540de --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md @@ -0,0 +1,14 @@ + +# Module type `Set.OrderedType` + +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + +``` +type t +``` +The type of the set elements. + +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md new file mode 100644 index 000000000..853191d56 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md @@ -0,0 +1,288 @@ + +# Module type `Set.S` + +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + + +## Sets + +``` +type elt +``` +The type of the set elements. + +``` +type t +``` +The type of sets. + +``` +val empty : t +``` +The empty set. + +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. + +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. + +``` +val inter : t -> t -> t +``` +Set intersection. + +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. + +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + +``` +val cardinal : t -> int +``` +Return the number of elements of a set. + + +## Elements + +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-MoreLabels-Set-Make.md). + +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +since 4.05 + +## Searching + +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + +since 4.05 +``` +val find_first : f:(elt -> bool) -> t -> elt +``` +`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + +since 4.05 +``` +val find_first_opt : f:(elt -> bool) -> t -> elt option +``` +`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 +``` +val find_last : f:(elt -> bool) -> t -> elt +``` +`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +since 4.05 +``` +val find_last_opt : f:(elt -> bool) -> t -> elt option +``` +`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 + +## Traversing + +``` +val iter : f:(elt -> unit) -> t -> unit +``` +`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + +``` +val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc +``` +`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + +## Transforming + +``` +val map : f:(elt -> elt) -> t -> t +``` +`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + +since 4.04 +``` +val filter : f:(elt -> bool) -> t -> t +``` +`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val filter_map : f:(elt -> elt option) -> t -> t +``` +`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + +For example, + +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. + +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + +since 4.11 +``` +val partition : f:(elt -> bool) -> t -> t * t +``` +`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + +## Predicates and comparisons + +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. + +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. + +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. + +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + +``` +val for_all : f:(elt -> bool) -> t -> bool +``` +`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. + +``` +val exists : f:(elt -> bool) -> t -> bool +``` +`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. + + +## Converting + +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. + +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order + +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order + +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. + +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set.md b/docs/api/re/melange/Stdlib-MoreLabels-Set.md new file mode 100644 index 000000000..489cab218 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels-Set.md @@ -0,0 +1,41 @@ + +# Module `MoreLabels.Set` + +Sets over ordered types. + +This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. + +The [`Make`](./Stdlib-MoreLabels-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: + +```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 PairsSet = Set.Make(IntPairs) + + let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) +``` +This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. + +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). + +``` +module Make + (Ord : OrderedType) : + S with type elt = Ord.t and type t = Set.Make(Ord).t +``` +Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-MoreLabels.md b/docs/api/re/melange/Stdlib-MoreLabels.md new file mode 100644 index 000000000..3dda53b24 --- /dev/null +++ b/docs/api/re/melange/Stdlib-MoreLabels.md @@ -0,0 +1,30 @@ + +# Module `Stdlib.MoreLabels` + +Extra labeled libraries. + +This meta-module provides labelized versions of the [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md) and [`Set`](./Stdlib-MoreLabels-Set.md) modules. + +This module is intended to be used through `open MoreLabels` which replaces [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md), and [`Set`](./Stdlib-MoreLabels-Set.md) with their labeled counterparts. + +For example: + +```ocaml + open MoreLabels + + Hashtbl.iter ~f:(fun ~key ~data -> g key data) table +``` +``` +module Hashtbl : sig ... end +``` +Hash tables and hash functions. + +``` +module Map : sig ... end +``` +Association tables over ordered types. + +``` +module Set : sig ... end +``` +Sets over ordered types. diff --git a/docs/api/re/melange/Stdlib-Mutex.md b/docs/api/re/melange/Stdlib-Mutex.md new file mode 100644 index 000000000..7e8180f6c --- /dev/null +++ b/docs/api/re/melange/Stdlib-Mutex.md @@ -0,0 +1,49 @@ + +# Module `Stdlib.Mutex` + +Locks for mutual exclusion. + +Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if `m` is the mutex associated with the data structure `D`): + +```ocaml + Mutex.lock m; + (* Critical section that operates over D *); + Mutex.unlock m +``` +``` +type t +``` +The type of mutexes. + +``` +val create : unit -> t +``` +Return a new mutex. + +``` +val lock : t -> unit +``` +Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex. + +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is already locked by the thread calling Mutex.lock. +before 4.12 Sys\_error was not raised for recursive locking (platform-dependent behaviour) +``` +val try_lock : t -> bool +``` +Same as [`Mutex.lock`](./#val-lock), but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. If the mutex is unlocked, lock it and return `true`. + +``` +val unlock : t -> unit +``` +Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. The mutex must have been previously locked by the thread that calls [`Mutex.unlock`](./#val-unlock). + +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is unlocked or was locked by another thread. +before 4.12 Sys\_error was not raised when unlocking an unlocked mutex or when unlocking a mutex from a different thread. +``` +val protect : t -> (unit -> 'a) -> 'a +``` +`protect mutex f` runs `f()` in a critical section where `mutex` is locked (using [`lock`](./#val-lock)); it then takes care of releasing `mutex`, whether `f()` returned a value or raised an exception. + +The unlocking operation is guaranteed to always takes place, even in the event an asynchronous exception (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)) is raised in some signal handler. + +since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Obj-Ephemeron.md b/docs/api/re/melange/Stdlib-Obj-Ephemeron.md new file mode 100644 index 000000000..4020b901b --- /dev/null +++ b/docs/api/re/melange/Stdlib-Obj-Ephemeron.md @@ -0,0 +1,65 @@ + +# Module `Obj.Ephemeron` + +Ephemeron with arbitrary arity and untyped + +``` +type obj_t = t +``` +alias for [`Obj.t`](./Stdlib-Obj.md#type-t) + +``` +type t +``` +an ephemeron cf [`Ephemeron`](#) + +``` +val create : int -> t +``` +`create n` returns an ephemeron with `n` keys. All the keys and the data are initially empty. The argument `n` must be between zero and [`max_ephe_length`](./#val-max_ephe_length) (limits included). + +``` +val length : t -> int +``` +return the number of keys + +``` +val get_key : t -> int -> obj_t option +``` +``` +val get_key_copy : t -> int -> obj_t option +``` +``` +val set_key : t -> int -> obj_t -> unit +``` +``` +val unset_key : t -> int -> unit +``` +``` +val check_key : t -> int -> bool +``` +``` +val blit_key : t -> int -> t -> int -> int -> unit +``` +``` +val get_data : t -> obj_t option +``` +``` +val get_data_copy : t -> obj_t option +``` +``` +val set_data : t -> obj_t -> unit +``` +``` +val unset_data : t -> unit +``` +``` +val check_data : t -> bool +``` +``` +val blit_data : t -> t -> unit +``` +``` +val max_ephe_length : int +``` +Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain diff --git a/docs/api/re/melange/Stdlib-Obj-Extension_constructor.md b/docs/api/re/melange/Stdlib-Obj-Extension_constructor.md new file mode 100644 index 000000000..c08771eb4 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Obj-Extension_constructor.md @@ -0,0 +1,15 @@ + +# Module `Obj.Extension_constructor` + +``` +type t = extension_constructor +``` +``` +val of_val : 'a -> t +``` +``` +val name : t -> string +``` +``` +val id : t -> int +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Obj.md b/docs/api/re/melange/Stdlib-Obj.md new file mode 100644 index 000000000..2e619aff6 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Obj.md @@ -0,0 +1,139 @@ + +# Module `Stdlib.Obj` + +Operations on internal representations of values. + +Not for the casual user. + +``` +type t +``` +``` +type raw_data = nativeint +``` +``` +val repr : 'a -> t +``` +``` +val obj : t -> 'a +``` +``` +val magic : 'a -> 'b +``` +``` +val is_block : t -> bool +``` +``` +val is_int : t -> bool +``` +``` +val tag : t -> int +``` +``` +val size : t -> int +``` +``` +val reachable_words : t -> int +``` +Computes the total size (in words, including the headers) of all heap blocks accessible from the argument. Statically allocated blocks are included. + +since 4.04 +``` +val field : t -> int -> t +``` +``` +val set_field : t -> int -> t -> unit +``` +When using flambda: + +`set_field` MUST NOT be called on immutable blocks. (Blocks allocated in C stubs, or with `new_block` below, are always considered mutable.) + +The same goes for `set_double_field`. + +For experts only: `set_field` et al can be made safe by first wrapping the block in [`Sys.opaque_identity`](./Stdlib-Sys.md#val-opaque_identity), so any information about its contents will not be propagated. + +``` +val double_field : t -> int -> float +``` +``` +val set_double_field : t -> int -> float -> unit +``` +``` +val raw_field : t -> int -> raw_data +``` +``` +val set_raw_field : t -> int -> raw_data -> unit +``` +``` +val new_block : int -> int -> t +``` +``` +val dup : t -> t +``` +``` +val add_offset : t -> Int32.t -> t +``` +``` +val with_tag : int -> t -> t +``` +``` +val first_non_constant_constructor_tag : int +``` +``` +val last_non_constant_constructor_tag : int +``` +``` +val forcing_tag : int +``` +``` +val cont_tag : int +``` +``` +val lazy_tag : int +``` +``` +val closure_tag : int +``` +``` +val object_tag : int +``` +``` +val infix_tag : int +``` +``` +val forward_tag : int +``` +``` +val no_scan_tag : int +``` +``` +val abstract_tag : int +``` +``` +val string_tag : int +``` +``` +val double_tag : int +``` +``` +val double_array_tag : int +``` +``` +val custom_tag : int +``` +``` +val int_tag : int +``` +``` +val out_of_heap_tag : int +``` +``` +val unaligned_tag : int +``` +``` +module Extension_constructor : sig ... end +``` +``` +module Ephemeron : sig ... end +``` +Ephemeron with arbitrary arity and untyped diff --git a/docs/api/re/melange/Stdlib-Oo.md b/docs/api/re/melange/Stdlib-Oo.md new file mode 100644 index 000000000..f212cee13 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Oo.md @@ -0,0 +1,15 @@ + +# Module `Stdlib.Oo` + +Operations on objects + +``` +val copy : < .. > as 'a -> 'a +``` +`Oo.copy o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`. + +alert unsynchronized\_access Unsynchronized accesses to mutable objects are a programming error. +``` +val id : < .. > -> int +``` +Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures. diff --git a/docs/api/re/melange/Stdlib-Option.md b/docs/api/re/melange/Stdlib-Option.md new file mode 100644 index 000000000..c84df4dca --- /dev/null +++ b/docs/api/re/melange/Stdlib-Option.md @@ -0,0 +1,111 @@ + +# Module `Stdlib.Option` + +Option values. + +Option values explicitly indicate the presence or absence of a value. + +since 4.08 + +## Options + +``` +type 'a t = 'a option = +``` +``` +| None +``` +``` +| Some of 'a +``` +``` + +``` +The type for option values. Either `None` or a value `Some v`. + +``` +val none : 'a option +``` +`none` is `None`. + +``` +val some : 'a -> 'a option +``` +`some v` is `Some v`. + +``` +val value : 'a option -> default:'a -> 'a +``` +`value o ~default` is `v` if `o` is `Some v` and `default` otherwise. + +``` +val get : 'a option -> 'a +``` +`get o` is `v` if `o` is `Some v` and raise otherwise. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if o is None. +``` +val bind : 'a option -> ('a -> 'b option) -> 'b option +``` +`bind o f` is `f v` if `o` is `Some v` and `None` if `o` is `None`. + +``` +val join : 'a option option -> 'a option +``` +`join oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise. + +``` +val map : ('a -> 'b) -> 'a option -> 'b option +``` +`map f o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`. + +``` +val fold : none:'a -> some:('b -> 'a) -> 'b option -> 'a +``` +`fold ~none ~some o` is `none` if `o` is `None` and `some v` if `o` is `Some v`. + +``` +val iter : ('a -> unit) -> 'a option -> unit +``` +`iter f o` is `f v` if `o` is `Some v` and `()` otherwise. + + +## Predicates and comparisons + +``` +val is_none : 'a option -> bool +``` +`is_none o` is `true` if and only if `o` is `None`. + +``` +val is_some : 'a option -> bool +``` +`is_some o` is `true` if and only if `o` is `Some o`. + +``` +val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool +``` +`equal eq o0 o1` is `true` if and only if `o0` and `o1` are both `None` or if they are `Some v0` and `Some v1` and `eq v0 v1` is `true`. + +``` +val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int +``` +`compare cmp o0 o1` is a total order on options using `cmp` to compare values wrapped by `Some _`. `None` is smaller than `Some _` values. + + +## Converting + +``` +val to_result : none:'e -> 'a option -> ('a, 'e) result +``` +`to_result ~none o` is `Ok v` if `o` is `Some v` and `Error none` otherwise. + +``` +val to_list : 'a option -> 'a list +``` +`to_list o` is `[]` if `o` is `None` and `[v]` if `o` is `Some v`. + +``` +val to_seq : 'a option -> 'a Seq.t +``` +`to_seq o` is `o` as a sequence. `None` is the empty sequence and `Some v` is the singleton sequence containing `v`. diff --git a/docs/api/re/melange/Stdlib-Out_channel.md b/docs/api/re/melange/Stdlib-Out_channel.md new file mode 100644 index 000000000..35eade38e --- /dev/null +++ b/docs/api/re/melange/Stdlib-Out_channel.md @@ -0,0 +1,239 @@ + +# Module `Stdlib.Out_channel` + +Output channels. + +This module provides functions for working with output channels. + +See [the example section](./#examples) below. + +since 4.14 + +## Channels + +``` +type t = out_channel +``` +The type of output channel. + +``` +type open_flag = open_flag = +``` +``` +| Open_rdonly +``` +open for reading. + +``` +| Open_wronly +``` +open for writing. + +``` +| Open_append +``` +open for appending: always write at end of file. + +``` +| Open_creat +``` +create the file if it does not exist. + +``` +| Open_trunc +``` +empty the file if it already exists. + +``` +| Open_excl +``` +fail if Open\_creat and the file already exists. + +``` +| Open_binary +``` +open in binary mode (no conversion). + +``` +| Open_text +``` +open in text mode (may perform conversions). + +``` +| Open_nonblock +``` +open in non-blocking mode. + +``` + +``` +Opening modes for [`open_gen`](./#val-open_gen). + +``` +val stdout : t +``` +The standard output for the process. + +``` +val stderr : t +``` +The standard error output for the process. + +``` +val open_bin : string -> t +``` +Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. + +``` +val open_text : string -> t +``` +Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). + +``` +val open_gen : open_flag list -> int -> string -> t +``` +`open_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. + +``` +val with_open_bin : string -> (t -> 'a) -> 'a +``` +`with_open_bin fn f` opens a channel `oc` on file `fn` and returns `f oc`. After `f` returns, either with a value or by raising an exception, `oc` is guaranteed to be closed. + +``` +val with_open_text : string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). + +``` +val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a +``` +Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). + +``` +val close : t -> unit +``` +Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except [`close`](./#val-close) and [`flush`](./#val-flush), which do nothing when applied to an already closed channel. Note that [`close`](./#val-close) may raise `Sys_error` if the operating system signals an error when flushing or closing. + +``` +val close_noerr : t -> unit +``` +Same as [`close`](./#val-close), but ignore all errors. + + +## Output + +``` +val output_char : t -> char -> unit +``` +Write the character on the given output channel. + +``` +val output_byte : t -> int -> unit +``` +Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. + +``` +val output_string : t -> string -> unit +``` +Write the string on the given output channel. + +``` +val output_bytes : t -> bytes -> unit +``` +Write the byte sequence on the given output channel. + + +## Advanced output + +``` +val output : t -> bytes -> int -> int -> unit +``` +`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val output_substring : t -> string -> int -> int -> unit +``` +Same as [`output`](./#val-output) but take a string as argument instead of a byte sequence. + + +## Flushing + +``` +val flush : t -> unit +``` +Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. + +``` +val flush_all : unit -> unit +``` +Flush all open output channels; ignore errors. + + +## Seeking + +``` +val seek : t -> int64 -> unit +``` +`seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. + +``` +val pos : t -> int64 +``` +Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). + +For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + + +## Attributes + +``` +val length : t -> int64 +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. + +``` +val set_binary_mode : t -> bool -> unit +``` +`set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output. + +`set_binary_mode oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. + +This function has no effect under operating systems that do not distinguish between text mode and binary mode. + +``` +val is_binary_mode : t -> bool +``` +`is_binary_mode oc` returns whether the channel `oc` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). + +since 5.2 +``` +val set_buffered : t -> bool -> unit +``` +`set_buffered oc true` sets the channel `oc` to *buffered* mode. In this mode, data output on `oc` will be buffered until either the internal buffer is full or the function [`flush`](./#val-flush) or [`flush_all`](./#val-flush_all) is called, at which point it will be sent to the output device. + +`set_buffered oc false` sets the channel `oc` to *unbuffered* mode. In this mode, data output on `oc` will be sent to the output device immediately. + +All channels are open in *buffered* mode by default. + +``` +val is_buffered : t -> bool +``` +`is_buffered oc` returns whether the channel `oc` is buffered (see [`set_buffered`](./#val-set_buffered)). + +``` +val isatty : t -> bool +``` +`isatty oc` is `true` if `oc` refers to a terminal or console window, `false` otherwise. + +since 5.1 + +## Examples + +Writing the contents of a file: + +```ocaml + let write_file file s = + Out_channel.with_open_bin file + (fun oc -> Out_channel.output_string oc s)) +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Parsing.md b/docs/api/re/melange/Stdlib-Parsing.md new file mode 100644 index 000000000..b95445513 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Parsing.md @@ -0,0 +1,61 @@ + +# Module `Stdlib.Parsing` + +The run-time library for parsers generated by `ocamlyacc`. + +``` +val symbol_start : unit -> int +``` +`symbol_start` and [`Parsing.symbol_end`](./#val-symbol_end) are to be called in the action part of a grammar rule only. They return the offset of the string that matches the left-hand side of the rule: `symbol_start()` returns the offset of the first character; `symbol_end()` returns the offset after the last character. The first character in a file is at offset 0. + +``` +val symbol_end : unit -> int +``` +See [`Parsing.symbol_start`](./#val-symbol_start). + +``` +val rhs_start : int -> int +``` +Same as [`Parsing.symbol_start`](./#val-symbol_start) and [`Parsing.symbol_end`](./#val-symbol_end), but return the offset of the string matching the `n`th item on the right-hand side of the rule, where `n` is the integer parameter to `rhs_start` and `rhs_end`. `n` is 1 for the leftmost item. + +``` +val rhs_end : int -> int +``` +See [`Parsing.rhs_start`](./#val-rhs_start). + +``` +val symbol_start_pos : unit -> Lexing.position +``` +Same as `symbol_start`, but return a `position` instead of an offset. + +``` +val symbol_end_pos : unit -> Lexing.position +``` +Same as `symbol_end`, but return a `position` instead of an offset. + +``` +val rhs_start_pos : int -> Lexing.position +``` +Same as `rhs_start`, but return a `position` instead of an offset. + +``` +val rhs_end_pos : int -> Lexing.position +``` +Same as `rhs_end`, but return a `position` instead of an offset. + +``` +val clear_parser : unit -> unit +``` +Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs. + +``` +exception Parse_error +``` +Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery. + +``` +val set_trace : bool -> bool +``` +Control debugging support for `ocamlyacc`\-generated parsers. After `Parsing.set_trace true`, the pushdown automaton that executes the parsers prints a trace of its actions (reading a token, shifting a state, reducing by a rule) on standard output. `Parsing.set_trace false` turns this debugging trace off. The boolean returned is the previous state of the trace flag. + +since 3.11 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Printexc-Slot.md b/docs/api/re/melange/Stdlib-Printexc-Slot.md new file mode 100644 index 000000000..452eda49a --- /dev/null +++ b/docs/api/re/melange/Stdlib-Printexc-Slot.md @@ -0,0 +1,45 @@ + +# Module `Printexc.Slot` + +since 4.02 +``` +type t = backtrace_slot +``` +``` +val is_raise : t -> bool +``` +`is_raise slot` is `true` when `slot` refers to a raising point in the code, and `false` when it comes from a simple function call. + +since 4.02 +``` +val is_inline : t -> bool +``` +`is_inline slot` is `true` when `slot` refers to a call that got inlined by the compiler, and `false` when it comes from any other context. + +since 4.04 +``` +val location : t -> location option +``` +`location slot` returns the location information of the slot, if available, and `None` otherwise. + +Some possible reasons for failing to return a location are as follow: + +- the slot corresponds to a compiler-inserted raise +- the slot corresponds to a part of the program that has not been compiled with debug information (`-g`) +since 4.02 +``` +val name : t -> string option +``` +`name slot` returns the name of the function or definition enclosing the location referred to by the slot. + +`name slot` returns None if the name is unavailable, which may happen for the same reasons as `location` returning None. + +since 4.11 +``` +val format : int -> t -> string option +``` +`format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`\-th element of the backtrace: the `0`\-th element is pretty-printed differently than the others. + +Whole-backtrace printing functions also skip some uninformative slots; in that case, `format pos slot` returns `None`. + +since 4.02 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Printexc.md b/docs/api/re/melange/Stdlib-Printexc.md new file mode 100644 index 000000000..47bfc94fe --- /dev/null +++ b/docs/api/re/melange/Stdlib-Printexc.md @@ -0,0 +1,280 @@ + +# Module `Stdlib.Printexc` + +Facilities for printing exceptions and inspecting current call stack. + +``` +type t = exn = .. +``` +The type of exception values. + +``` +val to_string : exn -> string +``` +`Printexc.to_string e` returns a string representation of the exception `e`. + +``` +val to_string_default : exn -> string +``` +`Printexc.to_string_default e` returns a string representation of the exception `e`, ignoring all registered exception printers. + +since 4.09 +``` +val print : ('a -> 'b) -> 'a -> 'b +``` +`Printexc.print fn x` applies `fn` to `x` and returns the result. If the evaluation of `fn x` raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application. + +``` +val catch : ('a -> 'b) -> 'a -> 'b +``` +`Printexc.catch fn x` is similar to [`Printexc.print`](./#val-print), but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as `Printexc.catch` does. Moreover, calling `Printexc.catch` makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use `Printexc.catch` in new code. + +deprecated This function is no longer needed. +``` +val print_backtrace : out_channel -> unit +``` +`Printexc.print_backtrace oc` prints an exception backtrace on the output channel `oc`. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls. + +If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one. + +since 3.11 +``` +val get_backtrace : unit -> string +``` +`Printexc.get_backtrace ()` returns a string containing the same exception backtrace that `Printexc.print_backtrace` would print. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). + +since 3.11 +``` +val record_backtrace : bool -> unit +``` +`Printexc.record_backtrace b` turns recording of exception backtraces on (if `b = true`) or off (if `b = false`). Initially, backtraces are not recorded, unless the `b` flag is given to the program through the `OCAMLRUNPARAM` variable. + +since 3.11 +``` +val backtrace_status : unit -> bool +``` +`Printexc.backtrace_status()` returns `true` if exception backtraces are currently recorded, `false` if not. + +since 3.11 +``` +val register_printer : (exn -> string option) -> unit +``` +`Printexc.register_printer fn` registers `fn` as an exception printer. The printer should return `None` or raise an exception if it does not know how to convert the passed exception, and `Some s` with `s` the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored. + +When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a `Some s` value (if no such printer exists, the runtime will use a generic printer). + +When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to `fn` should not use the backtrace if it has itself raised an exception before. + +since 3.11.2 +``` +val use_printers : exn -> string option +``` +`Printexc.use_printers e` returns `None` if there are no registered printers and `Some s` with `s` the resulting string otherwise. + +since 4.09 + +## Raw backtraces + +``` +type raw_backtrace +``` +The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below. + +Converting backtraces to `backtrace_slot`s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use `raw_backtrace` to avoid or delay conversion. + +Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the `backtrace_slots` function of the next section. + +since 4.01 +``` +type raw_backtrace_entry = private int +``` +A `raw_backtrace_entry` is an element of a `raw_backtrace`. + +Each `raw_backtrace_entry` is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary. + +A `raw_backtrace_entry` can be converted to a usable form using `backtrace_slots_of_raw_entry` below. Note that, due to inlining, a single `raw_backtrace_entry` may convert to several `backtrace_slot`s. Since the values of a `raw_backtrace_entry` are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them. + +Again due to inlining, there may be multiple distinct raw\_backtrace\_entry values that convert to equal `backtrace_slot`s. However, if two `raw_backtrace_entry`s are equal as integers, then they represent the same `backtrace_slot`s. + +since 4.12 +``` +val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array +``` +since 4.12 +``` +val get_raw_backtrace : unit -> raw_backtrace +``` +`Printexc.get_raw_backtrace ()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). + +since 4.01 +``` +val print_raw_backtrace : out_channel -> raw_backtrace -> unit +``` +Print a raw backtrace in the same format `Printexc.print_backtrace` uses. + +since 4.01 +``` +val raw_backtrace_to_string : raw_backtrace -> string +``` +Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses. + +since 4.01 +``` +val raise_with_backtrace : exn -> raw_backtrace -> 'a +``` +Reraise the exception using the given raw\_backtrace for the origin of the exception + +since 4.05 + +## Current call stack + +``` +val get_callstack : int -> raw_backtrace +``` +`Printexc.get_callstack n` returns a description of the top of the call stack on the current program point (for the current thread), with at most `n` entries. (Note: this function is not related to exceptions at all, despite being part of the `Printexc` module.) + +since 4.01 + +## Uncaught exceptions + +``` +val default_uncaught_exception_handler : exn -> raw_backtrace -> unit +``` +`Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output. + +since 4.11 +``` +val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit +``` +`Printexc.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. The default handler is [`Printexc.default_uncaught_exception_handler`](./#val-default_uncaught_exception_handler). + +Note that when `fn` is called all the functions registered with [`Stdlib.at_exit`](./Stdlib.md#val-at_exit) have already been called. Because of this you must make sure any output channel `fn` writes on is flushed. + +Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself. + +If `fn` raises an exception, both the exceptions passed to `fn` and raised by `fn` will be printed with their respective backtrace. + +since 4.02 + +## Manipulation of backtrace information + +These functions are used to traverse the slots of a raw backtrace and extract information from them in a programmer-friendly format. + +``` +type backtrace_slot +``` +The abstract type `backtrace_slot` represents a single slot of a backtrace. + +since 4.02 +``` +val backtrace_slots : raw_backtrace -> backtrace_slot array option +``` +Returns the slots of a raw backtrace, or `None` if none of them contain useful information. + +In the return array, the slot at index `0` corresponds to the most recent function call, raise, or primitive `get_backtrace` call in the trace. + +Some possible reasons for returning `None` are as follow: + +- none of the slots in the trace come from modules compiled with debug information (`-g`) +- the program is a bytecode program that has not been linked with debug information enabled (`ocamlc -g`) +since 4.02 +``` +val backtrace_slots_of_raw_entry : + raw_backtrace_entry -> + backtrace_slot array option +``` +Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information. + +Slots are returned in the same order as `backtrace_slots`: the slot at index `0` is the most recent call, raise, or primitive, and subsequent slots represent callers. + +since 4.12 +``` +type location = { +``` +`filename : string;` +`line_number : int;` +`start_char : int;` +`end_char : int;` +`end_line : int;` +since 5.2 +`end_col : int;` +since 5.2 +``` +} +``` +The type of location information found in backtraces. `start_char` and `end_char` are positions relative to the beginning of `line_number`. `end_col` is relative to the beginning of `end_line`. + +since 4.02 +``` +module Slot : sig ... end +``` + +## Raw backtrace slots + +``` +type raw_backtrace_slot +``` +This type is used to iterate over the slots of a `raw_backtrace`. For most purposes, `backtrace_slots_of_raw_entry` is easier to use. + +Like `raw_backtrace_entry`, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior). + +Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example). + +since 4.02 +``` +val raw_backtrace_length : raw_backtrace -> int +``` +`raw_backtrace_length bckt` returns the number of slots in the backtrace `bckt`. + +since 4.02 +``` +val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot +``` +`get_raw_backtrace_slot bckt pos` returns the slot in position `pos` in the backtrace `bckt`. + +since 4.02 +``` +val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot +``` +Extracts the user-friendly `backtrace_slot` from a low-level `raw_backtrace_slot`. + +since 4.02 +``` +val get_raw_backtrace_next_slot : + raw_backtrace_slot -> + raw_backtrace_slot option +``` +`get_raw_backtrace_next_slot slot` returns the next slot inlined, if any. + +Sample code to iterate over all frames (inlined and non-inlined): + +```ocaml + (* Iterate over inlined frames *) + let rec iter_raw_backtrace_slot f slot = + f slot; + match get_raw_backtrace_next_slot slot with + | None -> () + | Some slot' -> iter_raw_backtrace_slot f slot' + + (* Iterate over stack frames *) + let iter_raw_backtrace f bt = + for i = 0 to raw_backtrace_length bt - 1 do + iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i) + done +``` +since 4.04 + +## Exception slots + +``` +val exn_slot_id : exn -> int +``` +`Printexc.exn_slot_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime). + +since 4.02 +``` +val exn_slot_name : exn -> string +``` +`Printexc.exn_slot_name exn` returns the internal name of the constructor used to create the exception value `exn`. + +since 4.02 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Printf.md b/docs/api/re/melange/Stdlib-Printf.md new file mode 100644 index 000000000..4c1d41539 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Printf.md @@ -0,0 +1,144 @@ + +# Module `Stdlib.Printf` + +Formatted output functions. + +``` +val fprintf : out_channel -> ('a, out_channel, unit) format -> 'a +``` +`fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`. + +The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments. + +Conversion specifications have the following form: + +`% [flags] [width] [.precision] type` + +In short, a conversion specification consists in the `%` character, followed by optional modifiers and a type which is made of one or two characters. + +The types and their meanings are: + +- `d`, `i`: convert an integer argument to signed decimal. The flag `#` adds underscores to large values for readability. +- `u`, `n`, `l`, `L`, or `N`: convert an integer argument to unsigned decimal. Warning: `n`, `l`, `L`, and `N` are used for `scanf`, and should not be used for `printf`. The flag `#` adds underscores to large values for readability. +- `x`: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag `#` adds a `0x` prefix to non zero values. +- `X`: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag `#` adds a `0X` prefix to non zero values. +- `o`: convert an integer argument to unsigned octal. The flag `#` adds a `0` prefix to non zero values. +- `s`: insert a string argument. +- `S`: convert a string argument to OCaml syntax (double quotes, escapes). +- `c`: insert a character argument. +- `C`: convert a character argument to OCaml syntax (single quotes, escapes). +- `f`: convert a floating-point argument to decimal notation, in the style `dddd.ddd`. +- `F`: convert a floating-point argument to OCaml syntax (`dddd.` or `dddd.ddd` or `d.ddd e+-dd`). Converts to hexadecimal with the `#` flag (see `h`). +- `e` or `E`: convert a floating-point argument to decimal notation, in the style `d.ddd e+-dd` (mantissa and exponent). +- `g` or `G`: convert a floating-point argument to decimal notation, in style `f` or `e`, `E` (whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining. +- `h` or `H`: convert a floating-point argument to hexadecimal notation, in the style `0xh.hhhh p+-dd` (hexadecimal mantissa, exponent in decimal and denotes a power of 2). +- `B`: convert a boolean argument to the string `true` or `false` +- `b`: convert a boolean argument (deprecated; do not use in new programs). +- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: convert an `int32` argument to the format specified by the second letter (decimal, hexadecimal, etc). +- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: convert a `nativeint` argument to the format specified by the second letter. +- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: convert an `int64` argument to the format specified by the second letter. +- `a`: user-defined printer. Take two arguments and apply the first one to `outchan` (the current output channel) and to the second argument. The first argument must therefore have type `out_channel -> 'b -> unit` and the second `'b`. The output produced by the function is inserted in the output of `fprintf` at the current point. +- `t`: same as `%a`, but take only one argument (with type `out_channel -> unit`) and apply it to `outchan`. +- `\{ fmt %\}`: convert a format string argument to its type digest. The argument must have the same type as the internal format string `fmt`. +- `( fmt %)`: format string substitution. Take a format string argument and substitute it to the internal format string `fmt` to print following arguments. The argument must have the same type as the internal format string `fmt`. +- `!`: take no argument and flush the output. +- `%`: take no argument and output one `%` character. +- `\@`: take no argument and output one `\@` character. +- `,`: take no argument and output nothing: a no-op delimiter for conversion specifications. +The optional `flags` are: + +- `-`: left-justify the output (default is right justification). +- `0`: for numerical conversions, pad with zeroes instead of spaces. +- `+`: for signed numerical conversions, prefix number with a `+` sign if positive. +- space: for signed numerical conversions, prefix number with a space if positive. +- `#`: request an alternate formatting style for the integer types and the floating-point type `F`. +The optional `width` is an integer indicating the minimal width of the result. For instance, `%6d` prints an integer, prefixing it with spaces to fill at least 6 characters. + +The optional `precision` is a dot `.` followed by an integer indicating how many digits follow the decimal point in the `%f`, `%e`, `%E`, `%h`, and `%H` conversions or the maximum number of significant digits to appear for the `%F`, `%g` and `%G` conversions. For instance, `%.4f` prints a `float` with 4 fractional digits. + +The integer in a `width` or `precision` can also be specified as `*`, in which case an extra integer argument is taken to specify the corresponding `width` or `precision`. This integer argument precedes immediately the argument to print. For instance, `%.*f` prints a `float` with as many fractional digits as the value of the argument given before the float. + +``` +val printf : ('a, out_channel, unit) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but output on `stdout`. + +``` +val eprintf : ('a, out_channel, unit) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but output on `stderr`. + +``` +val sprintf : ('a, unit, string) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, return a string containing the result of formatting the arguments. + +``` +val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module [`Buffer`](./Stdlib-Buffer.md)). + +``` +val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a +``` +Same as [`Printf.fprintf`](./#val-fprintf), but does not print anything. Useful to ignore some material when conditionally printing. + +since 3.10 +``` +val ibprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a +``` +Same as [`Printf.bprintf`](./#val-bprintf), but does not print anything. Useful to ignore some material when conditionally printing. + +since 4.11 +Formatted output functions with continuations. + +``` +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 +``` +val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a +``` +Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + +since 4.01 +``` +val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a +``` +Same as `sprintf` above, but instead of returning the string, passes it to the first argument. + +since 3.09 +``` +val kbprintf : + (Buffer.t -> 'd) -> + Buffer.t -> + ('a, Buffer.t, unit, 'd) format4 -> + 'a +``` +Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing. + +since 3.10 +``` +val ikbprintf : + (Buffer.t -> 'd) -> + Buffer.t -> + ('a, Buffer.t, unit, 'd) format4 -> + 'a +``` +Same as `kbprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. + +since 4.11 +Deprecated + +``` +val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a +``` +A deprecated synonym for `ksprintf`. + +deprecated Use Printf.ksprintf instead. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Queue.md b/docs/api/re/melange/Stdlib-Queue.md new file mode 100644 index 000000000..820e40343 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Queue.md @@ -0,0 +1,225 @@ + +# Module `Stdlib.Queue` + +First-in first-out queues. + +This module implements queues (FIFOs), with in-place modification. See [the example section](./#examples) below. + +**Unsynchronized accesses** + +Unsynchronized accesses to a queue may lead to an invalid queue state. Thus, concurrent accesses to queues must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + +``` +type !'a t +``` +The type of queues containing elements of type `'a`. + +``` +exception Empty +``` +Raised when [`Queue.take`](./#val-take) or [`Queue.peek`](./#val-peek) is applied to an empty queue. + +``` +val create : unit -> 'a t +``` +Return a new queue, initially empty. + +``` +val add : 'a -> 'a t -> unit +``` +`add x q` adds the element `x` at the end of the queue `q`. + +``` +val push : 'a -> 'a t -> unit +``` +`push` is a synonym for `add`. + +``` +val take : 'a t -> 'a +``` +`take q` removes and returns the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. + +``` +val take_opt : 'a t -> 'a option +``` +`take_opt q` removes and returns the first element in queue `q`, or returns `None` if the queue is empty. + +since 4.08 +``` +val pop : 'a t -> 'a +``` +`pop` is a synonym for `take`. + +``` +val peek : 'a t -> 'a +``` +`peek q` returns the first element in queue `q`, without removing it from the queue, or raises [`Empty`](./#exception-Empty) if the queue is empty. + +``` +val peek_opt : 'a t -> 'a option +``` +`peek_opt q` returns the first element in queue `q`, without removing it from the queue, or returns `None` if the queue is empty. + +since 4.08 +``` +val top : 'a t -> 'a +``` +`top` is a synonym for `peek`. + +``` +val drop : 'a t -> unit +``` +`drop q` removes the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. + +since 5.3 +``` +val clear : 'a t -> unit +``` +Discard all elements from a queue. + +``` +val copy : 'a t -> 'a t +``` +Return a copy of the given queue. + +``` +val is_empty : 'a t -> bool +``` +Return `true` if the given queue is empty, `false` otherwise. + +``` +val length : 'a t -> int +``` +Return the number of elements in a queue. + +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f q` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. + +``` +val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold f accu q` is equivalent to `List.fold_left f accu l`, where `l` is the list of `q`'s elements. The queue remains unchanged. + +``` +val transfer : 'a t -> 'a t -> unit +``` +`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `iter (fun x -> add x q2) q1; clear q1`, but runs in constant time. + + +## Iterators + +``` +val to_seq : 'a t -> 'a Seq.t +``` +Iterate on the queue, in front-to-back order. The behavior is not specified if the queue is modified during the iteration. + +since 4.07 +``` +val add_seq : 'a t -> 'a Seq.t -> unit +``` +Add the elements from a sequence to the end of the queue. + +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a t +``` +Create a queue from a sequence. + +since 4.07 + +## Examples + + +### Basic Example + +A basic example: + +```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. +``` + +### Search Through a Graph + +For a more elaborate example, a classic algorithmic use of queues is to implement a BFS (breadth-first search) through a graph. + +```ocaml + type graph = { + edges: (int, int list) Hashtbl.t + } + + (* Search in graph [g] using BFS, starting from node [start]. + It returns the first node that satisfies [p], or [None] if + no node reachable from [start] satisfies [p]. + *) + let search_for ~(g:graph) ~(start:int) (p:int -> bool) : int option = + let to_explore = Queue.create() in + let explored = Hashtbl.create 16 in + + Queue.push start to_explore; + let rec loop () = + if Queue.is_empty to_explore then None + else + (* node to explore *) + let node = Queue.pop to_explore in + explore_node node + + and explore_node node = + if not (Hashtbl.mem explored node) then ( + if p node then Some node (* found *) + else ( + Hashtbl.add explored node (); + let children = + Hashtbl.find_opt g.edges node + |> Option.value ~default:[] + in + List.iter (fun child -> Queue.push child to_explore) children; + loop() + ) + ) else loop() + in + loop() + + (* a sample graph *) + let my_graph: graph = + let edges = + List.to_seq [ + 1, [2;3]; + 2, [10; 11]; + 3, [4;5]; + 5, [100]; + 11, [0; 20]; + ] + |> Hashtbl.of_seq + in {edges} + + # search_for ~g:my_graph ~start:1 (fun x -> x = 30) + - : int option = None + + # search_for ~g:my_graph ~start:1 (fun x -> x >= 15) + - : int option = Some 20 + + # search_for ~g:my_graph ~start:1 (fun x -> x >= 50) + - : int option = Some 100 +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Random-State.md b/docs/api/re/melange/Stdlib-Random-State.md new file mode 100644 index 000000000..cf10b7a30 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Random-State.md @@ -0,0 +1,50 @@ + +# Module `Random.State` + +``` +type t +``` +The type of PRNG states. + +``` +val make : int array -> t +``` +Create a new state and initialize it with the given seed. + +``` +val make_self_init : unit -> t +``` +Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in [`Random.self_init`](./Stdlib-Random.md#val-self_init). + +``` +val copy : t -> t +``` +Return a copy of the given state. + +``` +val bits : t -> int +``` +``` +val int : t -> int -> int +``` +``` +val full_int : t -> int -> int +``` +``` +val int32 : t -> Int32.t -> Int32.t +``` +``` +val int64 : t -> Int64.t -> Int64.t +``` +``` +val float : t -> float -> float +``` +``` +val bool : t -> bool +``` +``` +val bits32 : t -> Int32.t +``` +``` +val bits64 : t -> Int64.t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Random.md b/docs/api/re/melange/Stdlib-Random.md new file mode 100644 index 000000000..98f498047 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Random.md @@ -0,0 +1,103 @@ + +# Module `Stdlib.Random` + +Pseudo-random number generators (PRNG). + +With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain. + +In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the `Random.split` function and used with the functions from the [`Random.State`](./Stdlib-Random-State.md) module. + +before 5.0 Random value generation used a different algorithm. This affects all the functions in this module which return random values. + +## Basic functions + +``` +val init : int -> unit +``` +Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. + +``` +val full_init : int array -> unit +``` +Same as [`Random.init`](./#val-init) but takes more data as seed. + +``` +val self_init : unit -> unit +``` +Initialize the domain-local generator with a random seed chosen in a system-dependent way. If `/dev/urandom` is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state). + +``` +val bits : unit -> int +``` +Return 30 random bits in a nonnegative integer. + +``` +val int : int -> int +``` +`Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0 and less than 230. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0 or bound \>= 230. +``` +val full_int : int -> int +``` +`Random.full_int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` may be any positive integer. + +If `bound` is less than 231, then `Random.full_int bound` yields identical output across systems with varying `int` sizes. + +If `bound` is less than 230, then `Random.full_int bound` is equal to [`Random.int`](./#val-int)` bound`. + +If `bound` is at least 230 (on 64-bit systems, or non-standard environments such as JavaScript), then `Random.full_int` returns a value whereas [`Random.int`](./#val-int) raises [`Stdlib.Invalid_argument`](./Stdlib.md#exception-Invalid_argument). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. +since 4.13 +``` +val int32 : Int32.t -> Int32.t +``` +`Random.int32 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. +``` +val int64 : Int64.t -> Int64.t +``` +`Random.int64 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. +``` +val float : float -> float +``` +`Random.float bound` returns a random floating-point number between 0 and `bound` (inclusive). If `bound` is negative, the result is negative or zero. If `bound` is 0, the result is 0. + +``` +val bool : unit -> bool +``` +`Random.bool ()` returns `true` or `false` with probability 0.5 each. + +``` +val bits32 : unit -> Int32.t +``` +`Random.bits32 ()` returns 32 random bits as an integer between [`Int32.min_int`](./Stdlib-Int32.md#val-min_int) and [`Int32.max_int`](./Stdlib-Int32.md#val-max_int). + +since 4.14 +``` +val bits64 : unit -> Int64.t +``` +`Random.bits64 ()` returns 64 random bits as an integer between [`Int64.min_int`](./Stdlib-Int64.md#val-min_int) and [`Int64.max_int`](./Stdlib-Int64.md#val-max_int). + +since 4.14 + +## Advanced functions + +The functions from module [`State`](./Stdlib-Random-State.md) manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. + +``` +module State : sig ... end +``` +``` +val get_state : unit -> State.t +``` +`get_state()` returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). + +``` +val set_state : State.t -> unit +``` +`set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it. diff --git a/docs/api/re/melange/Stdlib-Result.md b/docs/api/re/melange/Stdlib-Result.md new file mode 100644 index 000000000..5e42a7a68 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Result.md @@ -0,0 +1,137 @@ + +# Module `Stdlib.Result` + +Result values. + +Result values handle computation results and errors in an explicit and declarative manner without resorting to exceptions. + +since 4.08 + +## Results + +``` +type ('a, 'e) t = ('a, 'e) result = +``` +``` +| Ok of 'a +``` +``` +| Error of 'e +``` +``` + +``` +The type for result values. Either a value `Ok v` or an error `Error e`. + +``` +val ok : 'a -> ('a, 'e) result +``` +`ok v` is `Ok v`. + +``` +val error : 'e -> ('a, 'e) result +``` +`error e` is `Error e`. + +``` +val value : ('a, 'e) result -> default:'a -> 'a +``` +`value r ~default` is `v` if `r` is `Ok v` and `default` otherwise. + +``` +val get_ok : ('a, 'e) result -> 'a +``` +`get_ok r` is `v` if `r` is `Ok v` and raise otherwise. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Error \_. +``` +val get_error : ('a, 'e) result -> 'e +``` +`get_error r` is `e` if `r` is `Error e` and raise otherwise. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Ok \_. +``` +val bind : ('a, 'e) result -> ('a -> ('b, 'e) result) -> ('b, 'e) result +``` +`bind r f` is `f v` if `r` is `Ok v` and `r` if `r` is `Error _`. + +``` +val join : (('a, 'e) result, 'e) result -> ('a, 'e) result +``` +`join rr` is `r` if `rr` is `Ok r` and `rr` if `rr` is `Error _`. + +``` +val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result +``` +`map f r` is `Ok (f v)` if `r` is `Ok v` and `r` if `r` is `Error _`. + +``` +val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result +``` +`map_error f r` is `Error (f e)` if `r` is `Error e` and `r` if `r` is `Ok _`. + +``` +val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c +``` +`fold ~ok ~error r` is `ok v` if `r` is `Ok v` and `error e` if `r` is `Error e`. + +``` +val iter : ('a -> unit) -> ('a, 'e) result -> unit +``` +`iter f r` is `f v` if `r` is `Ok v` and `()` otherwise. + +``` +val iter_error : ('e -> unit) -> ('a, 'e) result -> unit +``` +`iter_error f r` is `f e` if `r` is `Error e` and `()` otherwise. + + +## Predicates and comparisons + +``` +val is_ok : ('a, 'e) result -> bool +``` +`is_ok r` is `true` if and only if `r` is `Ok _`. + +``` +val is_error : ('a, 'e) result -> bool +``` +`is_error r` is `true` if and only if `r` is `Error _`. + +``` +val equal : + ok:('a -> 'a -> bool) -> + error:('e -> 'e -> bool) -> + ('a, 'e) result -> + ('a, 'e) result -> + bool +``` +`equal ~ok ~error r0 r1` tests equality of `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. + +``` +val compare : + ok:('a -> 'a -> int) -> + error:('e -> 'e -> int) -> + ('a, 'e) result -> + ('a, 'e) result -> + int +``` +`compare ~ok ~error r0 r1` totally orders `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _ ` and `Error _`. `Ok _` values are smaller than `Error _` values. + + +## Converting + +``` +val to_option : ('a, 'e) result -> 'a option +``` +`to_option r` is `r` as an option, mapping `Ok v` to `Some v` and `Error _` to `None`. + +``` +val to_list : ('a, 'e) result -> 'a list +``` +`to_list r` is `[v]` if `r` is `Ok v` and `[]` otherwise. + +``` +val to_seq : ('a, 'e) result -> 'a Seq.t +``` +`to_seq r` is `r` as a sequence. `Ok v` is the singleton sequence containing `v` and `Error _` is the empty sequence. diff --git a/docs/api/re/melange/Stdlib-Scanf-Scanning.md b/docs/api/re/melange/Stdlib-Scanf-Scanning.md new file mode 100644 index 000000000..1bfe20e18 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Scanf-Scanning.md @@ -0,0 +1,95 @@ + +# Module `Scanf.Scanning` + +``` +type in_channel +``` +The notion of input channel for the [`Scanf`](./Stdlib-Scanf.md) module: those channels provide all the machinery necessary to read from any source of characters, including a [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) value. A Scanf.Scanning.in\_channel value is also called a *formatted input channel* or equivalently a *scanning buffer*. The type [`Scanning.scanbuf`](./#type-scanbuf) below is an alias for `Scanning.in_channel`. Note that a `Scanning.in_channel` is not concurrency-safe: concurrent use may produce arbitrary values or exceptions. + +since 3.12 +``` +type scanbuf = in_channel +``` +The type of scanning buffers. A scanning buffer is the source from which a formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far. + +Note: a scanning action may often require to examine one character in advance; when this 'lookahead' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character yet to be read. + +``` +val stdin : in_channel +``` +The standard input notion for the [`Scanf`](./Stdlib-Scanf.md) module. `Scanning.stdin` is the [`Scanning.in_channel`](./#type-in_channel) formatted input channel attached to [`Stdlib.stdin`](./Stdlib.md#val-stdin). + +Note: in the interactive system, when input is read from [`Stdlib.stdin`](./Stdlib.md#val-stdin), the newline character that triggers evaluation is part of the input; thus, the scanning specifications must properly skip this additional newline character (for instance, simply add a `'\n'` as the last character of the format string). + +since 3.12 +``` +type file_name = string +``` +A convenient alias to designate a file name. + +since 4.00 +``` +val open_in : file_name -> in_channel +``` +`Scanning.open_in fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in text mode from file `fname`. + +Note: `open_in` returns a formatted input channel that efficiently reads characters in large chunks; in contrast, `from_channel` below returns formatted input channels that must read one character at a time, leading to a much slower scanning rate. + +since 3.12 +``` +val open_in_bin : file_name -> in_channel +``` +`Scanning.open_in_bin fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in binary mode from file `fname`. + +since 3.12 +``` +val close_in : in_channel -> unit +``` +Closes the [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) associated with the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + +since 3.12 +``` +val from_file : file_name -> in_channel +``` +An alias for [`Scanning.open_in`](./#val-open_in) above. + +``` +val from_file_bin : string -> in_channel +``` +An alias for [`Scanning.open_in_bin`](./#val-open_in_bin) above. + +``` +val from_string : string -> in_channel +``` +`Scanning.from_string s` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached. + +``` +val from_function : (unit -> char) -> in_channel +``` +`Scanning.from_function f` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel with the given function as its reading method. + +When scanning needs one more character, the given function is called. + +When the function has no more character to provide, it *must* signal an end-of-input condition by raising the exception `End_of_file`. + +``` +val from_channel : in_channel -> in_channel +``` +`Scanning.from_channel ic` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the regular [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) input channel `ic` argument. Reading starts at current reading position of `ic`. + +``` +val end_of_input : in_channel -> bool +``` +`Scanning.end_of_input ic` tests the end-of-input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + +``` +val beginning_of_input : in_channel -> bool +``` +`Scanning.beginning_of_input ic` tests the beginning of input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + +``` +val name_of_input : in_channel -> string +``` +`Scanning.name_of_input ic` returns the name of the character source for the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. + +since 3.09 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Scanf.md b/docs/api/re/melange/Stdlib-Scanf.md new file mode 100644 index 000000000..717b966f9 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Scanf.md @@ -0,0 +1,265 @@ + +# Module `Stdlib.Scanf` + +Formatted input functions. + + +## Introduction + + +### Functional input with format strings + +The module [`Scanf`](#) provides formatted input functions or *scanners*. + +The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a *formatted input channel* (or *scanning buffer*) and has type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). The more general formatted input function reads from any scanning buffer and is named `bscanf`. + +Generally speaking, the formatted input functions have 3 arguments: + +- the first argument is a source of characters for the input, +- the second argument is a format string that specifies the values to read, +- the third argument is a *receiver function* that is applied to the values read. +Hence, a typical call to the formatted input function [`Scanf.bscanf`](./#val-bscanf) is `bscanf ic fmt f`, where: + +- `ic` is a source of characters (typically a *formatted input channel* with type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)), +- `fmt` is a format string (the same format strings as those used to print material with module [`Printf`](./Stdlib-Printf.md) or [`Format`](./Stdlib-Format.md)), +- `f` is a function that has as many arguments as the number of values to read in the input according to `fmt`. + +### A simple example + +As suggested above, the expression `bscanf ic "%d" f` reads a decimal integer `n` from the source of characters `ic` and returns `f n`. + +For instance, + +- if we use `stdin` as the source of characters ([`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) is the predefined formatted input channel that reads from standard input), +- if we define the receiver `f` as `let f x = x + 1`, +then `bscanf Scanning.stdin "%d" f` reads an integer `n` from the standard input and returns `f n` (that is `n + 1`). Thus, if we evaluate `bscanf stdin "%d" f`, and then enter `41` at the keyboard, the result we get is `42`. + + +### Formatted input as a functional feature + +The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assignment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time. + +**Unsynchronized accesses** + +Unsynchronized accesses to a [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) may lead to an invalid [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) state. Thus, concurrent accesses to [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)s must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + + +## Formatted input channel + +``` +module Scanning : sig ... end +``` + +## Type of formatted input functions + +``` +type ('a, 'b, 'c, 'd) scanner = + ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> + 'c +``` +The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic`. + +For instance, the [`Scanf.scanf`](./#val-scanf) function below has type `('a, 'b, 'c, 'd) scanner`, since it is a formatted input function that reads from [`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin): `scanf fmt f` applies `f` to the arguments specified by `fmt`, reading those arguments from [`Stdlib.stdin`](./Stdlib.md#val-stdin) as expected. + +If the format `fmt` has some `%r` indications, the corresponding formatted input functions must be provided *before* receiver function `f`. For instance, if `read_elem` is an input function for values of type `t`, then `bscanf ic "%r;" read_elem f` reads a value `v` of type `t` followed by a `';'` character, and returns `f v`. + +since 3.10 +``` +type ('a, 'b, 'c, 'd) scanner_opt = + ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) format6 -> + 'c +``` +``` +exception Scan_failure of string +``` +When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan_failure`. + + +## The general formatted input function + +``` +val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner +``` +`bscanf ic fmt r1 ... rN f` reads characters from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic` and converts them to values according to format string `fmt`. As a final step, receiver function `f` is applied to the values read and gives the result of the `bscanf` call. + +For instance, if `f` is the function `fun s i -> i + 1`, then `Scanf.sscanf "x = 1" "%s = %i" f` returns `2`. + +Arguments `r1` to `rN` are user-defined input functions that read the argument corresponding to the `%r` conversions specified in the format string. + +``` +val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but returns `None` in case of scanning failure. + +since 5.0 + +## Format string description + +The format string is a character string which contains three types of objects: + +- plain characters, which are simply matched with the characters of the input (with a special case for space and line feed, see [The space character in format strings](./#space)), +- conversion specifications, each of which causes reading and conversion of one argument for the function `f` (see [Conversion specifications in format strings](./#conversion)), +- scanning indications to specify boundaries of tokens (see scanning [Scanning indications in format strings](./#indication)). + +### The space character in format strings + +As mentioned above, a plain character in the format string is just matched with the next character of the input; however, two characters are special exceptions to this rule: the space character (`' '` or ASCII code 32) and the line feed character (`'\n'` or ASCII code 10). A space does not match a single space character, but any amount of 'whitespace' in the input. More precisely, a space inside the format string matches *any number* of tab, space, line feed and carriage return characters. Similarly, a line feed character in the format string matches either a single line feed or a carriage return followed by a line feed. + +Matching *any* amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call `bscanf ib "Price = %d $" (fun p -> p)` succeeds and returns `1` when reading an input with various whitespace in it, such as `Price = 1 $`, `Price = 1 $`, or even `Price=1$`. + + +### Conversion specifications in format strings + +Conversion specifications consist in the `%` character, followed by an optional flag, an optional field width, and followed by one or two conversion characters. + +The conversion characters and their meanings are: + +- `d`: reads an optionally signed decimal integer (`0-9`\+). +- `i`: reads an optionally signed integer (usual input conventions for decimal (`0-9`\+), hexadecimal (`0x[0-9a-f]+` and `0X[0-9A-F]+`), octal (`0o[0-7]+`), and binary (`0b[0-1]+`) notations are understood). +- `u`: reads an unsigned decimal integer. +- `x` or `X`: reads an unsigned hexadecimal integer (`[0-9a-fA-F]+`). +- `o`: reads an unsigned octal integer (`[0-7]+`). +- `s`: reads a string argument that spreads as much as possible, until the following bounding condition holds: + + - a whitespace has been found (see [The space character in format strings](./#space)), + - a scanning indication (see scanning [Scanning indications in format strings](./#indication)) has been encountered, + - the end-of-input has been reached. + Hence, this conversion always succeeds: it returns an empty string if the bounding condition holds when the scan begins. + +- `S`: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml). +- `c`: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification `%0c`. Raise `Invalid_argument`, if the field width specification is greater than 1\. +- `C`: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml). +- `f`, `e`, `E`, `g`, `G`: reads an optionally signed floating-point number in decimal notation, in the style `dddd.ddd e/E+-dd`. +- `h`, `H`: reads an optionally signed floating-point number in hexadecimal notation. +- `F`: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned). +- `B`: reads a boolean argument (`true` or `false`). +- `b`: reads a boolean argument (for backward compatibility; do not use in new programs). +- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: reads an `int32` argument to the format specified by the second letter for regular integers. +- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: reads a `nativeint` argument to the format specified by the second letter for regular integers. +- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: reads an `int64` argument to the format specified by the second letter for regular integers. +- `[ range ]`: reads characters that matches one of the characters mentioned in the range of characters `range` (or not mentioned in it, if the range starts with `^`). Reads a `string` that can be empty, if the next input character does not match the range. The set of characters from `c1` to `c2` (inclusively) is denoted by `c1-c2`. Hence, `%[0-9]` returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, `%[0-9a-f]` returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the `^` in case of range negation); hence `[]]` matches a `]` character and `[^]]` matches any character that is not `]`. Use `%%` and `%@` to include a `%` or a `@` in a range. +- `r`: user-defined reader. Takes the next `ri` formatted input function and applies it to the scanning buffer `ib` to read the next argument. The input function `ri` must therefore have type `Scanning.in_channel -> 'a` and the argument read has type `'a`. +- `{ fmt %}`: reads a format string argument. The format string read must have the same type as the format string specification `fmt`. For instance, `"%{ %i %}"` reads any format string that can read a value of type `int`; hence, if `s` is the string `"fmt:\"number is %u\""`, then `Scanf.sscanf s "fmt: %{%i%}"` succeeds and returns the format string `"number is %u"`. +- `( fmt %)`: scanning sub-format substitution. Reads a format string `rf` in the input, then goes on scanning with `rf` instead of scanning with `fmt`. The format string `rf` must have the same type as the format string specification `fmt` that it replaces. For instance, `"%( %i %)"` reads any format string that can read a value of type `int`. The conversion returns the format string read `rf`, and then a value read using `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%(%i%)" (fun fmt i -> fmt, i)` evaluates to `("%4d", 1234)`. This behaviour is not mere format substitution, since the conversion returns the format string read as additional argument. If you need pure format substitution, use special flag `_` to discard the extraneous argument: conversion `%_( fmt %)` reads a format string `rf` and then behaves the same as format string `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%_(%i%)"` is simply equivalent to `Scanf.sscanf "1234.00" "%4d"`. +- `l`: returns the number of lines read so far. +- `n`: returns the number of characters read so far. +- `N` or `L`: returns the number of tokens read so far. +- `!`: matches the end of input condition. +- `%`: matches one `%` character in the input. +- `@`: matches one `@` character in the input. +- `,`: does nothing. +Following the `%` character that introduces a conversion, there may be the special flag `_`: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if `f` is the function `fun i -> i + 1`, and `s` is the string `"x = 1"`, then `Scanf.sscanf s "%_s = %i" f` returns `2`. + +The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, `%6d` reads an integer, having at most 6 decimal digits; `%4f` reads a float with at most 4 characters; and `%8[\000-\255]` returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input). + +Notes: + +- as mentioned above, a `%s` conversion always succeeds, even if there is nothing to read in the input: in this case, it simply returns `""`. +- in addition to the relevant digits, `'_'` characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions. +- the `scanf` facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module `Str`), stream parsers, `ocamllex`\-generated lexers, `ocamlyacc`\-generated parsers. + +### Scanning indications in format strings + +Scanning indications appear just after the string conversions `%s` and `%[ range ]` to delimit the end of the token. A scanning indication is introduced by a `@` character, followed by some plain character `c`. It means that the string token should end just before the next matching `c` (which is skipped). If no `c` character is encountered, the string token spreads as much as possible. For instance, `"%s@\t"` reads a string up to the next tab character or to the end of input. If a `@` character appears anywhere else in the format string, it is treated as a plain character. + +Note: + +- As usual in format strings, `%` and `@` characters must be escaped using `%%` and `%@`; this rule still holds within range specifications and scanning indications. For instance, format `"%s@%%"` reads a string up to the next `%` character, and format `"%s@%@"` reads a string up to the next `@`. +- The scanning indications introduce slight differences in the syntax of [`Scanf`](#) format strings, compared to those used for the [`Printf`](./Stdlib-Printf.md) module. However, the scanning indications are similar to those used in the [`Format`](./Stdlib-Format.md) module; hence, when producing formatted text to be scanned by [`Scanf.bscanf`](./#val-bscanf), it is wise to use printing functions from the [`Format`](./Stdlib-Format.md) module (or, if you need to use functions from [`Printf`](./Stdlib-Printf.md), banish or carefully double check the format strings that contain `'@'` characters). + +### Exceptions during scanning + +Scanners may raise the following exceptions when the input cannot be read according to the format string: + +- Raise [`Scanf.Scan_failure`](./#exception-Scan_failure) if the input does not match the format. +- Raise `Failure` if a conversion to a number is not possible. +- Raise `End_of_file` if the end of input is encountered while some more characters are needed to read the current conversion specification. +- Raise `Invalid_argument` if the format string is invalid. +Note: + +- as a consequence, scanning a `%s` conversion never raises exception `End_of_file`: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or `""` if none were ever read. + +## Specialised formatted input functions + +``` +val sscanf : string -> ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the given string. + +``` +val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt +``` +Same as [`Scanf.sscanf`](./#val-sscanf), but returns `None` in case of scanning failure. + +since 5.0 +``` +val scanf : ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the predefined formatted input channel [`Scanf.Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) that is connected to [`Stdlib.stdin`](./Stdlib.md#val-stdin). + +``` +val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt +``` +Same as [`Scanf.scanf`](./#val-scanf), but returns `None` in case of scanning failure. + +since 5.0 +``` +val kscanf : + Scanning.in_channel -> + (Scanning.in_channel -> exn -> 'd) -> + ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.bscanf`](./#val-bscanf), but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments. + +``` +val ksscanf : + string -> + (Scanning.in_channel -> exn -> 'd) -> + ('a, 'b, 'c, 'd) scanner +``` +Same as [`Scanf.kscanf`](./#val-kscanf) but reads from the given string. + +since 4.02 + +## Reading format strings from input + +``` +val bscanf_format : + Scanning.in_channel -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> + 'g +``` +`bscanf_format ic fmt f` reads a format string token from the formatted input channel `ic`, according to the given format string `fmt`, and applies `f` to the resulting format string value. + +raises [`Scan_failure`](./#exception-Scan_failure) if the format string value read does not have the same type as fmt. +since 3.09 +``` +val sscanf_format : + string -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> + 'g +``` +Same as [`Scanf.bscanf_format`](./#val-bscanf_format), but reads from the given string. + +since 3.09 +``` +val format_from_string : + string -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 +``` +`format_from_string s fmt` converts a string argument to a format string, according to the given format string `fmt`. + +raises [`Scan_failure`](./#exception-Scan_failure) if s, considered as a format string, does not have the same type as fmt. +since 3.10 +``` +val unescaped : string -> string +``` +`unescaped s` return a copy of `s` with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, `Scanf.unescaped` has the following property: for all string `s`, `Scanf.unescaped (String.escaped s) = s`. + +Always return a copy of the argument, even if there is no escape sequence in the argument. + +raises [`Scan_failure`](./#exception-Scan_failure) if s is not properly escaped (i.e. s has invalid escape sequences or special characters that are not properly escaped). For instance, Scanf.unescaped "\\"" will fail. +since 4.00 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Seq.md b/docs/api/re/melange/Stdlib-Seq.md new file mode 100644 index 000000000..fae489474 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Seq.md @@ -0,0 +1,624 @@ + +# Module `Stdlib.Seq` + +Sequences. + +A sequence of type `'a Seq.t` can be thought of as a **delayed list**, that is, a list whose elements are computed only when they are demanded by a consumer. This allows sequences to be produced and transformed lazily (one element at a time) rather than eagerly (all elements at once). This also allows constructing conceptually infinite sequences. + +The type `'a Seq.t` is defined as a synonym for `unit -> 'a Seq.node`. This is a function type: therefore, it is opaque. The consumer can **query** a sequence in order to request the next element (if there is one), but cannot otherwise inspect the sequence in any way. + +Because it is opaque, the type `'a Seq.t` does *not* reveal whether a sequence is: + +- **persistent**, which means that the sequence can be used as many times as desired, producing the same elements every time, just like an immutable list; or +- **ephemeral**, which means that the sequence is not persistent. Querying an ephemeral sequence might have an observable side effect, such as incrementing a mutable counter. As a common special case, an ephemeral sequence can be **affine**, which means that it must be queried at most once. +It also does *not* reveal whether the elements of the sequence are: + +- **pre-computed and stored** in memory, which means that querying the sequence is cheap; +- **computed when first demanded and then stored** in memory, which means that querying the sequence once can be expensive, but querying the same sequence again is cheap; or +- **re-computed every time they are demanded**, which may or may not be cheap. +It is up to the programmer to keep these distinctions in mind so as to understand the time and space requirements of sequences. + +For the sake of simplicity, most of the documentation that follows is written under the implicit assumption that the sequences at hand are persistent. We normally do not point out *when* or *how many times* each function is invoked, because that would be too verbose. For instance, in the description of `map`, we write: "if `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`". If we wished to be more explicit, we could point out that the transformation takes place on demand: that is, the elements of `map f xs` are computed only when they are demanded. In other words, the definition `let ys = map f xs` terminates immediately and does not invoke `f`. The function call `f x0` takes place only when the first element of `ys` is demanded, via the function call `ys()`. Furthermore, calling `ys()` twice causes `f x0` to be called twice as well. If one wishes for `f` to be applied at most once to each element of `xs`, even in scenarios where `ys` is queried more than once, then one should use `let ys = memoize (map f xs)`. + +As a general rule, the functions that build sequences, such as `map`, `filter`, `scan`, `take`, etc., produce sequences whose elements are computed only on demand. The functions that eagerly consume sequences, such as `is_empty`, `find`, `length`, `iter`, `fold_left`, etc., are the functions that force computation to take place. + +When possible, we recommend using sequences rather than dispensers (functions of type `unit -> 'a option` that produce elements upon demand). Whereas sequences can be persistent or ephemeral, dispensers are always ephemeral, and are typically more difficult to work with than sequences. Two conversion functions, [`to_dispenser`](./#val-to_dispenser) and [`of_dispenser`](./#val-of_dispenser), are provided. + +since 4.07 +``` +type 'a t = unit -> 'a node +``` +A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. Such a sequence is queried by performing a function application `xs()`. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail. + +``` +and +'a node = +``` +``` +| Nil +``` +``` +| Cons of 'a * 'a t +``` +``` + +``` +A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence. + + +## Consuming sequences + +The functions in this section consume their argument, a sequence, either partially or completely: + +- `is_empty` and `uncons` consume the sequence down to depth 1\. That is, they demand the first argument of the sequence, if there is one. +- `iter`, `fold_left`, `length`, etc., consume the sequence all the way to its end. They terminate only if the sequence is finite. +- `for_all`, `exists`, `find`, etc. consume the sequence down to a certain depth, which is a priori unpredictable. +Similarly, among the functions that consume two sequences, one can distinguish two groups: + +- `iter2` and `fold_left2` consume both sequences all the way to the end, provided the sequences have the same length. +- `for_all2`, `exists2`, `equal`, `compare` consume the sequences down to a certain depth, which is a priori unpredictable. +The functions that consume two sequences can be applied to two sequences of distinct lengths: in that case, the excess elements in the longer sequence are ignored. (It may be the case that one excess element is demanded, even though this element is not used.) + +None of the functions in this section is lazy. These functions are consumers: they force some computation to take place. + +``` +val is_empty : 'a t -> bool +``` +`is_empty xs` determines whether the sequence `xs` is empty. + +It is recommended that the sequence `xs` be persistent. Indeed, `is_empty xs` demands the head of the sequence `xs`, so, if `xs` is ephemeral, it may be the case that `xs` cannot be used any more after this call has taken place. + +since 4.14 +``` +val uncons : 'a t -> ('a * 'a t) option +``` +If `xs` is empty, then `uncons xs` is `None`. + +If `xs` is nonempty, then `uncons xs` is `Some (x, ys)` where `x` is the head of the sequence and `ys` its tail. + +since 4.14 +``` +val length : 'a t -> int +``` +`length xs` is the length of the sequence `xs`. + +The sequence `xs` must be finite. + +since 4.14 +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right. + +It terminates only if the sequence `xs` is finite. + +``` +val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right. + +An accumulator of type `'a` is threaded through the calls to `f`. + +It terminates only if the sequence `xs` is finite. + +``` +val iteri : (int -> 'a -> unit) -> 'a t -> unit +``` +`iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`. + +It terminates only if the sequence `xs` is finite. + +`iteri f xs` is equivalent to `iter (fun (i, x) -> f i x) (zip (ints 0) xs)`. + +since 4.14 +``` +val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`. + +An accumulator of type `'b` is threaded through the calls to `f`. + +It terminates only if the sequence `xs` is finite. + +`fold_lefti f accu xs` is equivalent to `fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)`. + +since 4.14 +``` +val for_all : ('a -> bool) -> 'a t -> bool +``` +`for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`. + +The sequence `xs` must be finite. + +since 4.14 +``` +val exists : ('a -> bool) -> 'a t -> bool +``` +`exists xs p` determines whether at least one element `x` of the sequence `xs` satisfies `p x`. + +The sequence `xs` must be finite. + +since 4.14 +``` +val find : ('a -> bool) -> 'a t -> 'a option +``` +`find p xs` returns `Some x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element. + +It returns `None` if there is no such element. + +The sequence `xs` must be finite. + +since 4.14 +``` +val find_index : ('a -> bool) -> 'a t -> int option +``` +`find_index p xs` returns `Some i`, where `i` is the index of the first element of the sequence `xs` that satisfies `p x`, if there is such an element. + +It returns `None` if there is no such element. + +The sequence `xs` must be finite. + +since 5.1 +``` +val find_map : ('a -> 'b option) -> 'a t -> 'b option +``` +`find_map f xs` returns `Some y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`. + +It returns `None` if there is no such element. + +The sequence `xs` must be finite. + +since 4.14 +``` +val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option +``` +Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. + +The sequence `xs` must be finite. + +since 5.1 +``` +val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit +``` +`iter2 f xs ys` invokes `f x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. + +If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + +Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. + +`iter2 f xs ys` is equivalent to `iter (fun (x, y) -> f x y) (zip xs ys)`. + +since 4.14 +``` +val fold_left2 : ('acc -> 'a -> 'b -> 'acc) -> 'acc -> 'a t -> 'b t -> 'acc +``` +`fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. + +An accumulator of type `'a` is threaded through the calls to `f`. + +If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + +Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. + +`fold_left2 f accu xs ys` is equivalent to `fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)`. + +since 4.14 +``` +val for_all2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool +``` +`for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`. + +If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if `xs` or `ys` is empty, then `for_all2 p xs ys` is true. This is where `for_all2` and `equal` differ: `equal eq xs ys` can be true only if `xs` and `ys` have the same length. + +At least one of the sequences `xs` and `ys` must be finite. + +`for_all2 p xs ys` is equivalent to `for_all (fun b -> b) (map2 p xs ys)`. + +since 4.14 +``` +val exists2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool +``` +`exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`. + +If the sequences `xs` and `ys` have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + +At least one of the sequences `xs` and `ys` must be finite. + +`exists2 p xs ys` is equivalent to `exists (fun b -> b) (map2 p xs ys)`. + +since 4.14 +``` +val equal : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool +``` +Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal. + +At least one of the sequences `xs` and `ys` must be finite. + +since 4.14 +``` +val compare : ('a -> 'b -> int) -> 'a t -> 'b t -> int +``` +Provided the function `cmp` defines a preorder on elements, `compare cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder. + +For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). + +At least one of the sequences `xs` and `ys` must be finite. + +since 4.14 + +## Constructing sequences + +The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. + +``` +val empty : 'a t +``` +`empty` is the empty sequence. It has no elements. Its length is 0. + +``` +val return : 'a -> 'a t +``` +`return x` is the sequence whose sole element is `x`. Its length is 1\. + +``` +val cons : 'a -> 'a t -> 'a t +``` +`cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`. + +Writing `cons (f()) xs` causes the function call `f()` to take place immediately. For this call to be delayed until the sequence is queried, one must instead write `(fun () -> Cons(f(), xs))`. + +since 4.11 +``` +val init : int -> (int -> 'a) -> 'a t +``` +`init n f` is the sequence `f 0; f 1; ...; f (n-1)`. + +`n` must be nonnegative. + +If desired, the infinite sequence `f 0; f 1; ...` can be defined as `map f (ints 0)`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.14 +``` +val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t +``` +`unfold` constructs a sequence out of a step function and an initial state. + +If `f u` is `None` then `unfold f u` is the empty sequence. If `f u` is `Some (x, u')` then `unfold f u` is the nonempty sequence `cons x (unfold f u')`. + +For example, `unfold (function [] -> None | h :: t -> Some (h, t)) l` is equivalent to `List.to_seq l`. + +since 4.11 +``` +val repeat : 'a -> 'a t +``` +`repeat x` is the infinite sequence where the element `x` is repeated indefinitely. + +`repeat x` is equivalent to `cycle (return x)`. + +since 4.14 +``` +val forever : (unit -> 'a) -> 'a t +``` +`forever f` is an infinite sequence where every element is produced (on demand) by the function call `f()`. + +For instance, `forever Random.bool` is an infinite sequence of random bits. + +`forever f` is equivalent to `map f (repeat ())`. + +since 4.14 +``` +val cycle : 'a t -> 'a t +``` +`cycle xs` is the infinite sequence that consists of an infinite number of repetitions of the sequence `xs`. + +If `xs` is an empty sequence, then `cycle xs` is empty as well. + +Consuming (a prefix of) the sequence `cycle xs` once can cause the sequence `xs` to be consumed more than once. Therefore, `xs` must be persistent. + +since 4.14 +``` +val iterate : ('a -> 'a) -> 'a -> 'a t +``` +`iterate f x` is the infinite sequence whose elements are `x`, `f x`, `f (f x)`, and so on. + +In other words, it is the orbit of the function `f`, starting at `x`. + +since 4.14 + +## Transforming sequences + +The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. + +``` +val map : ('a -> 'b) -> 'a t -> 'b t +``` +`map f xs` is the image of the sequence `xs` through the transformation `f`. + +If `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`. + +``` +val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t +``` +`mapi` is analogous to `map`, but applies the function `f` to an index and an element. + +`mapi f xs` is equivalent to `map2 f (ints 0) xs`. + +since 4.14 +``` +val filter : ('a -> bool) -> 'a t -> 'a t +``` +`filter p xs` is the sequence of the elements `x` of `xs` that satisfy `p x`. + +In other words, `filter p xs` is the sequence `xs`, deprived of the elements `x` such that `p x` is false. + +``` +val filter_map : ('a -> 'b option) -> 'a t -> 'b t +``` +`filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`. + +`filter_map f xs` is equivalent to `map Option.get (filter Option.is_some (map f xs))`. + +``` +val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t +``` +If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators `[a0; a1; a2; ...]` where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on. + +Thus, `scan f a0 xs` is conceptually related to `fold_left f a0 xs`. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators. + +For instance, `scan (+) 0` transforms a sequence of integers into the sequence of its partial sums. + +If `xs` has length `n` then `scan f a0 xs` has length `n+1`. + +since 4.14 +``` +val take : int -> 'a t -> 'a t +``` +`take n xs` is the sequence of the first `n` elements of `xs`. + +If `xs` has fewer than `n` elements, then `take n xs` is equivalent to `xs`. + +`n` must be nonnegative. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.14 +``` +val drop : int -> 'a t -> 'a t +``` +`drop n xs` is the sequence `xs`, deprived of its first `n` elements. + +If `xs` has fewer than `n` elements, then `drop n xs` is empty. + +`n` must be nonnegative. + +`drop` is lazy: the first `n+1` elements of the sequence `xs` are demanded only when the first element of `drop n xs` is demanded. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. +since 4.14 +``` +val take_while : ('a -> bool) -> 'a t -> 'a t +``` +`take_while p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`. + +since 4.14 +``` +val drop_while : ('a -> bool) -> 'a t -> 'a t +``` +`drop_while p xs` is the sequence `xs`, deprived of the prefix `take_while p xs`. + +since 4.14 +``` +val group : ('a -> 'a -> bool) -> 'a t -> 'a t t +``` +Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`. + +Every element of `group eq xs` is a nonempty sequence of equal elements. + +The concatenation `concat (group eq xs)` is equal to `xs`. + +Consuming `group eq xs`, and consuming the sequences that it contains, can cause `xs` to be consumed more than once. Therefore, `xs` must be persistent. + +since 4.14 +``` +val memoize : 'a t -> 'a t +``` +The sequence `memoize xs` has the same elements as the sequence `xs`. + +Regardless of whether `xs` is ephemeral or persistent, `memoize xs` is persistent: even if it is queried several times, `xs` is queried at most once. + +The construction of the sequence `memoize xs` internally relies on suspensions provided by the module [`Lazy`](./Stdlib-Lazy.md). These suspensions are *not* thread-safe. Therefore, the sequence `memoize xs` must *not* be queried by multiple threads concurrently. + +since 4.14 +``` +exception Forced_twice +``` +This exception is raised when a sequence returned by [`once`](./#val-once) (or a suffix of it) is queried more than once. + +since 4.14 +``` +val once : 'a t -> 'a t +``` +The sequence `once xs` has the same elements as the sequence `xs`. + +Regardless of whether `xs` is ephemeral or persistent, `once xs` is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception `Forced_twice` is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once. + +raises [`Forced_twice`](./#exception-Forced_twice) if once xs, or a suffix of it, is queried more than once. +since 4.14 +``` +val transpose : 'a t t -> 'a t t +``` +If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`. + +The rows of the matrix `xss` are not required to have the same length. + +The matrix `xss` is not required to be finite (in either direction). + +The matrix `xss` must be persistent. + +since 4.14 + +## Combining sequences + +``` +val append : 'a t -> 'a t -> 'a t +``` +`append xs ys` is the concatenation of the sequences `xs` and `ys`. + +Its elements are the elements of `xs`, followed by the elements of `ys`. + +since 4.11 +``` +val concat : 'a t t -> 'a t +``` +If `xss` is a sequence of sequences, then `concat xss` is its concatenation. + +If `xss` is the sequence `xs0; xs1; ...` then `concat xss` is the sequence `xs0 @ xs1 @ ...`. + +since 4.13 +``` +val flat_map : ('a -> 'b t) -> 'a t -> 'b t +``` +`flat_map f xs` is equivalent to `concat (map f xs)`. + +``` +val concat_map : ('a -> 'b t) -> 'a t -> 'b t +``` +`concat_map f xs` is equivalent to `concat (map f xs)`. + +`concat_map` is an alias for `flat_map`. + +since 4.13 +``` +val zip : 'a t -> 'b t -> ('a * 'b) t +``` +`zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`. + +If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + +`zip xs ys` is equivalent to `map2 (fun a b -> (a, b)) xs ys`. + +since 4.14 +``` +val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t +``` +`map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`. + +If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. + +`map2 f xs ys` is equivalent to `map (fun (x, y) -> f x y) (zip xs ys)`. + +since 4.14 +``` +val interleave : 'a t -> 'a t -> 'a t +``` +`interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on. + +When one of the sequences `xs` and `ys` is exhausted, `interleave xs ys` continues with the rest of the other sequence. + +since 4.14 +``` +val sorted_merge : ('a -> 'a -> int) -> 'a t -> 'a t -> 'a t +``` +If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`. + +For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). + +since 4.14 +``` +val product : 'a t -> 'b t -> ('a * 'b) t +``` +`product xs ys` is the Cartesian product of the sequences `xs` and `ys`. + +For every element `x` of `xs` and for every element `y` of `ys`, the pair `(x, y)` appears once as an element of `product xs ys`. + +The order in which the pairs appear is unspecified. + +The sequences `xs` and `ys` are not required to be finite. + +The sequences `xs` and `ys` must be persistent. + +since 4.14 +``` +val map_product : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t +``` +The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`. + +For every element `x` of `xs` and for every element `y` of `ys`, the element `f x y` appears once as an element of `map_product f xs ys`. + +The order in which these elements appear is unspecified. + +The sequences `xs` and `ys` are not required to be finite. + +The sequences `xs` and `ys` must be persistent. + +`map_product f xs ys` is equivalent to `map (fun (x, y) -> f x y) (product xs ys)`. + +since 4.14 + +## Splitting a sequence into two sequences + +``` +val unzip : ('a * 'b) t -> 'a t * 'b t +``` +`unzip` transforms a sequence of pairs into a pair of sequences. + +`unzip xs` is equivalent to `(map fst xs, map snd xs)`. + +Querying either of the sequences returned by `unzip xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `unzip (memoize xs)`. + +since 4.14 +``` +val split : ('a * 'b) t -> 'a t * 'b t +``` +`split` is an alias for `unzip`. + +since 4.14 +``` +val partition_map : ('a -> ('b, 'c) Either.t) -> 'a t -> 'b t * 'c t +``` +`partition_map f xs` returns a pair of sequences `(ys, zs)`, where: + +- `ys` is the sequence of the elements `y` such that `f x = Left y`, where `x` ranges over `xs`; +- `zs` is the sequence of the elements `z` such that `f x = Right z`, where `x` ranges over `xs`. +`partition_map f xs` is equivalent to a pair of `filter_map Either.find_left (map f xs)` and `filter_map Either.find_right (map f xs)`. + +Querying either of the sequences returned by `partition_map f xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `partition_map f (memoize xs)`. + +since 4.14 +``` +val partition : ('a -> bool) -> 'a t -> 'a t * 'a t +``` +`partition p xs` returns a pair of the subsequence of the elements of `xs` that satisfy `p` and the subsequence of the elements of `xs` that do not satisfy `p`. + +`partition p xs` is equivalent to `filter p xs, filter (fun x -> not (p x)) xs`. + +Consuming both of the sequences returned by `partition p xs` causes `xs` to be consumed twice and causes the function `f` to be applied twice to each element of the list. Therefore, `f` should be pure and cheap. Furthermore, `xs` should be persistent and cheap. If that is not the case, use `partition p (memoize xs)`. + +since 4.14 + +## Converting between sequences and dispensers + +A dispenser is a representation of a sequence as a function of type `unit -> 'a option`. Every time this function is invoked, it returns the next element of the sequence. When there are no more elements, it returns `None`. A dispenser has mutable internal state, therefore is ephemeral: the sequence that it represents can be consumed at most once. + +``` +val of_dispenser : (unit -> 'a option) -> 'a t +``` +`of_dispenser it` is the sequence of the elements produced by the dispenser `it`. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use `memoize (of_dispenser it)`. + +since 4.14 +``` +val to_dispenser : 'a t -> unit -> 'a option +``` +`to_dispenser xs` is a fresh dispenser on the sequence `xs`. + +This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently. + +since 4.14 + +## Sequences of integers + +``` +val ints : int -> int t +``` +`ints i` is the infinite sequence of the integers beginning at `i` and counting up. + +since 4.14 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md new file mode 100644 index 000000000..3abdead73 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md @@ -0,0 +1,12 @@ + +# Parameter `Make.Ord` + +``` +type t +``` +The type of the set elements. + +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Set-Make.md b/docs/api/re/melange/Stdlib-Set-Make.md new file mode 100644 index 000000000..93d2962e8 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Set-Make.md @@ -0,0 +1,297 @@ + +# Module `Set.Make` + +Functor building an implementation of the set structure given a totally ordered type. + + +## Parameters + +``` +module Ord : OrderedType +``` + +## Signature + + +## Sets + +``` +type elt = Ord.t +``` +The type of the set elements. + +``` +type t +``` +The type of sets. + +``` +val empty : t +``` +The empty set. + +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. + +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. + +``` +val inter : t -> t -> t +``` +Set intersection. + +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. + +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + +``` +val cardinal : t -> int +``` +Return the number of elements of a set. + + +## Elements + +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). + +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +since 4.05 + +## Searching + +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + +since 4.05 +``` +val find_first : (elt -> bool) -> t -> elt +``` +`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + +since 4.05 +``` +val find_first_opt : (elt -> bool) -> t -> elt option +``` +`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 +``` +val find_last : (elt -> bool) -> t -> elt +``` +`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +since 4.05 +``` +val find_last_opt : (elt -> bool) -> t -> elt option +``` +`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 + +## Traversing + +``` +val iter : (elt -> unit) -> t -> unit +``` +`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + +``` +val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + +## Transforming + +``` +val map : (elt -> elt) -> t -> t +``` +`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + +since 4.04 +``` +val filter : (elt -> bool) -> t -> t +``` +`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val filter_map : (elt -> elt option) -> t -> t +``` +`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + +For example, + +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. + +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + +since 4.11 +``` +val partition : (elt -> bool) -> t -> t * t +``` +`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + +## Predicates and comparisons + +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. + +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. + +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. + +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + +``` +val for_all : (elt -> bool) -> t -> bool +``` +`for_all f s` checks if all elements of the set satisfy the predicate `f`. + +``` +val exists : (elt -> bool) -> t -> bool +``` +`exists f s` checks if at least one element of the set satisfies the predicate `f`. + + +## Converting + +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. + +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order + +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order + +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. + +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md new file mode 100644 index 000000000..11f9d9c0d --- /dev/null +++ b/docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md @@ -0,0 +1,14 @@ + +# Module type `Set.OrderedType` + +Input signature of the functor [`Make`](./Stdlib-Set-Make.md). + +``` +type t +``` +The type of the set elements. + +``` +val compare : t -> t -> int +``` +A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Set-module-type-S.md b/docs/api/re/melange/Stdlib-Set-module-type-S.md new file mode 100644 index 000000000..72db61d6a --- /dev/null +++ b/docs/api/re/melange/Stdlib-Set-module-type-S.md @@ -0,0 +1,288 @@ + +# Module type `Set.S` + +Output signature of the functor [`Make`](./Stdlib-Set-Make.md). + + +## Sets + +``` +type elt +``` +The type of the set elements. + +``` +type t +``` +The type of sets. + +``` +val empty : t +``` +The empty set. + +``` +val add : elt -> t -> t +``` +`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val singleton : elt -> t +``` +`singleton x` returns the one-element set containing only `x`. + +``` +val remove : elt -> t -> t +``` +`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val union : t -> t -> t +``` +Set union. + +``` +val inter : t -> t -> t +``` +Set intersection. + +``` +val disjoint : t -> t -> bool +``` +Test if two sets are disjoint. + +since 4.08 +``` +val diff : t -> t -> t +``` +Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. + +``` +val cardinal : t -> int +``` +Return the number of elements of a set. + + +## Elements + +``` +val elements : t -> elt list +``` +Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-Set-Make.md). + +``` +val min_elt : t -> elt +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. + +``` +val min_elt_opt : t -> elt option +``` +Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. + +since 4.05 +``` +val max_elt : t -> elt +``` +Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. + +``` +val max_elt_opt : t -> elt option +``` +Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. + +since 4.05 +``` +val choose : t -> elt +``` +Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +``` +val choose_opt : t -> elt option +``` +Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. + +since 4.05 + +## Searching + +``` +val find : elt -> t -> elt +``` +`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. + +since 4.01 +``` +val find_opt : elt -> t -> elt option +``` +`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. + +since 4.05 +``` +val find_first : (elt -> bool) -> t -> elt +``` +`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. + +since 4.05 +``` +val find_first_opt : (elt -> bool) -> t -> elt option +``` +`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 +``` +val find_last : (elt -> bool) -> t -> elt +``` +`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. + +since 4.05 +``` +val find_last_opt : (elt -> bool) -> t -> elt option +``` +`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. + +since 4.05 + +## Traversing + +``` +val iter : (elt -> unit) -> t -> unit +``` +`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. + +``` +val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. + + +## Transforming + +``` +val map : (elt -> elt) -> t -> t +``` +`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. + +The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. + +If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) + +since 4.04 +``` +val filter : (elt -> bool) -> t -> t +``` +`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). + +before 4.03 Physical equality was not ensured. +``` +val filter_map : (elt -> elt option) -> t -> t +``` +`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. + +For example, + +```ocaml +filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s +``` +is the set of halves of the even elements of `s`. + +If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. + +since 4.11 +``` +val partition : (elt -> bool) -> t -> t * t +``` +`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. + +``` +val split : elt -> t -> t * bool * t +``` +`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. + + +## Predicates and comparisons + +``` +val is_empty : t -> bool +``` +Test whether a set is empty or not. + +``` +val mem : elt -> t -> bool +``` +`mem x s` tests whether `x` belongs to the set `s`. + +``` +val equal : t -> t -> bool +``` +`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. + +``` +val compare : t -> t -> int +``` +Total ordering between sets. Can be used as the ordering function for doing sets of sets. + +``` +val subset : t -> t -> bool +``` +`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. + +``` +val for_all : (elt -> bool) -> t -> bool +``` +`for_all f s` checks if all elements of the set satisfy the predicate `f`. + +``` +val exists : (elt -> bool) -> t -> bool +``` +`exists f s` checks if at least one element of the set satisfies the predicate `f`. + + +## Converting + +``` +val to_list : t -> elt list +``` +`to_list s` is [`elements`](./#val-elements)` s`. + +since 5.1 +``` +val of_list : elt list -> t +``` +`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. + +since 4.02 +``` +val to_seq_from : elt -> t -> elt Seq.t +``` +`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. + +since 4.07 +``` +val to_seq : t -> elt Seq.t +``` +Iterate on the whole set, in ascending order + +since 4.07 +``` +val to_rev_seq : t -> elt Seq.t +``` +Iterate on the whole set, in descending order + +since 4.12 +``` +val add_seq : elt Seq.t -> t -> t +``` +Add the given elements to the set, in order. + +since 4.07 +``` +val of_seq : elt Seq.t -> t +``` +Build a set from the given bindings + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Set.md b/docs/api/re/melange/Stdlib-Set.md new file mode 100644 index 000000000..f961f9b00 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Set.md @@ -0,0 +1,39 @@ + +# Module `Stdlib.Set` + +Sets over ordered types. + +This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. + +The [`Make`](./Stdlib-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: + +```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 PairsSet = Set.Make(IntPairs) + + let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) +``` +This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. + +``` +module type OrderedType = sig ... end +``` +Input signature of the functor [`Make`](./Stdlib-Set-Make.md). + +``` +module type S = sig ... end +``` +Output signature of the functor [`Make`](./Stdlib-Set-Make.md). + +``` +module Make (Ord : OrderedType) : S with type elt = Ord.t +``` +Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-Stack.md b/docs/api/re/melange/Stdlib-Stack.md new file mode 100644 index 000000000..e02894994 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Stack.md @@ -0,0 +1,111 @@ + +# Module `Stdlib.Stack` + +Last-in first-out stacks. + +This module implements stacks (LIFOs), with in-place modification. + +**Unsynchronized accesses** + +Unsynchronized accesses to a stack may lead to an invalid queue state. Thus, concurrent accesses to stacks must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + +``` +type !'a t +``` +The type of stacks containing elements of type `'a`. + +``` +exception Empty +``` +Raised when [`Stack.pop`](./#val-pop) or [`Stack.top`](./#val-top) is applied to an empty stack. + +``` +val create : unit -> 'a t +``` +Return a new stack, initially empty. + +``` +val push : 'a -> 'a t -> unit +``` +`push x s` adds the element `x` at the top of stack `s`. + +``` +val pop : 'a t -> 'a +``` +`pop s` removes and returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. + +``` +val pop_opt : 'a t -> 'a option +``` +`pop_opt s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty. + +since 4.08 +``` +val drop : 'a t -> unit +``` +`drop s` removes the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. + +since 5.1 +``` +val top : 'a t -> 'a +``` +`top s` returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. + +``` +val top_opt : 'a t -> 'a option +``` +`top_opt s` returns the topmost element in stack `s`, or `None` if the stack is empty. + +since 4.08 +``` +val clear : 'a t -> unit +``` +Discard all elements from a stack. + +``` +val copy : 'a t -> 'a t +``` +Return a copy of the given stack. + +``` +val is_empty : 'a t -> bool +``` +Return `true` if the given stack is empty, `false` otherwise. + +``` +val length : 'a t -> int +``` +Return the number of elements in a stack. Time complexity O(1) + +``` +val iter : ('a -> unit) -> 'a t -> unit +``` +`iter f s` applies `f` in turn to all elements of `s`, from the element at the top of the stack to the element at the bottom of the stack. The stack itself is unchanged. + +``` +val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc +``` +`fold f accu s` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1` is the top of the stack, `x2` the second element, and `xn` the bottom element. The stack is unchanged. + +since 4.03 + +## Stacks and Sequences + +``` +val to_seq : 'a t -> 'a Seq.t +``` +Iterate on the stack, top to bottom. It is safe to modify the stack during iteration. + +since 4.07 +``` +val add_seq : 'a t -> 'a Seq.t -> unit +``` +Add the elements from the sequence on the top of the stack. + +since 4.07 +``` +val of_seq : 'a Seq.t -> 'a t +``` +Create a stack from the sequence. + +since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-StdLabels.md b/docs/api/re/melange/Stdlib-StdLabels.md new file mode 100644 index 000000000..e90ae87f6 --- /dev/null +++ b/docs/api/re/melange/Stdlib-StdLabels.md @@ -0,0 +1,26 @@ + +# Module `Stdlib.StdLabels` + +Standard labeled libraries. + +This meta-module provides versions of the [`Array`](./Stdlib-ArrayLabels.md), [`Bytes`](./Stdlib-BytesLabels.md), [`List`](./Stdlib-ListLabels.md) and [`String`](./Stdlib-StringLabels.md) modules where function arguments are systematically labeled. It is intended to be opened at the top of source files, as shown below. + +```ocaml + open StdLabels + + let to_upper = String.map ~f:Char.uppercase_ascii + let seq len = List.init ~f:(fun i -> i) ~len + let everything = Array.create_matrix ~dimx:42 ~dimy:42 42 +``` +``` +module Array = ArrayLabels +``` +``` +module Bytes = BytesLabels +``` +``` +module List = ListLabels +``` +``` +module String = StringLabels +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-String.md b/docs/api/re/melange/Stdlib-String.md new file mode 100644 index 000000000..063536325 --- /dev/null +++ b/docs/api/re/melange/Stdlib-String.md @@ -0,0 +1,480 @@ + +# Module `Stdlib.String` + +Strings. + +A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. + +The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. + +``` +positions 0 1 2 3 4 n-1 n + +---+---+---+---+ +-----+ + indices | 0 | 1 | 2 | 3 | ... | n-1 | + +---+---+---+---+ +-----+ +``` +- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. +- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. +Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. + +**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. + +**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + + +## Strings + +``` +type t = string +``` +The type for strings. + +``` +val make : int -> char -> string +``` +`make n c` is a string of length `n` with each index holding the character `c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> (int -> char) -> string +``` +`init n f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +since 4.02 +``` +val empty : string +``` +The empty string. + +since 4.13 +``` +val length : string -> int +``` +`length s` is the length (number of bytes/characters) of `s`. + +``` +val get : string -> int -> char +``` +`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. +``` +val of_bytes : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. + +since 4.13 +``` +val to_bytes : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. + +since 4.13 +``` +val blit : string -> int -> bytes -> int -> int -> unit +``` +Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. + + +## Concatenating + +**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. + +``` +val concat : string -> string list -> string +``` +`concat sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : string -> string -> string +``` +`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.13 + +## Predicates and comparisons + +``` +val equal : t -> t -> bool +``` +`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. + +since 4.03 (4.05 in StringLabels) +``` +val compare : t -> t -> int +``` +`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. + +``` +val starts_with : prefix:string -> string -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + +since 4.13 +``` +val ends_with : suffix:string -> string -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + +since 4.13 +``` +val contains_from : string -> int -> char -> bool +``` +`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : string -> int -> char -> bool +``` +`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val contains : string -> char -> bool +``` +`contains s c` is [`String.contains_from`](./#val-contains_from)` s 0 c`. + + +## Extracting substrings + +``` +val sub : string -> int -> int -> string +``` +`sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. +``` +val split_on_char : char -> string -> string list +``` +`split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. + +The function's result is specified by the following invariants: + +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). +- No string in the result contains the `sep` character. +since 4.04 (4.05 in StringLabels) + +## Transforming + +``` +val map : (char -> char) -> string -> string +``` +`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. + +since 4.00 +``` +val mapi : (int -> char -> char) -> string -> string +``` +`mapi f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. + +since 4.02 +``` +val fold_left : ('acc -> char -> 'acc) -> 'acc -> string -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. + +since 4.13 +``` +val fold_right : (char -> 'acc -> 'acc) -> string -> 'acc -> 'acc +``` +`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. + +since 4.13 +``` +val for_all : (char -> bool) -> string -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. + +since 4.13 +``` +val exists : (char -> bool) -> string -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. + +since 4.13 +``` +val trim : string -> string +``` +`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. + +since 4.00 +``` +val escaped : string -> string +``` +`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. + +All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). + +The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val uppercase_ascii : string -> string +``` +`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) +``` +val lowercase_ascii : string -> string +``` +`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) +``` +val capitalize_ascii : string -> string +``` +`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) +``` +val uncapitalize_ascii : string -> string +``` +`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) + +## Traversing + +``` +val iter : (char -> unit) -> string -> unit +``` +`iter f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. + +``` +val iteri : (int -> char -> unit) -> string -> unit +``` +`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. + +since 4.00 + +## Searching + +``` +val index_from : string -> int -> char -> int +``` +`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +``` +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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : string -> int -> char -> int +``` +`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +``` +val rindex_from_opt : string -> int -> char -> int option +``` +`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val index : string -> char -> int +``` +`index s c` is [`String.index_from`](./#val-index_from)` s 0 c`. + +``` +val index_opt : string -> char -> int option +``` +`index_opt s c` is [`String.index_from_opt`](./#val-index_from_opt)` s 0 c`. + +since 4.05 +``` +val rindex : string -> char -> int +``` +`rindex s c` is [`String.rindex_from`](./#val-rindex_from)` s (length s - 1) c`. + +``` +val rindex_opt : string -> char -> int option +``` +`rindex_opt s c` is [`String.rindex_from_opt`](./#val-rindex_from_opt)` s (length s - 1) c`. + +since 4.05 + +## Strings and Sequences + +``` +val to_seq : t -> char Seq.t +``` +`to_seq s` is a sequence made of the string's characters in increasing order. + +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. + +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +`of_seq s` is a string made of the sequence's characters. + +since 4.07 + +## UTF decoding and validations + +since 4.14 + +### UTF-8 + +``` +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`. + +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + +### UTF-16BE + +``` +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`. + +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + +### UTF-16LE + +``` +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`. + +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + +## Binary decoding of integers + +The functions in this section binary decode integers from strings. + +All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. + +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. + +``` +val get_uint8 : string -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int8 : string -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. + +since 4.13 +``` +val get_uint16_ne : string -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_uint16_be : string -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_uint16_le : string -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int16_ne : string -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int16_be : string -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int16_le : string -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int32_ne : string -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. + +since 4.13 +``` +val hash : t -> int +``` +An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.0 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.0 +``` +val get_int32_be : string -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int32_le : string -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int64_ne : string -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int64_be : string -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int64_le : string -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. + +since 4.13 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-StringLabels.md b/docs/api/re/melange/Stdlib-StringLabels.md new file mode 100644 index 000000000..c969a00a3 --- /dev/null +++ b/docs/api/re/melange/Stdlib-StringLabels.md @@ -0,0 +1,486 @@ + +# Module `Stdlib.StringLabels` + +Strings. + +A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. + +The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. + +``` +positions 0 1 2 3 4 n-1 n + +---+---+---+---+ +-----+ + indices | 0 | 1 | 2 | 3 | ... | n-1 | + +---+---+---+---+ +-----+ +``` +- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. +- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. +Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. + +**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. + +**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. + +The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. + + +## Strings + +``` +type t = string +``` +The type for strings. + +``` +val make : int -> char -> string +``` +`make n c` is a string of length `n` with each index holding the character `c`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +``` +val init : int -> f:(int -> char) -> string +``` +`init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. +since 4.02 +``` +val empty : string +``` +The empty string. + +since 4.13 +``` +val length : string -> int +``` +`length s` is the length (number of bytes/characters) of `s`. + +``` +val get : string -> int -> char +``` +`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. +``` +val of_bytes : bytes -> string +``` +Return a new string that contains the same bytes as the given byte sequence. + +since 4.13 +``` +val to_bytes : string -> bytes +``` +Return a new byte sequence that contains the same bytes as the given string. + +since 4.13 +``` +val blit : + src:string -> + src_pos:int -> + dst:bytes -> + dst_pos:int -> + len:int -> + unit +``` +Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. + + +## Concatenating + +**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. + +``` +val concat : sep:string -> string list -> string +``` +`concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val cat : string -> string -> string +``` +`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +since 4.13 + +## Predicates and comparisons + +``` +val equal : t -> t -> bool +``` +`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. + +since 4.03 (4.05 in StringLabels) +``` +val compare : t -> t -> int +``` +`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. + +``` +val starts_with : prefix:string -> string -> bool +``` +`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. + +since 4.13 +``` +val ends_with : suffix:string -> string -> bool +``` +`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. + +since 4.13 +``` +val contains_from : string -> int -> char -> bool +``` +`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. +``` +val rcontains_from : string -> int -> char -> bool +``` +`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. +``` +val contains : string -> char -> bool +``` +`contains s c` is [`String.contains_from`](./Stdlib-String.md#val-contains_from)` s 0 c`. + + +## Extracting substrings + +``` +val sub : string -> pos:int -> len:int -> string +``` +`sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. +``` +val split_on_char : sep:char -> string -> string list +``` +`split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. + +The function's result is specified by the following invariants: + +- The list is not empty. +- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). +- No string in the result contains the `sep` character. +since 4.04 (4.05 in StringLabels) + +## Transforming + +``` +val map : f:(char -> char) -> string -> string +``` +`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. + +since 4.00 +``` +val mapi : f:(int -> char -> char) -> string -> string +``` +`mapi ~f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. + +since 4.02 +``` +val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> string -> 'acc +``` +`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. + +since 4.13 +``` +val fold_right : f:(char -> 'acc -> 'acc) -> string -> init:'acc -> 'acc +``` +`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. + +since 4.13 +``` +val for_all : f:(char -> bool) -> string -> bool +``` +`for_all p s` checks if all characters in `s` satisfy the predicate `p`. + +since 4.13 +``` +val exists : f:(char -> bool) -> string -> bool +``` +`exists p s` checks if at least one character of `s` satisfies the predicate `p`. + +since 4.13 +``` +val trim : string -> string +``` +`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. + +since 4.00 +``` +val escaped : string -> string +``` +`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. + +All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). + +The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. +``` +val uppercase_ascii : string -> string +``` +`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) +``` +val lowercase_ascii : string -> string +``` +`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) +``` +val capitalize_ascii : string -> string +``` +`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) +``` +val uncapitalize_ascii : string -> string +``` +`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. + +since 4.03 (4.05 in StringLabels) + +## Traversing + +``` +val iter : f:(char -> unit) -> string -> unit +``` +`iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. + +``` +val iteri : f:(int -> char -> unit) -> string -> unit +``` +`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. + +since 4.00 + +## Searching + +``` +val index_from : string -> int -> char -> int +``` +`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +``` +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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. +since 4.05 +``` +val rindex_from : string -> int -> char -> int +``` +`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +``` +val rindex_from_opt : string -> int -> char -> int option +``` +`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. +since 4.05 +``` +val index : string -> char -> int +``` +`index s c` is [`String.index_from`](./Stdlib-String.md#val-index_from)` s 0 c`. + +``` +val index_opt : string -> char -> int option +``` +`index_opt s c` is [`String.index_from_opt`](./Stdlib-String.md#val-index_from_opt)` s 0 c`. + +since 4.05 +``` +val rindex : string -> char -> int +``` +`rindex s c` is [`String.rindex_from`](./Stdlib-String.md#val-rindex_from)` s (length s - 1) c`. + +``` +val rindex_opt : string -> char -> int option +``` +`rindex_opt s c` is [`String.rindex_from_opt`](./Stdlib-String.md#val-rindex_from_opt)` s (length s - 1) c`. + +since 4.05 + +## Strings and Sequences + +``` +val to_seq : t -> char Seq.t +``` +`to_seq s` is a sequence made of the string's characters in increasing order. + +since 4.07 +``` +val to_seqi : t -> (int * char) Seq.t +``` +`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. + +since 4.07 +``` +val of_seq : char Seq.t -> t +``` +`of_seq s` is a string made of the sequence's characters. + +since 4.07 + +## UTF decoding and validations + +since 4.14 + +### UTF-8 + +``` +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`. + +``` +val is_valid_utf_8 : t -> bool +``` +`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. + + +### UTF-16BE + +``` +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`. + +``` +val is_valid_utf_16be : t -> bool +``` +`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. + + +### UTF-16LE + +``` +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`. + +``` +val is_valid_utf_16le : t -> bool +``` +`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. + + +## Binary decoding of integers + +The functions in this section binary decode integers from strings. + +All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. + +Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). + +32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. + +8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. + +``` +val get_uint8 : string -> int -> int +``` +`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int8 : string -> int -> int +``` +`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. + +since 4.13 +``` +val get_uint16_ne : string -> int -> int +``` +`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_uint16_be : string -> int -> int +``` +`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_uint16_le : string -> int -> int +``` +`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int16_ne : string -> int -> int +``` +`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int16_be : string -> int -> int +``` +`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int16_le : string -> int -> int +``` +`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int32_ne : string -> int -> int32 +``` +`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. + +since 4.13 +``` +val hash : t -> int +``` +An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.0 +``` +val seeded_hash : int -> t -> int +``` +A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.0 +``` +val get_int32_be : string -> int -> int32 +``` +`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int32_le : string -> int -> int32 +``` +`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int64_ne : string -> int -> int64 +``` +`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int64_be : string -> int -> int64 +``` +`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. + +since 4.13 +``` +val get_int64_le : string -> int -> int64 +``` +`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. + +since 4.13 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md new file mode 100644 index 000000000..8c2c620d7 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md @@ -0,0 +1,6 @@ + +# Parameter `Make.Immediate` + +``` +type t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md new file mode 100644 index 000000000..08e19ba97 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md @@ -0,0 +1,6 @@ + +# Parameter `Make.Non_immediate` + +``` +type t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md new file mode 100644 index 000000000..deef830ee --- /dev/null +++ b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md @@ -0,0 +1,33 @@ + +# Module `Immediate64.Make` + + +## Parameters + +``` +module Immediate : Immediate +``` +``` +module Non_immediate : Non_immediate +``` + +## Signature + +``` +type t +``` +``` +type 'a repr = +``` +``` +| Immediate : Immediate.t repr +``` +``` +| Non_immediate : Non_immediate.t repr +``` +``` + +``` +``` +val repr : t repr +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md new file mode 100644 index 000000000..f63bbba0a --- /dev/null +++ b/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md @@ -0,0 +1,6 @@ + +# Module type `Immediate64.Immediate` + +``` +type t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md new file mode 100644 index 000000000..d4d3814fd --- /dev/null +++ b/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md @@ -0,0 +1,6 @@ + +# Module type `Immediate64.Non_immediate` + +``` +type t +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64.md b/docs/api/re/melange/Stdlib-Sys-Immediate64.md new file mode 100644 index 000000000..79e8eb8ca --- /dev/null +++ b/docs/api/re/melange/Stdlib-Sys-Immediate64.md @@ -0,0 +1,18 @@ + +# Module `Sys.Immediate64` + +This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. + +since 4.10 +``` +module type Non_immediate = sig ... end +``` +``` +module type Immediate = sig ... end +``` +``` +module Make + (Immediate : Immediate) + (Non_immediate : Non_immediate) : + sig ... end +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys.md b/docs/api/re/melange/Stdlib-Sys.md new file mode 100644 index 000000000..af5584b69 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Sys.md @@ -0,0 +1,476 @@ + +# Module `Stdlib.Sys` + +System interface. + +Every function in this module raises `Sys_error` with an informative message when the underlying system call signal an error. + +``` +val argv : string array +``` +The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program. + +``` +val executable_name : string +``` +The name of the file containing the executable currently running. This name may be absolute or relative to the current directory, depending on the platform and whether the program was compiled to bytecode or a native executable. + +``` +val file_exists : string -> bool +``` +Test if a file with the given name exists. + +``` +val is_directory : string -> bool +``` +Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file. + +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. +since 3.10 +``` +val is_regular_file : string -> bool +``` +Returns `true` if the given name refers to a regular file, `false` if it refers to another kind of file. + +raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. +since 5.1 +``` +val remove : string -> unit +``` +Remove the given file name from the file system. + +``` +val rename : string -> string -> unit +``` +Rename a file or directory. `rename oldpath newpath` renames the file or directory called `oldpath`, giving it `newpath` as its new name, moving it between (parent) directories if needed. If a file named `newpath` already exists, its contents will be replaced with those of `oldpath`. Depending on the operating system, the metadata (permissions, owner, etc) of `newpath` can either be preserved or be replaced by those of `oldpath`. + +since 4.06 concerning the "replace existing file" behavior +``` +val getenv : string -> string +``` +Return the value associated to a variable in the process environment. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if the variable is unbound. +``` +val getenv_opt : string -> string option +``` +Return the value associated to a variable in the process environment or `None` if the variable is unbound. + +since 4.05 +``` +val command : string -> int +``` +Execute the given shell command and return its exit code. + +The argument of [`Sys.command`](./#val-command) is generally the name of a command followed by zero, one or several arguments, separated by whitespace. The given argument is interpreted by a shell: either the Windows shell `cmd.exe` for the Win32 ports of OCaml, or the POSIX shell `sh` for other ports. It can contain shell builtin commands such as `echo`, and also special characters such as file redirections `>` and `<`, which will be honored by the shell. + +Conversely, whitespace or special shell characters occurring in command names or in their arguments must be quoted or escaped so that the shell does not interpret them. The quoting rules vary between the POSIX shell and the Windows shell. The [`Filename.quote_command`](./Stdlib-Filename.md#val-quote_command) performs the appropriate quoting given a command name, a list of arguments, and optional file redirections. + +``` +val time : unit -> float +``` +Return the processor time, in seconds, used by the program since the beginning of execution. + +``` +val chdir : string -> unit +``` +Change the current working directory of the process. + +``` +val mkdir : string -> int -> unit +``` +Create a directory with the given permissions. + +since 4.12 +``` +val rmdir : string -> unit +``` +Remove an empty directory. + +since 4.12 +``` +val getcwd : unit -> string +``` +Return the current working directory of the process. + +``` +val readdir : string -> string array +``` +Return the names of all files present in the given directory. Names denoting the current directory and the parent directory (`"."` and `".."` in Unix) are not returned. Each string in the result is a file name rather than a complete path. There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order. + +``` +val interactive : bool ref +``` +This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`. + +alert unsynchronized\_access The interactive status is a mutable global state. +``` +val os_type : string +``` +Operating system currently executing the OCaml program. One of + +- `"Unix"` (for all Unix versions, including Linux and Mac OS X), +- `"Win32"` (for MS-Windows, OCaml compiled with MSVC++ or MinGW-w64), +- `"Cygwin"` (for MS-Windows, OCaml compiled with Cygwin). +``` +type backend_type = +``` +``` +| Native +``` +``` +| Bytecode +``` +``` +| Other of string +``` +``` + +``` +Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript. + +since 4.04 +``` +val backend_type : backend_type +``` +Backend type currently executing the OCaml program. + +since 4.04 +``` +val unix : bool +``` +True if `Sys.os_type = "Unix"`. + +since 4.01 +``` +val win32 : bool +``` +True if `Sys.os_type = "Win32"`. + +since 4.01 +``` +val cygwin : bool +``` +True if `Sys.os_type = "Cygwin"`. + +since 4.01 +``` +val word_size : int +``` +Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64. + +``` +val int_size : int +``` +Size of `int`, in bits. It is 31 (resp. 63) when using OCaml on a 32-bit (resp. 64-bit) platform. It may differ for other implementations, e.g. it can be 32 bits when compiling to JavaScript. + +since 4.03 +``` +val big_endian : bool +``` +Whether the machine currently executing the Caml program is big-endian. + +since 4.00 +``` +val max_string_length : int +``` +Maximum length of strings and byte sequences. + +``` +val max_array_length : int +``` +Maximum length of a normal array (i.e. any array whose elements are not of type `float`). The maximum length of a `float array` is `max_floatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with `--disable-flat-float-array`. + +``` +val max_floatarray_length : int +``` +Maximum length of a floatarray. This is also the maximum length of a `float array` when OCaml is configured with `--enable-flat-float-array`. + +``` +val runtime_variant : unit -> string +``` +Return the name of the runtime variant the program is running on. This is normally the argument given to `-runtime-variant` at compile time, but for byte-code it can be changed after compilation. + +since 4.03 +``` +val runtime_parameters : unit -> string +``` +Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable. + +since 4.03 + +## Signal handling + +``` +type signal_behavior = +``` +``` +| Signal_default +``` +``` +| Signal_ignore +``` +``` +| Signal_handle of int -> unit +``` +``` + +``` +What to do when receiving a signal: + +- `Signal_default`: take the default behavior (usually: abort the program) +- `Signal_ignore`: ignore the signal +- `Signal_handle f`: call function `f`, giving it the signal number as argument. +``` +val signal : int -> signal_behavior -> signal_behavior +``` +Set the behavior of the system on receipt of a given signal. The first argument is the signal number. Return the behavior previously associated with the signal. If the signal number is invalid (or not available on your system), an `Invalid_argument` exception is raised. + +``` +val set_signal : int -> signal_behavior -> unit +``` +Same as [`Sys.signal`](./#val-signal) but return value is ignored. + + +### Signal numbers for the standard POSIX signals. + +``` +val sigabrt : int +``` +Abnormal termination + +``` +val sigalrm : int +``` +Timeout + +``` +val sigfpe : int +``` +Arithmetic exception + +``` +val sighup : int +``` +Hangup on controlling terminal + +``` +val sigill : int +``` +Invalid hardware instruction + +``` +val sigint : int +``` +Interactive interrupt (ctrl-C) + +``` +val sigkill : int +``` +Termination (cannot be ignored) + +``` +val sigpipe : int +``` +Broken pipe + +``` +val sigquit : int +``` +Interactive termination + +``` +val sigsegv : int +``` +Invalid memory reference + +``` +val sigterm : int +``` +Termination + +``` +val sigusr1 : int +``` +Application-defined signal 1 + +``` +val sigusr2 : int +``` +Application-defined signal 2 + +``` +val sigchld : int +``` +Child process terminated + +``` +val sigcont : int +``` +Continue + +``` +val sigstop : int +``` +Stop + +``` +val sigtstp : int +``` +Interactive stop + +``` +val sigttin : int +``` +Terminal read from background process + +``` +val sigttou : int +``` +Terminal write from background process + +``` +val sigvtalrm : int +``` +Timeout in virtual time + +``` +val sigprof : int +``` +Profiling interrupt + +``` +val sigbus : int +``` +Bus error + +since 4.03 +``` +val sigpoll : int +``` +Pollable event + +since 4.03 +``` +val sigsys : int +``` +Bad argument to routine + +since 4.03 +``` +val sigtrap : int +``` +Trace/breakpoint trap + +since 4.03 +``` +val sigurg : int +``` +Urgent condition on socket + +since 4.03 +``` +val sigxcpu : int +``` +Timeout in cpu time + +since 4.03 +``` +val sigxfsz : int +``` +File size limit exceeded + +since 4.03 +``` +exception Break +``` +Exception raised on interactive interrupt if [`Sys.catch_break`](./#val-catch_break) is enabled. + +``` +val catch_break : bool -> unit +``` +`catch_break` governs whether interactive interrupt (ctrl-C) terminates the program or raises the `Break` exception. Call `catch_break true` to enable raising `Break`, and `catch_break false` to let the system terminate the program on user interrupt. + +Inside multi-threaded programs, the `Break` exception will arise in any one of the active threads, and will keep arising on further interactive interrupt until all threads are terminated. Use signal masks from `Thread.sigmask` to direct the interrupt towards a specific thread. + +``` +val ocaml_version : string +``` +`ocaml_version` is the version of OCaml. It is a string of the form `"major.minor[.patchlevel][(+|~)additional-info]"`, where `major`, `minor`, and `patchlevel` are integers, and `additional-info` is an arbitrary string. The `[.patchlevel]` part was absent before version 3.08.0 and became mandatory from 3.08.0 onwards. The `[(+|~)additional-info]` part may be absent. + +``` +val development_version : bool +``` +`true` if this is a development version, `false` otherwise. + +since 4.14 +``` +type extra_prefix = +``` +``` +| Plus +``` +``` +| Tilde +``` +since 4.14 +``` + +``` +``` +type extra_info = extra_prefix * string +``` +since 4.14 +``` +type ocaml_release_info = { +``` +`major : int;` +`minor : int;` +`patchlevel : int;` +`extra : extra_info option;` +``` +} +``` +since 4.14 +``` +val ocaml_release : ocaml_release_info +``` +`ocaml_release` is the version of OCaml. + +since 4.14 +``` +val enable_runtime_warnings : bool -> unit +``` +Control whether the OCaml runtime system can emit warnings on stderr. Currently, the only supported warning is triggered when a channel created by `open_*` functions is finalized without being closed. Runtime warnings are disabled by default. + +since 4.03 +alert unsynchronized\_access The status of runtime warnings is a mutable global state. +``` +val runtime_warnings_enabled : unit -> bool +``` +Return whether runtime warnings are currently enabled. + +since 4.03 +alert unsynchronized\_access The status of runtime warnings is a mutable global state. + +## Optimization + +``` +val opaque_identity : 'a -> 'a +``` +For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function. + +At runtime, `opaque_identity` disappears altogether. However, it does prevent the argument from being garbage collected until the location where the call would have occurred. + +A typical use of this function is to prevent pure computations from being optimized away in benchmarking loops. For example: + +```ocaml + for _round = 1 to 100_000 do + ignore (Sys.opaque_identity (my_pure_computation ())) + done +``` +since 4.03 +``` +module Immediate64 : sig ... end +``` +This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. diff --git a/docs/api/re/melange/Stdlib-Type-Id.md b/docs/api/re/melange/Stdlib-Type-Id.md new file mode 100644 index 000000000..39402a663 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Type-Id.md @@ -0,0 +1,80 @@ + +# Module `Type.Id` + +Type identifiers. + +A type identifier is a value that denotes a type. Given two type identifiers, they can be tested for [equality](./#val-provably_equal) to prove they denote the same type. Note that: + +- Unequal identifiers do not imply unequal types: a given type can be denoted by more than one identifier. +- Type identifiers can be marshalled, but they get a new, distinct, identity on unmarshalling, so the equalities are lost. +See an [example](./#example) of use. + + +## Type identifiers + +``` +type !'a t +``` +The type for identifiers for type `'a`. + +``` +val make : unit -> 'a t +``` +`make ()` is a new type identifier. + +``` +val uid : 'a t -> int +``` +`uid id` is a runtime unique identifier for `id`. + +``` +val provably_equal : 'a t -> 'b t -> ('a, 'b) eq option +``` +`provably_equal i0 i1` is `Some Equal` if identifier `i0` is equal to `i1` and `None` otherwise. + + +## Example + +The following shows how type identifiers can be used to implement a simple heterogeneous key-value dictionary. In contrast to [`Stdlib.Map`](./Stdlib-Map.md) values whose keys map to a single, homogeneous type of values, this dictionary can associate a different type of value to each key. + +```ocaml +(** Heterogeneous dictionaries. *) +module Dict : sig + type t + (** The type for dictionaries. *) + + type 'a key + (** The type for keys binding values of type ['a]. *) + + val key : unit -> 'a key + (** [key ()] is a new dictionary key. *) + + val empty : t + (** [empty] is the empty dictionary. *) + + val add : 'a key -> 'a -> t -> t + (** [add k v d] is [d] with [k] bound to [v]. *) + + val remove : 'a key -> t -> t + (** [remove k d] is [d] with the last binding of [k] removed. *) + + val find : 'a key -> t -> 'a option + (** [find k d] is the binding of [k] in [d], if any. *) +end = struct + type 'a key = 'a Type.Id.t + type binding = B : 'a key * 'a -> binding + type t = (int * binding) list + + let key () = Type.Id.make () + let empty = [] + let add k v d = (Type.Id.uid k, B (k, v)) :: d + let remove k d = List.remove_assoc (Type.Id.uid k) d + let find : type a. a key -> t -> a option = fun k d -> + match List.assoc_opt (Type.Id.uid k) d with + | None -> None + | Some (B (k', v)) -> + match Type.Id.provably_equal k k' with + | Some Type.Equal -> Some v + | None -> assert false +end +``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Type.md b/docs/api/re/melange/Stdlib-Type.md new file mode 100644 index 000000000..0a071fda8 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Type.md @@ -0,0 +1,36 @@ + +# Module `Stdlib.Type` + +Type introspection. + +since 5.1 + +## Type equality witness + +``` +type (_, _) eq = +``` +``` +| Equal : ('a, 'a) eq +``` +``` + +``` +The purpose of `eq` is to represent type equalities that may not otherwise be known by the type checker (e.g. because they may depend on dynamic data). + +A value of type `(a, b) eq` represents the fact that types `a` and `b` are equal. + +If one has a value `eq : (a, b) eq` that proves types `a` and `b` are equal, one can use it to convert a value of type `a` to a value of type `b` by pattern matching on `Equal`: + +```ocaml + let cast (type a) (type b) (Equal : (a, b) Type.eq) (a : a) : b = a +``` +At runtime, this function simply returns its second argument unchanged. + + +## Type identifiers + +``` +module Id : sig ... end +``` +Type identifiers. diff --git a/docs/api/re/melange/Stdlib-Uchar.md b/docs/api/re/melange/Stdlib-Uchar.md new file mode 100644 index 000000000..a90cfee5e --- /dev/null +++ b/docs/api/re/melange/Stdlib-Uchar.md @@ -0,0 +1,144 @@ + +# Module `Stdlib.Uchar` + +Unicode characters. + +since 4.03 +``` +type t +``` +The type for Unicode characters. + +A value of this type represents a Unicode [scalar value](http://unicode.org/glossary/#unicode_scalar_value) which is an integer in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`. + +``` +val min : t +``` +`min` is U+0000. + +``` +val max : t +``` +`max` is U+10FFFF. + +``` +val bom : t +``` +`bom` is U+FEFF, the [byte order mark](http://unicode.org/glossary/#byte_order_mark) (BOM) character. + +since 4.06 +``` +val rep : t +``` +`rep` is U+FFFD, the [replacement](http://unicode.org/glossary/#replacement_character) character. + +since 4.06 +``` +val succ : t -> t +``` +`succ u` is the scalar value after `u` in the set of Unicode scalar values. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is max. +``` +val pred : t -> t +``` +`pred u` is the scalar value before `u` in the set of Unicode scalar values. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is min. +``` +val is_valid : int -> bool +``` +`is_valid n` is `true` if and only if `n` is a Unicode scalar value (i.e. in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`). + +``` +val of_int : int -> t +``` +`of_int i` is `i` as a Unicode character. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i does not satisfy is\_valid. +``` +val to_int : t -> int +``` +`to_int u` is `u` as an integer. + +``` +val is_char : t -> bool +``` +`is_char u` is `true` if and only if `u` is a latin1 OCaml character. + +``` +val of_char : char -> t +``` +`of_char c` is `c` as a Unicode character. + +``` +val to_char : t -> char +``` +`to_char u` is `u` as an OCaml latin1 character. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u does not satisfy is\_char. +``` +val equal : t -> t -> bool +``` +`equal u u'` is `u = u'`. + +``` +val compare : t -> t -> int +``` +`compare u u'` is `Stdlib.compare u u'`. + +``` +val seeded_hash : int -> t -> int +``` +`seeded_hash seed u` A seeded hash function with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). + +since 5.3 +``` +val hash : t -> int +``` +An unseeded hash function with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). + +since 5.3 + +## UTF codecs tools + +since 4.14 +``` +type utf_decode +``` +The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt. + +``` +val utf_decode_is_valid : utf_decode -> bool +``` +`utf_decode_is_valid d` is `true` if and only if `d` holds a valid decode. + +``` +val utf_decode_uchar : utf_decode -> t +``` +`utf_decode_uchar d` is the Unicode character decoded by `d` if `utf_decode_is_valid d` is `true` and [`Uchar.rep`](./#val-rep) otherwise. + +``` +val utf_decode_length : utf_decode -> int +``` +`utf_decode_length d` is the number of elements from the source that were consumed by the decode `d`. This is always strictly positive and smaller or equal to `4`. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes. + +``` +val utf_decode : int -> t -> utf_decode +``` +`utf_decode n u` is a valid UTF decode for `u` that consumed `n` elements from the source for decoding. `n` must be positive and smaller or equal to `4` (this is not checked by the module). + +``` +val utf_decode_invalid : int -> utf_decode +``` +`utf_decode_invalid n` is an invalid UTF decode that consumed `n` elements from the source to error. `n` must be positive and smaller or equal to `4` (this is not checked by the module). The resulting decode has [`rep`](./#val-rep) as the decoded Unicode character. + +``` +val utf_8_byte_length : t -> int +``` +`utf_8_byte_length u` is the number of bytes needed to encode `u` in UTF-8. + +``` +val utf_16_byte_length : t -> int +``` +`utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16. diff --git a/docs/api/re/melange/Stdlib-Unit.md b/docs/api/re/melange/Stdlib-Unit.md new file mode 100644 index 000000000..50428889e --- /dev/null +++ b/docs/api/re/melange/Stdlib-Unit.md @@ -0,0 +1,36 @@ + +# Module `Stdlib.Unit` + +Unit values. + +since 4.08 + +## The unit type + +``` +type t = unit = +``` +``` +| () +``` +``` + +``` +The unit type. + +The constructor `()` is included here so that it has a path, but it is not intended to be used in user-defined data types. + +``` +val equal : t -> t -> bool +``` +`equal u1 u2` is `true`. + +``` +val compare : t -> t -> int +``` +`compare u1 u2` is `0`. + +``` +val to_string : t -> string +``` +`to_string b` is `"()"`. diff --git a/docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md b/docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md new file mode 100644 index 000000000..80efdc53c --- /dev/null +++ b/docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md @@ -0,0 +1,21 @@ + +# Parameter `Make.H` + +``` +type t +``` +The type of the hashtable keys. + +``` +val equal : t -> t -> bool +``` +The equality predicate used to compare keys. + +``` +val hash : t -> int +``` +A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include + +- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) +- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly +- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Weak-Make.md b/docs/api/re/melange/Stdlib-Weak-Make.md new file mode 100644 index 000000000..a9786f098 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Weak-Make.md @@ -0,0 +1,90 @@ + +# Module `Weak.Make` + +Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. + + +## Parameters + +``` +module H : Hashtbl.HashedType +``` + +## Signature + +``` +type data = H.t +``` +The type of the elements stored in the table. + +``` +type t +``` +The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. + +``` +val create : int -> t +``` +`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. + +``` +val clear : t -> unit +``` +Remove all elements from the table. + +``` +val merge : t -> data -> data +``` +`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. + +``` +val add : t -> data -> unit +``` +`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. + +``` +val remove : t -> data -> unit +``` +`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. + +``` +val find : t -> data -> data +``` +`find t x` returns an instance of `x` found in `t`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. +``` +val find_opt : t -> data -> data option +``` +`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. + +since 4.05 +``` +val find_all : t -> data -> data list +``` +`find_all t x` returns a list of all the instances of `x` found in `t`. + +``` +val mem : t -> data -> bool +``` +`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. + +``` +val iter : (data -> unit) -> t -> unit +``` +`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + +``` +val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + +``` +val count : t -> int +``` +Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. + +``` +val stats : t -> int * int * int * int * int * int +``` +Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/re/melange/Stdlib-Weak-module-type-S.md b/docs/api/re/melange/Stdlib-Weak-module-type-S.md new file mode 100644 index 000000000..22f814459 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Weak-module-type-S.md @@ -0,0 +1,81 @@ + +# Module type `Weak.S` + +The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). + +``` +type data +``` +The type of the elements stored in the table. + +``` +type t +``` +The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. + +``` +val create : int -> t +``` +`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. + +``` +val clear : t -> unit +``` +Remove all elements from the table. + +``` +val merge : t -> data -> data +``` +`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. + +``` +val add : t -> data -> unit +``` +`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. + +``` +val remove : t -> data -> unit +``` +`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. + +``` +val find : t -> data -> data +``` +`find t x` returns an instance of `x` found in `t`. + +raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. +``` +val find_opt : t -> data -> data option +``` +`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. + +since 4.05 +``` +val find_all : t -> data -> data list +``` +`find_all t x` returns a list of all the instances of `x` found in `t`. + +``` +val mem : t -> data -> bool +``` +`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. + +``` +val iter : (data -> unit) -> t -> unit +``` +`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + +``` +val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc +``` +`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. + +``` +val count : t -> int +``` +Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. + +``` +val stats : t -> int * int * int * int * int * int +``` +Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/re/melange/Stdlib-Weak.md b/docs/api/re/melange/Stdlib-Weak.md new file mode 100644 index 000000000..98afcfae4 --- /dev/null +++ b/docs/api/re/melange/Stdlib-Weak.md @@ -0,0 +1,88 @@ + +# Module `Stdlib.Weak` + +Arrays of weak pointers and hash sets of weak pointers. + + +## Low-level functions + +``` +type !'a t +``` +The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program. Note that finalisation functions are run before the weak pointers are erased, because the finalisation functions can make values alive again (before 4.03 the finalisation functions were run after). + +A weak pointer is said to be full if it points to a value, empty if the value was erased by the GC. + +Notes: + +- Integers are not allocated and cannot be stored in weak arrays. +- Weak arrays cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) nor the functions of the [`Marshal`](./Stdlib-Marshal.md) module. +``` +val create : int -> 'a t +``` +`Weak.create n` returns a new weak array of length `n`. All the pointers are initially empty. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not comprised between zero and Obj.Ephemeron.max\_ephe\_length (limits included). +``` +val length : 'a t -> int +``` +`Weak.length ar` returns the length (number of elements) of `ar`. + +``` +val set : 'a t -> int -> 'a option -> unit +``` +`Weak.set ar n (Some el)` sets the `n`th cell of `ar` to be a (full) pointer to `el`; `Weak.set ar n None` sets the `n`th cell of `ar` to empty. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +``` +val get : 'a t -> int -> 'a option +``` +`Weak.get ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is the value) if it is full. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +``` +val get_copy : 'a t -> int -> 'a option +``` +`Weak.get_copy ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is a (shallow) copy of the value) if it is full. In addition to pitfalls with mutable values, the interesting difference with `get` is that `get_copy` does not prevent the incremental GC from erasing the value in its current cycle (`get` may delay the erasure to the next GC cycle). + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +If the element is a custom block it is not copied. + +``` +val check : 'a t -> int -> bool +``` +`Weak.check ar n` returns `true` if the `n`th cell of `ar` is full, `false` if it is empty. Note that even if `Weak.check ar n` returns `true`, a subsequent [`Weak.get`](./#val-get)` ar n` can return `None`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. +``` +val fill : 'a t -> int -> int -> 'a option -> unit +``` +`Weak.fill ar ofs len el` sets to `el` all pointers of `ar` from `ofs` to `ofs + len - 1`. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid subarray of ar. +``` +val blit : 'a t -> int -> 'a t -> int -> int -> unit +``` +`Weak.blit ar1 off1 ar2 off2 len` copies `len` weak pointers from `ar1` (starting at `off1`) to `ar2` (starting at `off2`). It works correctly even if `ar1` and `ar2` are the same. + +raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off1 and len do not designate a valid subarray of ar1, or if off2 and len do not designate a valid subarray of ar2. + +## Weak hash sets + +A weak hash set is a hashed set of values. Each value may magically disappear from the set when it is not used by the rest of the program any more. This is normally used to share data structures without inducing memory leaks. Weak hash sets are defined on values from a [`Hashtbl.HashedType`](./Stdlib-Hashtbl-module-type-HashedType.md) module; the `equal` relation and `hash` function are taken from that module. We will say that `v` is an instance of `x` if `equal x v` is `true`. + +The `equal` relation must be able to work on a shallow copy of the values and give the same result as with the values themselves. + +**Unsynchronized accesses** + +Unsynchronized accesses to weak hash sets are a programming error. Unsynchronized accesses to a weak hash set may lead to an invalid weak hash set state. Thus, concurrent accesses to weak hash sets must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). + +``` +module type S = sig ... end +``` +The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). + +``` +module Make (H : Hashtbl.HashedType) : S with type data = H.t +``` +Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. diff --git a/docs/api/re/melange/Stdlib.md b/docs/api/re/melange/Stdlib.md new file mode 100644 index 000000000..ba13a16e8 --- /dev/null +++ b/docs/api/re/melange/Stdlib.md @@ -0,0 +1,1565 @@ + +# Module `Stdlib` + +The OCaml Standard library. + +This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by `Stdlib`. + +In particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the [standard library modules](./#modules). + + +## Exceptions + +``` +val raise : exn -> 'a +``` +Raise the given exception value + +``` +val raise_notrace : exn -> 'a +``` +A faster version `raise` which does not record the backtrace. + +since 4.02 +``` +val invalid_arg : string -> 'a +``` +Raise exception `Invalid_argument` with the given string. + +``` +val failwith : string -> 'a +``` +Raise exception `Failure` with the given string. + +``` +exception Exit +``` +The `Exit` exception is not raised by any library function. It is provided for use in your programs. + +``` +exception Match_failure of string * int * int +``` +Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number). + +``` +exception Assert_failure of string * int * int +``` +Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number). + +``` +exception Invalid_argument of string +``` +Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it. + +``` +exception Failure of string +``` +Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure \_ instead). + +``` +exception Not_found +``` +Exception raised by search functions when the desired object could not be found. + +``` +exception Out_of_memory +``` +Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.) + +``` +exception Stack_overflow +``` +Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program. + +Before 4.10, it was not fully implemented by the native-code compiler. + +``` +exception Sys_error of string +``` +Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys\_error \_ instead). + +``` +exception End_of_file +``` +Exception raised by input functions to signal that the end of file has been reached. + +``` +exception Division_by_zero +``` +Exception raised by integer division and remainder operations when their second argument is zero. + +``` +exception Sys_blocked_io +``` +A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel. + +``` +exception Undefined_recursive_module of string * int * int +``` +Exception raised when an ill-founded recursive module definition is evaluated. The arguments are the location of the definition in the source code (file name, line number, column number). + + +## Comparisons + +``` +val (=) : 'a -> 'a -> bool +``` +`e1 = e2` tests for structural equality of `e1` and `e2`. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises `Invalid_argument`. Equality between cyclic data structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (<>) : 'a -> 'a -> bool +``` +Negation of [`Stdlib.(=)`](./#val-\(=\)). Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (<) : 'a -> 'a -> bool +``` +See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (>) : 'a -> 'a -> bool +``` +See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (<=) : 'a -> 'a -> bool +``` +See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (>=) : 'a -> 'a -> bool +``` +Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with `( = )`. As in the case of `( = )`, mutable structures are compared by contents. Comparison between functional values raises `Invalid_argument`. Comparison between cyclic structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val compare : 'a -> 'a -> int +``` +`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. The ordering implemented by `compare` is compatible with the comparison predicates `=`, `<` and `>` defined above, with one difference on the treatment of the float value [`Stdlib.nan`](./#val-nan). Namely, the comparison predicates treat `nan` as different from any other float value, including itself; while `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. + +`compare` applied to functional values may raise `Invalid_argument`. `compare` applied to cyclic structures may not terminate. + +The `compare` function can be used as the comparison function required by the [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md) functors, as well as the [`List.sort`](./Stdlib-List.md#val-sort) and [`Array.sort`](./Stdlib-Array.md#val-sort) functions. + +``` +val min : 'a -> 'a -> 'a +``` +``` +val max : 'a -> 'a -> 'a +``` +``` +val (==) : 'a -> 'a -> bool +``` +`e1 == e2` tests for physical equality of `e1` and `e2`. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, `e1 == e2` is true if and only if physical modification of `e1` also affects `e2`. On non-mutable types, the behavior of `( == )` is implementation-dependent; however, it is guaranteed that `e1 == e2` implies `compare e1 e2 = 0`. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (!=) : 'a -> 'a -> bool +``` +Negation of [`Stdlib.(==)`](./#val-\(==\)). Left-associative operator, see `Ocaml_operators` for more information. + + +## Boolean operations + +``` +val not : bool -> bool +``` +The boolean negation. + +``` +val (&&) : bool -> bool -> bool +``` +The boolean 'and'. Evaluation is sequential, left-to-right: in `e1 && e2`, `e1` is evaluated first, and if it returns `false`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. + +``` +val (||) : bool -> bool -> bool +``` +The boolean 'or'. Evaluation is sequential, left-to-right: in `e1 || e2`, `e1` is evaluated first, and if it returns `true`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. + + +## Debugging + +``` +val __LOC__ : string +``` +`__LOC__` returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". + +since 4.02 +``` +val __FILE__ : string +``` +`__FILE__` returns the name of the file currently being parsed by the compiler. + +since 4.02 +``` +val __LINE__ : int +``` +`__LINE__` returns the line number at which this expression appears in the file currently being parsed by the compiler. + +since 4.02 +``` +val __MODULE__ : string +``` +`__MODULE__` returns the module name of the file being parsed by the compiler. + +since 4.02 +``` +val __POS__ : string * int * int * int +``` +`__POS__` returns a tuple `(file,lnum,cnum,enum)`, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. + +since 4.02 +``` +val __FUNCTION__ : string +``` +`__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes. + +since 4.12 +``` +val __LOC_OF__ : 'a -> string * 'a +``` +`__LOC_OF__ expr` returns a pair `(loc, expr)` where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". + +since 4.02 +``` +val __LINE_OF__ : 'a -> int * 'a +``` +`__LINE_OF__ expr` returns a pair `(line, expr)`, where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler. + +since 4.02 +``` +val __POS_OF__ : 'a -> (string * int * int * int) * 'a +``` +`__POS_OF__ expr` returns a pair `(loc,expr)`, where `loc` is a tuple `(file,lnum,cnum,enum)` corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. + +since 4.02 + +## Composition operators + +``` +val (|>) : 'a -> ('a -> 'b) -> 'b +``` +Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. Left-associative operator, see `Ocaml_operators` for more information. + +since 4.01 +``` +val (@@) : ('a -> 'b) -> 'a -> 'b +``` +Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. Right-associative operator, see `Ocaml_operators` for more information. + +since 4.01 + +## Integer arithmetic + +Integers are `Sys.int_size` bits wide. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. + +``` +val (~-) : int -> int +``` +Unary negation. You can also write `- e` instead of `~- e`. Unary operator, see `Ocaml_operators` for more information. + +``` +val (~+) : int -> int +``` +Unary addition. You can also write `+ e` instead of `~+ e`. Unary operator, see `Ocaml_operators` for more information. + +since 3.12 +``` +val succ : int -> int +``` +`succ x` is `x + 1`. + +``` +val pred : int -> int +``` +`pred x` is `x - 1`. + +``` +val (+) : int -> int -> int +``` +Integer addition. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (-) : int -> int -> int +``` +Integer subtraction. Left-associative operator, , see `Ocaml_operators` for more information. + +``` +val (*) : int -> int -> int +``` +Integer multiplication. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (/) : int -> int -> int +``` +Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if `x >= 0` and `y > 0`, `x / y` is the greatest integer less than or equal to the real quotient of `x` by `y`. Moreover, `(- x) / y = x / (- y) = - (x / y)`. Left-associative operator, see `Ocaml_operators` for more information. + +raises [`Division_by_zero`](./#exception-Division_by_zero) if the second argument is 0. +``` +val (mod) : int -> int -> int +``` +Integer remainder. If `y` is not zero, the result of `x mod y` satisfies the following properties: `x = (x / y) * y + x mod y` and `abs(x mod y) <= abs(y) - 1`. If `y = 0`, `x mod y` raises `Division_by_zero`. Note that `x mod y` is negative only if `x < 0`. Left-associative operator, see `Ocaml_operators` for more information. + +raises [`Division_by_zero`](./#exception-Division_by_zero) if y is zero. +``` +val abs : int -> int +``` +`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. + +``` +val max_int : int +``` +The greatest representable integer. + +``` +val min_int : int +``` +The smallest representable integer. + + +### Bitwise operations + +``` +val (land) : int -> int -> int +``` +Bitwise logical and. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (lor) : int -> int -> int +``` +Bitwise logical or. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (lxor) : int -> int -> int +``` +Bitwise logical exclusive or. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val lnot : int -> int +``` +Bitwise logical negation. + +``` +val (lsl) : int -> int -> int +``` +`n lsl m` shifts `n` to the left by `m` bits. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. + +``` +val (lsr) : int -> int -> int +``` +`n lsr m` shifts `n` to the right by `m` bits. This is a logical shift: zeroes are inserted regardless of the sign of `n`. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. + +``` +val (asr) : int -> int -> int +``` +`n asr m` shifts `n` to the right by `m` bits. This is an arithmetic shift: the sign bit of `n` is replicated. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. + + +## Floating-point arithmetic + +OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... + +``` +val (~-.) : float -> float +``` +Unary negation. You can also write `-. e` instead of `~-. e`. Unary operator, see `Ocaml_operators` for more information. + +``` +val (~+.) : float -> float +``` +Unary addition. You can also write `+. e` instead of `~+. e`. Unary operator, see `Ocaml_operators` for more information. + +since 3.12 +``` +val (+.) : float -> float -> float +``` +Floating-point addition. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (-.) : float -> float -> float +``` +Floating-point subtraction. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (*.) : float -> float -> float +``` +Floating-point multiplication. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (/.) : float -> float -> float +``` +Floating-point division. Left-associative operator, see `Ocaml_operators` for more information. + +``` +val (**) : float -> float -> float +``` +Exponentiation. + +``` +val sqrt : float -> float +``` +Square root. + +``` +val exp : float -> float +``` +Exponential. + +``` +val log : float -> float +``` +Natural logarithm. + +``` +val log10 : float -> float +``` +Base 10 logarithm. + +``` +val expm1 : float -> float +``` +`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. + +since 3.12.0 +``` +val log1p : float -> float +``` +`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. + +since 3.12.0 +``` +val cos : float -> float +``` +Cosine. Argument is in radians. + +``` +val sin : float -> float +``` +Sine. Argument is in radians. + +``` +val tan : float -> float +``` +Tangent. Argument is in radians. + +``` +val acos : float -> float +``` +Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. + +``` +val asin : float -> float +``` +Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. + +``` +val atan : float -> float +``` +Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. + +``` +val atan2 : float -> float -> float +``` +`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. + +``` +val hypot : float -> float -> float +``` +`hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. + +since 4.00.0 +``` +val cosh : float -> float +``` +Hyperbolic cosine. Argument is in radians. + +``` +val sinh : float -> float +``` +Hyperbolic sine. Argument is in radians. + +``` +val tanh : float -> float +``` +Hyperbolic tangent. Argument is in radians. + +``` +val acosh : float -> float +``` +Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. + +since 4.13.0 +``` +val asinh : float -> float +``` +Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. + +since 4.13.0 +``` +val atanh : float -> float +``` +Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. + +since 4.13.0 +``` +val ceil : float -> float +``` +Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. + +``` +val floor : float -> float +``` +Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. + +``` +val abs_float : float -> float +``` +`abs_float f` returns the absolute value of `f`. + +``` +val copysign : float -> float -> float +``` +`copysign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. + +since 4.00 +``` +val mod_float : float -> float -> float +``` +`mod_float a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. + +``` +val frexp : float -> float * int +``` +`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. + +``` +val ldexp : float -> int -> float +``` +`ldexp x n` returns `x *. 2 ** n`. + +``` +val modf : float -> float * float +``` +`modf f` returns the pair of the fractional and integral part of `f`. + +``` +val float : int -> float +``` +Same as [`Stdlib.float_of_int`](./#val-float_of_int). + +``` +val float_of_int : int -> float +``` +Convert an integer to floating-point. + +``` +val truncate : float -> int +``` +Same as [`Stdlib.int_of_float`](./#val-int_of_float). + +``` +val int_of_float : float -> int +``` +Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. + +``` +val infinity : float +``` +Positive infinity. + +``` +val neg_infinity : float +``` +Negative infinity. + +``` +val nan : float +``` +``` +val max_float : float +``` +The largest positive finite value of type `float`. + +``` +val min_float : float +``` +The smallest positive, non-zero, non-denormalized value of type `float`. + +``` +val epsilon_float : float +``` +The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. + +``` +type fpclass = +``` +``` +| FP_normal +``` +Normal number, none of the below + +``` +| FP_subnormal +``` +Number very close to 0.0, has reduced precision + +``` +| FP_zero +``` +Number is 0.0 or \-0.0 + +``` +| FP_infinite +``` +Number is positive or negative infinity + +``` +| FP_nan +``` +Not a number: result of an undefined operation + +``` + +``` +The five classes of floating-point numbers, as determined by the [`Stdlib.classify_float`](./#val-classify_float) function. + +``` +val classify_float : float -> fpclass +``` + +## String operations + +More string operations are provided in module [`String`](./Stdlib-String.md). + +``` +val (^) : string -> string -> string +``` +String concatenation. Right-associative operator, see `Ocaml_operators` for more information. + +raises [`Invalid_argument`](./#exception-Invalid_argument) if the result is longer then than Sys.max\_string\_length bytes. + +## Character operations + +More character operations are provided in module [`Char`](./Stdlib-Char.md). + +``` +val int_of_char : char -> int +``` +Return the ASCII code of the argument. + +``` +val char_of_int : int -> char +``` +Return the character with the given ASCII code. + +raises [`Invalid_argument`](./#exception-Invalid_argument) if the argument is outside the range 0--255. + +## Unit operations + +``` +val ignore : 'a -> unit +``` +Discard the value of its argument and return `()`. For instance, `ignore(f x)` discards the result of the side-effecting function `f`. It is equivalent to `f x; ()`, except that the latter may generate a compiler warning; writing `ignore(f x)` instead avoids the warning. + + +## String conversion functions + +``` +val string_of_bool : bool -> string +``` +Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly. + +``` +val bool_of_string_opt : string -> bool option +``` +Convert the given string to a boolean. + +Return `None` if the string is not `"true"` or `"false"`. + +since 4.05 +``` +val bool_of_string : string -> bool +``` +Same as [`Stdlib.bool_of_string_opt`](./#val-bool_of_string_opt), but raise `Invalid_argument "bool_of_string"` instead of returning `None`. + +``` +val string_of_int : int -> string +``` +Return the string representation of an integer, in decimal. + +``` +val int_of_string_opt : string -> int option +``` +Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with `0u`), in hexadecimal (if it begins with `0x` or `0X`), in octal (if it begins with `0o` or `0O`), or in binary (if it begins with `0b` or `0B`). + +The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*max_int+1]`. If the input exceeds [`max_int`](./#val-max_int) it is converted to the signed integer `min_int + input - max_int - 1`. + +The `_` (underscore) character can appear anywhere in the string and is ignored. + +Return `None` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int`. + +since 4.05 +``` +val int_of_string : string -> int +``` +Same as [`Stdlib.int_of_string_opt`](./#val-int_of_string_opt), but raise `Failure "int_of_string"` instead of returning `None`. + +``` +val string_of_float : float -> string +``` +Return a string representation of a floating-point number. + +This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). + +``` +val float_of_string_opt : string -> float option +``` +Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). + +The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. + +The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. + +In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. + +The `_` (underscore) character can appear anywhere in the string and is ignored. + +Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. + +Return `None` if the given string is not a valid representation of a float. + +since 4.05 +``` +val float_of_string : string -> float +``` +Same as [`Stdlib.float_of_string_opt`](./#val-float_of_string_opt), but raise `Failure "float_of_string"` instead of returning `None`. + + +## Pair operations + +``` +val fst : ('a * 'b) -> 'a +``` +Return the first component of a pair. + +``` +val snd : ('a * 'b) -> 'b +``` +Return the second component of a pair. + + +## List operations + +More list operations are provided in module [`List`](./Stdlib-List.md). + +``` +val (@) : 'a list -> 'a list -> 'a list +``` +`l0 @ l1` appends `l1` to `l0`. Same function as [`List.append`](./Stdlib-List.md#val-append). Right-associative operator, see `Ocaml_operators` for more information. + +since 5.1 this function is tail-recursive. + +## Input/output + +Note: all input/output functions can raise `Sys_error` when the system calls they invoke fail. + +``` +type in_channel +``` +The type of input channel. + +``` +type out_channel +``` +The type of output channel. + +``` +val stdin : in_channel +``` +The standard input for the process. + +``` +val stdout : out_channel +``` +The standard output for the process. + +``` +val stderr : out_channel +``` +The standard error output for the process. + + +### Output functions on standard output + +``` +val print_char : char -> unit +``` +Print a character on standard output. + +``` +val print_string : string -> unit +``` +Print a string on standard output. + +``` +val print_bytes : bytes -> unit +``` +Print a byte sequence on standard output. + +since 4.02 +``` +val print_int : int -> unit +``` +Print an integer, in decimal, on standard output. + +``` +val print_float : float -> unit +``` +Print a floating-point number, in decimal, on standard output. + +The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. + +``` +val print_endline : string -> unit +``` +Print a string, followed by a newline character, on standard output and flush standard output. + +``` +val print_newline : unit -> unit +``` +Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. + + +### Output functions on standard error + +``` +val prerr_char : char -> unit +``` +Print a character on standard error. + +``` +val prerr_string : string -> unit +``` +Print a string on standard error. + +``` +val prerr_bytes : bytes -> unit +``` +Print a byte sequence on standard error. + +since 4.02 +``` +val prerr_int : int -> unit +``` +Print an integer, in decimal, on standard error. + +``` +val prerr_float : float -> unit +``` +Print a floating-point number, in decimal, on standard error. + +The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. + +``` +val prerr_endline : string -> unit +``` +Print a string, followed by a newline character on standard error and flush standard error. + +``` +val prerr_newline : unit -> unit +``` +Print a newline character on standard error, and flush standard error. + + +### Input functions on standard input + +``` +val read_line : unit -> string +``` +Flush standard output, then read characters from standard input until a newline character is encountered. + +Return the string of all characters read, without the newline character at the end. + +raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. +``` +val read_int_opt : unit -> int option +``` +Flush standard output, then read one line from standard input and convert it to an integer. + +Return `None` if the line read is not a valid representation of an integer. + +since 4.05 +``` +val read_int : unit -> int +``` +Same as [`Stdlib.read_int_opt`](./#val-read_int_opt), but raise `Failure "int_of_string"` instead of returning `None`. + +``` +val read_float_opt : unit -> float option +``` +Flush standard output, then read one line from standard input and convert it to a floating-point number. + +Return `None` if the line read is not a valid representation of a floating-point number. + +since 4.05 +``` +val read_float : unit -> float +``` +Same as [`Stdlib.read_float_opt`](./#val-read_float_opt), but raise `Failure "float_of_string"` instead of returning `None`. + + +### General output functions + +``` +type open_flag = +``` +``` +| Open_rdonly +``` +open for reading. + +``` +| Open_wronly +``` +open for writing. + +``` +| Open_append +``` +open for appending: always write at end of file. + +``` +| Open_creat +``` +create the file if it does not exist. + +``` +| Open_trunc +``` +empty the file if it already exists. + +``` +| Open_excl +``` +fail if Open\_creat and the file already exists. + +``` +| Open_binary +``` +open in binary mode (no conversion). + +``` +| Open_text +``` +open in text mode (may perform conversions). + +``` +| Open_nonblock +``` +open in non-blocking mode. + +``` + +``` +Opening modes for [`Stdlib.open_out_gen`](./#val-open_out_gen) and [`Stdlib.open_in_gen`](./#val-open_in_gen). + +``` +val open_out : string -> out_channel +``` +Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. + +``` +val open_out_bin : string -> out_channel +``` +Same as [`Stdlib.open_out`](./#val-open_out), but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_out`](./#val-open_out). + +``` +val open_out_gen : open_flag list -> int -> string -> out_channel +``` +`open_out_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`Stdlib.open_out`](./#val-open_out) and [`Stdlib.open_out_bin`](./#val-open_out_bin) are special cases of this function. + +``` +val flush : out_channel -> unit +``` +Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. + +``` +val flush_all : unit -> unit +``` +Flush all open output channels; ignore errors. + +``` +val output_char : out_channel -> char -> unit +``` +Write the character on the given output channel. + +``` +val output_string : out_channel -> string -> unit +``` +Write the string on the given output channel. + +``` +val output_bytes : out_channel -> bytes -> unit +``` +Write the byte sequence on the given output channel. + +since 4.02 +``` +val output : out_channel -> bytes -> int -> int -> unit +``` +`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. + +raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val output_substring : out_channel -> string -> int -> int -> unit +``` +Same as `output` but take a string as argument instead of a byte sequence. + +since 4.02 +``` +val output_byte : out_channel -> int -> unit +``` +Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. + +``` +val output_binary_int : out_channel -> int -> unit +``` +Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the [`Stdlib.input_binary_int`](./#val-input_binary_int) function. The format is compatible across all machines for a given version of OCaml. + +``` +val output_value : out_channel -> 'a -> unit +``` +Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function [`Stdlib.input_value`](./#val-input_value). See the description of module [`Marshal`](./Stdlib-Marshal.md) for more information. [`Stdlib.output_value`](./#val-output_value) is equivalent to [`Marshal.to_channel`](./Stdlib-Marshal.md#val-to_channel) with an empty list of flags. + +``` +val seek_out : out_channel -> int -> unit +``` +`seek_out chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. + +``` +val pos_out : out_channel -> int +``` +Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_out`, then going back to this position using `seek_out` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + +``` +val out_channel_length : out_channel -> int +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. + +``` +val close_out : out_channel -> unit +``` +Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except `close_out` and `flush`, which do nothing when applied to an already closed channel. Note that `close_out` may raise `Sys_error` if the operating system signals an error when flushing or closing. + +``` +val close_out_noerr : out_channel -> unit +``` +Same as `close_out`, but ignore all errors. + +``` +val set_binary_mode_out : out_channel -> bool -> unit +``` +`set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. `set_binary_mode_out oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. + + +### General input functions + +``` +val open_in : string -> in_channel +``` +Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. + +``` +val open_in_bin : string -> in_channel +``` +Same as [`Stdlib.open_in`](./#val-open_in), but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_in`](./#val-open_in). + +``` +val open_in_gen : open_flag list -> int -> string -> in_channel +``` +`open_in_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`Stdlib.open_in`](./#val-open_in) and [`Stdlib.open_in_bin`](./#val-open_in_bin) are special cases of this function. + +``` +val input_char : in_channel -> char +``` +Read one character from the given input channel. + +raises [`End_of_file`](./#exception-End_of_file) if there are no more characters to read. +``` +val input_line : in_channel -> string +``` +Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. + +raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. +``` +val input : in_channel -> bytes -> int -> int -> int +``` +`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and `len` exclusive means that not all requested `len` characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; `input` must be called again to read the remaining characters, if desired. (See also [`Stdlib.really_input`](./#val-really_input) for reading exactly `len` characters.) Exception `Invalid_argument "input"` is raised if `pos` and `len` do not designate a valid range of `buf`. + +``` +val really_input : in_channel -> bytes -> int -> int -> unit +``` +`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. + +raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. +raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. +``` +val really_input_string : in_channel -> int -> string +``` +`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. + +raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. +since 4.02 +``` +val input_byte : in_channel -> int +``` +Same as [`Stdlib.input_char`](./#val-input_char), but return the 8-bit integer representing the character. + +raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached. +``` +val input_binary_int : in_channel -> int +``` +Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See [`Stdlib.output_binary_int`](./#val-output_binary_int). + +raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached while reading the integer. +``` +val input_value : in_channel -> 'a +``` +Read the representation of a structured value, as produced by [`Stdlib.output_value`](./#val-output_value), and return the corresponding value. This function is identical to [`Marshal.from_channel`](./Stdlib-Marshal.md#val-from_channel); see the description of module [`Marshal`](./Stdlib-Marshal.md) for more information, in particular concerning the lack of type safety. + +``` +val seek_in : in_channel -> int -> unit +``` +`seek_in chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. + +``` +val pos_in : in_channel -> int +``` +Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_in`, then going back to this position using `seek_in` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. + +``` +val in_channel_length : in_channel -> int +``` +Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. + +``` +val close_in : in_channel -> unit +``` +Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except `close_in`, which does nothing when applied to an already closed channel. + +``` +val close_in_noerr : in_channel -> unit +``` +Same as `close_in`, but ignore all errors. + +``` +val set_binary_mode_in : in_channel -> bool -> unit +``` +`set_binary_mode_in ic true` sets the channel `ic` to binary mode: no translations take place during input. `set_binary_mode_out ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. + + +### Operations on large files + +``` +module LargeFile : sig ... end +``` +Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. + + +## References + +``` +type 'a ref = { +``` +`mutable contents : 'a;` +``` +} +``` +The type of references (mutable indirection cells) containing a value of type `'a`. + +``` +val ref : 'a -> 'a ref +``` +Return a fresh reference containing the given value. + +``` +val (!) : 'a ref -> 'a +``` +`!r` returns the current contents of reference `r`. Equivalent to `fun r -> r.contents`. Unary operator, see `Ocaml_operators` for more information. + +``` +val (:=) : 'a ref -> 'a -> unit +``` +`r := a` stores the value of `a` in reference `r`. Equivalent to `fun r v -> r.contents <- v`. Right-associative operator, see `Ocaml_operators` for more information. + +``` +val incr : int ref -> unit +``` +Increment the integer contained in the given reference. Equivalent to `fun r -> r := succ !r`. + +``` +val decr : int ref -> unit +``` +Decrement the integer contained in the given reference. Equivalent to `fun r -> r := pred !r`. + + +## Result type + +``` +type ('a, 'b) result = +``` +``` +| Ok of 'a +``` +``` +| Error of 'b +``` +``` + +``` +since 4.03 + +## Operations on format strings + +Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module [`Scanf`](./Stdlib-Scanf.md) and to print data with formatted output functions from modules [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). + +Format strings are made of three kinds of entities: + +- *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print, +- *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument, +- *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output. +There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`. + +For more information about conversion specifications and formatting indications available, read the documentation of modules [`Scanf`](./Stdlib-Scanf.md), [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). + +Format strings have a general and highly polymorphic type `('a, 'b, 'c, 'd, 'e, 'f) format6`. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml. + +The meaning of format string type parameters is as follows: + +- `'a` is the type of the parameters of the format for formatted output functions (`printf`\-style functions); `'a` is the type of the values read by the format for formatted input functions (`scanf`\-style functions). +- `'b` is the type of input source for formatted input functions and the type of output target for formatted output functions. For `printf`\-style functions from module [`Printf`](./Stdlib-Printf.md), `'b` is typically `out_channel`; for `printf`\-style functions from module [`Format`](./Stdlib-Format.md), `'b` is typically [`Format.formatter`](./Stdlib-Format.md#type-formatter); for `scanf`\-style functions from module [`Scanf`](./Stdlib-Scanf.md), `'b` is typically [`Scanf.Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). +Type argument `'b` is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion. + +- `'c` is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf`\-style functions or to the `kscanf`\-style functions. +- `'d` is the type of parameters for the `scanf`\-style functions. +- `'e` is the type of the receiver function for the `scanf`\-style functions. +- `'f` is the final result type of a formatted input/output function invocation: for the `printf`\-style functions, it is typically `unit`; for the `scanf`\-style functions, it is typically the result type of the receiver function. +``` +type ('a, 'b, 'c, 'd, 'e, 'f) format6 = + ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 +``` +``` +type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 +``` +``` +type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 +``` +``` +val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string +``` +Converts a format string into a string. + +``` +val format_of_string : + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + ('a, 'b, 'c, 'd, 'e, 'f) format6 +``` +`format_of_string s` returns a format string read from the string literal `s`. Note: `format_of_string` can not convert a string argument that is not a literal. If you need this functionality, use the more general [`Scanf.format_from_string`](./Stdlib-Scanf.md#val-format_from_string) function. + +``` +val (^^) : + ('a, 'b, 'c, 'd, 'e, 'f) format6 -> + ('f, 'b, 'c, 'e, 'g, 'h) format6 -> + ('a, 'b, 'c, 'd, 'g, 'h) format6 +``` +`f1 ^^ f2` catenates format strings `f1` and `f2`. The result is a format string that behaves as the concatenation of format strings `f1` and `f2`: in case of formatted output, it accepts arguments from `f1`, then arguments from `f2`; in case of formatted input, it returns results from `f1`, then results from `f2`. Right-associative operator, see `Ocaml_operators` for more information. + + +## Program termination + +``` +val exit : int -> 'a +``` +Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with [`Domain.at_exit`](./Stdlib-Domain.md#val-at_exit) are called followed by those registered with [`Stdlib.at_exit`](./#val-at_exit). + +An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception. + +``` +val at_exit : (unit -> unit) -> unit +``` +Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following: + +- executes [`Stdlib.exit`](./#val-exit) +- terminates, either normally or because of an uncaught exception +- executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. + +## Standard library modules + +``` +module Arg : sig ... end +``` +Parsing of command line arguments. + +``` +module Array : sig ... end +``` +Array operations. + +``` +module ArrayLabels : sig ... end +``` +Array operations. + +``` +module Atomic : sig ... end +``` +Atomic references. + +``` +module Bool : sig ... end +``` +Boolean values. + +``` +module Buffer : sig ... end +``` +Extensible buffers. + +``` +module Bytes : sig ... end +``` +Byte sequence operations. + +``` +module BytesLabels : sig ... end +``` +Byte sequence operations. + +``` +module Char : sig ... end +``` +Character operations. + +``` +module Complex : sig ... end +``` +Complex numbers. + +``` +module Digest : sig ... end +``` +Message digest. + +``` +module Domain : sig ... end +``` +``` +module Dynarray : sig ... end +``` +Dynamic arrays. + +``` +module Effect : sig ... end +``` +``` +module Either : sig ... end +``` +Either type. + +``` +module Filename : sig ... end +``` +Operations on file names. + +``` +module Float : sig ... end +``` +Floating-point arithmetic. + +``` +module Format : sig ... end +``` +Pretty-printing. + +``` +module Fun : sig ... end +``` +Function manipulation. + +``` +module Gc : sig ... end +``` +Memory management control and statistics; finalised values. + +``` +module Hashtbl : sig ... end +``` +Hash tables and hash functions. + +``` +module In_channel : sig ... end +``` +Input channels. + +``` +module Int : sig ... end +``` +Integer values. + +``` +module Int32 : sig ... end +``` +32-bit integers. + +``` +module Int64 : sig ... end +``` +64-bit integers. + +``` +module Lazy : sig ... end +``` +Deferred computations. + +``` +module Lexing : sig ... end +``` +The run-time library for lexers generated by `ocamllex`. + +``` +module List : sig ... end +``` +List operations. + +``` +module ListLabels : sig ... end +``` +List operations. + +``` +module Map : sig ... end +``` +Association tables over ordered types. + +``` +module Marshal : sig ... end +``` +Marshaling of data structures. + +``` +module MoreLabels : sig ... end +``` +Extra labeled libraries. + +``` +module Mutex : sig ... end +``` +Locks for mutual exclusion. + +``` +module Obj : sig ... end +``` +Operations on internal representations of values. + +``` +module Oo : sig ... end +``` +Operations on objects + +``` +module Option : sig ... end +``` +Option values. + +``` +module Out_channel : sig ... end +``` +Output channels. + +``` +module Parsing : sig ... end +``` +The run-time library for parsers generated by `ocamlyacc`. + +``` +module Printexc : sig ... end +``` +Facilities for printing exceptions and inspecting current call stack. + +``` +module Printf : sig ... end +``` +Formatted output functions. + +``` +module Queue : sig ... end +``` +First-in first-out queues. + +``` +module Random : sig ... end +``` +Pseudo-random number generators (PRNG). + +``` +module Result : sig ... end +``` +Result values. + +``` +module Scanf : sig ... end +``` +Formatted input functions. + +``` +module Seq : sig ... end +``` +Sequences. + +``` +module Set : sig ... end +``` +Sets over ordered types. + +``` +module Stack : sig ... end +``` +Last-in first-out stacks. + +``` +module StdLabels : sig ... end +``` +Standard labeled libraries. + +``` +module String : sig ... end +``` +Strings. + +``` +module StringLabels : sig ... end +``` +Strings. + +``` +module Sys : sig ... end +``` +System interface. + +``` +module Type : sig ... end +``` +Type introspection. + +``` +module Uchar : sig ... end +``` +Unicode characters. + +``` +module Unit : sig ... end +``` +Unit values. + +``` +module Weak : sig ... end +``` +Arrays of weak pointers and hash sets of weak pointers. diff --git a/docs/public/api/.gitkeep b/docs/public/api/.gitkeep deleted file mode 100644 index e69de29bb..000000000 From d2b29b7cdfeea6235b4e31862b0c1c30ecd91432 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Fri, 1 Aug 2025 15:35:45 +0200 Subject: [PATCH 09/19] Use dune for markdown generation directly --- Makefile | 15 ++------------- documentation-site.opam.template | 1 + 2 files changed, 3 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index ec0a30cf6..0c5b8752a 100644 --- a/Makefile +++ b/Makefile @@ -89,18 +89,7 @@ pull-melange-docs: ## Pull melange docs opam source melange; \ fi cd melange.dev - dune build @doc + dune build @doc-markdown cd .. - odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/stdlib.odocl - odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/js.odocl - odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/belt.odocl - odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/dom.odocl - odoc markdown-generate -o docs/api/ml ./_build/default/_doc/_odocls/melange/node.odocl cd melange.dev - ODOC_SYNTAX="re" dune build @doc - cd .. - odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/stdlib.odocl - odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/js.odocl - odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/belt.odocl - odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/dom.odocl - odoc markdown-generate -o docs/api/re ./_build/default/_doc/_odocls/melange/node.odocl + ODOC_SYNTAX="re" dune build @doc-markdown diff --git a/documentation-site.opam.template b/documentation-site.opam.template index 838339cd8..48b7079e9 100644 --- a/documentation-site.opam.template +++ b/documentation-site.opam.template @@ -4,4 +4,5 @@ pin-depends: [ ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] + ["dune.dev" "git+https://github.com/davesnx/dune.git#f3481f5b3c54f01ec5022c619fd2582cb4119ed8"] ] From 45b16f7dc87d42e30e4d72a2f86ff0ce08333a72 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Fri, 1 Aug 2025 16:44:50 +0200 Subject: [PATCH 10/19] Push latest from davesnx/dune --- .github/workflows/deploy-docs.yml | 2 +- documentation-site.opam.template | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 22e61a812..1e62d5b45 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -40,7 +40,7 @@ jobs: git config --local user.email "github-actions[bot]@users.noreply.github.com" git config --local user.name "github-actions[bot]" - name: Fetch and checkout gh-pages - run: | + run: | git fetch origin gh-pages --depth=1 git checkout gh-pages - name: Copy published site into folder diff --git a/documentation-site.opam.template b/documentation-site.opam.template index 48b7079e9..d3e2d61c8 100644 --- a/documentation-site.opam.template +++ b/documentation-site.opam.template @@ -4,5 +4,5 @@ pin-depends: [ ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] - ["dune.dev" "git+https://github.com/davesnx/dune.git#f3481f5b3c54f01ec5022c619fd2582cb4119ed8"] + ["dune.dev" "git+https://github.com/davesnx/dune.git#74cd7f053526cb4409a44f75f0a8505d100f51b4"] ] From 16230ab85b4dfa0b39585679ec673688374e20e9 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Fri, 5 Sep 2025 13:30:55 +0200 Subject: [PATCH 11/19] Remove markdown from repo --- docs/api/ml/melange/Belt-Array.md | 654 ------- docs/api/ml/melange/Belt-Float.md | 29 - docs/api/ml/melange/Belt-HashMap-Int.md | 79 - docs/api/ml/melange/Belt-HashMap-String.md | 79 - docs/api/ml/melange/Belt-HashMap.md | 165 -- docs/api/ml/melange/Belt-HashSet-Int.md | 68 - docs/api/ml/melange/Belt-HashSet-String.md | 68 - docs/api/ml/melange/Belt-HashSet.md | 124 -- .../Belt-Id-MakeComparable-argument-1-M.md | 9 - docs/api/ml/melange/Belt-Id-MakeComparable.md | 21 - .../Belt-Id-MakeComparableU-argument-1-M.md | 9 - .../api/ml/melange/Belt-Id-MakeComparableU.md | 21 - .../Belt-Id-MakeHashable-argument-1-M.md | 12 - docs/api/ml/melange/Belt-Id-MakeHashable.md | 24 - .../Belt-Id-MakeHashableU-argument-1-M.md | 12 - docs/api/ml/melange/Belt-Id-MakeHashableU.md | 24 - .../melange/Belt-Id-module-type-Comparable.md | 12 - .../melange/Belt-Id-module-type-Hashable.md | 15 - docs/api/ml/melange/Belt-Id.md | 113 -- docs/api/ml/melange/Belt-Int.md | 29 - docs/api/ml/melange/Belt-List.md | 680 ------- docs/api/ml/melange/Belt-Map-Dict.md | 281 --- docs/api/ml/melange/Belt-Map-Int.md | 217 --- docs/api/ml/melange/Belt-Map-String.md | 217 --- docs/api/ml/melange/Belt-Map.md | 460 ----- docs/api/ml/melange/Belt-MutableMap-Int.md | 165 -- docs/api/ml/melange/Belt-MutableMap-String.md | 165 -- docs/api/ml/melange/Belt-MutableMap.md | 206 --- docs/api/ml/melange/Belt-MutableQueue.md | 114 -- docs/api/ml/melange/Belt-MutableSet-Int.md | 166 -- docs/api/ml/melange/Belt-MutableSet-String.md | 166 -- docs/api/ml/melange/Belt-MutableSet.md | 189 -- docs/api/ml/melange/Belt-MutableStack.md | 62 - docs/api/ml/melange/Belt-Option.md | 200 --- docs/api/ml/melange/Belt-Range.md | 62 - docs/api/ml/melange/Belt-Result.md | 165 -- docs/api/ml/melange/Belt-Set-Dict.md | 197 --- docs/api/ml/melange/Belt-Set-Int.md | 163 -- docs/api/ml/melange/Belt-Set-String.md | 163 -- docs/api/ml/melange/Belt-Set.md | 377 ---- docs/api/ml/melange/Belt-SortArray-Int.md | 39 - docs/api/ml/melange/Belt-SortArray-String.md | 39 - docs/api/ml/melange/Belt-SortArray.md | 81 - docs/api/ml/melange/Belt.md | 168 -- docs/api/ml/melange/Dom-Storage.md | 30 - docs/api/ml/melange/Dom.md | 841 --------- docs/api/ml/melange/Js-Array.md | 179 -- docs/api/ml/melange/Js-Bigint.md | 71 - docs/api/ml/melange/Js-Blob.md | 54 - docs/api/ml/melange/Js-Console.md | 72 - docs/api/ml/melange/Js-Date.md | 319 ---- docs/api/ml/melange/Js-Dict.md | 74 - docs/api/ml/melange/Js-Exn.md | 78 - docs/api/ml/melange/Js-File.md | 72 - docs/api/ml/melange/Js-Float.md | 140 -- docs/api/ml/melange/Js-FormData.md | 90 - docs/api/ml/melange/Js-Global.md | 150 -- docs/api/ml/melange/Js-Int.md | 79 - docs/api/ml/melange/Js-Iterator.md | 25 - docs/api/ml/melange/Js-Json.md | 285 --- docs/api/ml/melange/Js-Map.md | 49 - docs/api/ml/melange/Js-Math.md | 299 ---- docs/api/ml/melange/Js-Null.md | 74 - docs/api/ml/melange/Js-Nullable.md | 79 - docs/api/ml/melange/Js-Obj.md | 19 - docs/api/ml/melange/Js-Promise.md | 57 - docs/api/ml/melange/Js-Re.md | 178 -- docs/api/ml/melange/Js-Set.md | 43 - docs/api/ml/melange/Js-String.md | 464 ----- .../ml/melange/Js-Typed_array-ArrayBuffer.md | 20 - .../api/ml/melange/Js-Typed_array-DataView.md | 108 -- .../ml/melange/Js-Typed_array-Float32Array.md | 165 -- .../ml/melange/Js-Typed_array-Float64Array.md | 165 -- .../ml/melange/Js-Typed_array-Int16Array.md | 165 -- .../ml/melange/Js-Typed_array-Int32Array.md | 165 -- .../ml/melange/Js-Typed_array-Int8Array.md | 165 -- .../ml/melange/Js-Typed_array-Uint16Array.md | 165 -- .../ml/melange/Js-Typed_array-Uint32Array.md | 165 -- .../ml/melange/Js-Typed_array-Uint8Array.md | 165 -- .../Js-Typed_array-Uint8ClampedArray.md | 165 -- docs/api/ml/melange/Js-Typed_array.md | 44 - docs/api/ml/melange/Js-Types.md | 109 -- docs/api/ml/melange/Js-Undefined.md | 79 - docs/api/ml/melange/Js-WeakMap.md | 25 - docs/api/ml/melange/Js-WeakSet.md | 22 - docs/api/ml/melange/Js.md | 320 ---- docs/api/ml/melange/Node-Buffer.md | 56 - docs/api/ml/melange/Node-Child_process.md | 30 - docs/api/ml/melange/Node-Fs-Watch.md | 33 - docs/api/ml/melange/Node-Fs.md | 110 -- docs/api/ml/melange/Node-Module.md | 8 - docs/api/ml/melange/Node-Path.md | 56 - docs/api/ml/melange/Node-Process.md | 38 - docs/api/ml/melange/Node.md | 73 - docs/api/ml/melange/Stdlib-Arg.md | 261 --- docs/api/ml/melange/Stdlib-Array.md | 373 ---- docs/api/ml/melange/Stdlib-ArrayLabels.md | 383 ---- docs/api/ml/melange/Stdlib-Atomic.md | 144 -- docs/api/ml/melange/Stdlib-Bool.md | 83 - docs/api/ml/melange/Stdlib-Buffer.md | 282 --- docs/api/ml/melange/Stdlib-Bytes.md | 683 ------- docs/api/ml/melange/Stdlib-BytesLabels.md | 695 -------- docs/api/ml/melange/Stdlib-Char.md | 61 - docs/api/ml/melange/Stdlib-Complex.md | 106 -- docs/api/ml/melange/Stdlib-Digest-BLAKE128.md | 78 - docs/api/ml/melange/Stdlib-Digest-BLAKE256.md | 78 - docs/api/ml/melange/Stdlib-Digest-BLAKE512.md | 78 - docs/api/ml/melange/Stdlib-Digest-MD5.md | 78 - .../ml/melange/Stdlib-Digest-module-type-S.md | 78 - docs/api/ml/melange/Stdlib-Digest.md | 120 -- docs/api/ml/melange/Stdlib-Domain-DLS.md | 45 - docs/api/ml/melange/Stdlib-Domain.md | 89 - docs/api/ml/melange/Stdlib-Dynarray.md | 582 ------ docs/api/ml/melange/Stdlib-Either.md | 115 -- docs/api/ml/melange/Stdlib-Filename.md | 167 -- docs/api/ml/melange/Stdlib-Float-Array.md | 330 ---- docs/api/ml/melange/Stdlib-Float.md | 482 ----- docs/api/ml/melange/Stdlib-Format.md | 1401 --------------- docs/api/ml/melange/Stdlib-Fun.md | 51 - docs/api/ml/melange/Stdlib-Gc-Memprof.md | 113 -- docs/api/ml/melange/Stdlib-Gc.md | 295 ---- .../Stdlib-Hashtbl-Make-argument-1-H.md | 21 - docs/api/ml/melange/Stdlib-Hashtbl-Make.md | 96 - .../Stdlib-Hashtbl-MakeSeeded-argument-1-H.md | 17 - .../ml/melange/Stdlib-Hashtbl-MakeSeeded.md | 95 - .../Stdlib-Hashtbl-module-type-HashedType.md | 23 - .../melange/Stdlib-Hashtbl-module-type-S.md | 87 - ...ib-Hashtbl-module-type-SeededHashedType.md | 20 - .../Stdlib-Hashtbl-module-type-SeededS.md | 86 - docs/api/ml/melange/Stdlib-Hashtbl.md | 388 ---- docs/api/ml/melange/Stdlib-In_channel.md | 238 --- docs/api/ml/melange/Stdlib-Int.md | 176 -- docs/api/ml/melange/Stdlib-Int32.md | 237 --- docs/api/ml/melange/Stdlib-Int64.md | 257 --- docs/api/ml/melange/Stdlib-LargeFile.md | 23 - docs/api/ml/melange/Stdlib-Lazy.md | 95 - docs/api/ml/melange/Stdlib-Lexing.md | 136 -- docs/api/ml/melange/Stdlib-List.md | 482 ----- docs/api/ml/melange/Stdlib-ListLabels.md | 482 ----- .../melange/Stdlib-Map-Make-argument-1-Ord.md | 12 - docs/api/ml/melange/Stdlib-Map-Make.md | 315 ---- .../Stdlib-Map-module-type-OrderedType.md | 14 - .../ml/melange/Stdlib-Map-module-type-S.md | 306 ---- docs/api/ml/melange/Stdlib-Map.md | 39 - docs/api/ml/melange/Stdlib-Marshal.md | 106 -- ...ib-MoreLabels-Hashtbl-Make-argument-1-H.md | 21 - .../melange/Stdlib-MoreLabels-Hashtbl-Make.md | 96 - ...eLabels-Hashtbl-MakeSeeded-argument-1-H.md | 17 - .../Stdlib-MoreLabels-Hashtbl-MakeSeeded.md | 95 - ...reLabels-Hashtbl-module-type-HashedType.md | 23 - ...Stdlib-MoreLabels-Hashtbl-module-type-S.md | 87 - ...ls-Hashtbl-module-type-SeededHashedType.md | 20 - ...-MoreLabels-Hashtbl-module-type-SeededS.md | 86 - .../ml/melange/Stdlib-MoreLabels-Hashtbl.md | 399 ----- ...dlib-MoreLabels-Map-Make-argument-1-Ord.md | 12 - .../ml/melange/Stdlib-MoreLabels-Map-Make.md | 315 ---- ...-MoreLabels-Map-module-type-OrderedType.md | 14 - .../Stdlib-MoreLabels-Map-module-type-S.md | 306 ---- docs/api/ml/melange/Stdlib-MoreLabels-Map.md | 41 - ...dlib-MoreLabels-Set-Make-argument-1-Ord.md | 12 - .../ml/melange/Stdlib-MoreLabels-Set-Make.md | 297 ---- ...-MoreLabels-Set-module-type-OrderedType.md | 14 - .../Stdlib-MoreLabels-Set-module-type-S.md | 288 --- docs/api/ml/melange/Stdlib-MoreLabels-Set.md | 41 - docs/api/ml/melange/Stdlib-MoreLabels.md | 30 - docs/api/ml/melange/Stdlib-Mutex.md | 49 - docs/api/ml/melange/Stdlib-Obj-Ephemeron.md | 65 - .../Stdlib-Obj-Extension_constructor.md | 15 - docs/api/ml/melange/Stdlib-Obj.md | 139 -- docs/api/ml/melange/Stdlib-Oo.md | 15 - docs/api/ml/melange/Stdlib-Option.md | 111 -- docs/api/ml/melange/Stdlib-Out_channel.md | 239 --- docs/api/ml/melange/Stdlib-Parsing.md | 61 - docs/api/ml/melange/Stdlib-Printexc-Slot.md | 45 - docs/api/ml/melange/Stdlib-Printexc.md | 280 --- docs/api/ml/melange/Stdlib-Printf.md | 144 -- docs/api/ml/melange/Stdlib-Queue.md | 225 --- docs/api/ml/melange/Stdlib-Random-State.md | 50 - docs/api/ml/melange/Stdlib-Random.md | 103 -- docs/api/ml/melange/Stdlib-Result.md | 137 -- docs/api/ml/melange/Stdlib-Scanf-Scanning.md | 95 - docs/api/ml/melange/Stdlib-Scanf.md | 265 --- docs/api/ml/melange/Stdlib-Seq.md | 624 ------- .../melange/Stdlib-Set-Make-argument-1-Ord.md | 12 - docs/api/ml/melange/Stdlib-Set-Make.md | 297 ---- .../Stdlib-Set-module-type-OrderedType.md | 14 - .../ml/melange/Stdlib-Set-module-type-S.md | 288 --- docs/api/ml/melange/Stdlib-Set.md | 39 - docs/api/ml/melange/Stdlib-Stack.md | 111 -- docs/api/ml/melange/Stdlib-StdLabels.md | 26 - docs/api/ml/melange/Stdlib-String.md | 480 ----- docs/api/ml/melange/Stdlib-StringLabels.md | 486 ----- ...s-Immediate64-Make-argument-1-Immediate.md | 6 - ...mediate64-Make-argument-2-Non_immediate.md | 6 - .../ml/melange/Stdlib-Sys-Immediate64-Make.md | 33 - ...b-Sys-Immediate64-module-type-Immediate.md | 6 - ...s-Immediate64-module-type-Non_immediate.md | 6 - docs/api/ml/melange/Stdlib-Sys-Immediate64.md | 18 - docs/api/ml/melange/Stdlib-Sys.md | 476 ----- docs/api/ml/melange/Stdlib-Type-Id.md | 80 - docs/api/ml/melange/Stdlib-Type.md | 36 - docs/api/ml/melange/Stdlib-Uchar.md | 144 -- docs/api/ml/melange/Stdlib-Unit.md | 36 - .../melange/Stdlib-Weak-Make-argument-1-H.md | 21 - docs/api/ml/melange/Stdlib-Weak-Make.md | 90 - .../ml/melange/Stdlib-Weak-module-type-S.md | 81 - docs/api/ml/melange/Stdlib-Weak.md | 88 - docs/api/ml/melange/Stdlib.md | 1565 ----------------- docs/api/re/melange/Belt-Array.md | 654 ------- docs/api/re/melange/Belt-Float.md | 29 - docs/api/re/melange/Belt-HashMap-Int.md | 79 - docs/api/re/melange/Belt-HashMap-String.md | 79 - docs/api/re/melange/Belt-HashMap.md | 165 -- docs/api/re/melange/Belt-HashSet-Int.md | 68 - docs/api/re/melange/Belt-HashSet-String.md | 68 - docs/api/re/melange/Belt-HashSet.md | 124 -- .../Belt-Id-MakeComparable-argument-1-M.md | 9 - docs/api/re/melange/Belt-Id-MakeComparable.md | 21 - .../Belt-Id-MakeComparableU-argument-1-M.md | 9 - .../api/re/melange/Belt-Id-MakeComparableU.md | 21 - .../Belt-Id-MakeHashable-argument-1-M.md | 12 - docs/api/re/melange/Belt-Id-MakeHashable.md | 24 - .../Belt-Id-MakeHashableU-argument-1-M.md | 12 - docs/api/re/melange/Belt-Id-MakeHashableU.md | 24 - .../melange/Belt-Id-module-type-Comparable.md | 12 - .../melange/Belt-Id-module-type-Hashable.md | 15 - docs/api/re/melange/Belt-Id.md | 113 -- docs/api/re/melange/Belt-Int.md | 29 - docs/api/re/melange/Belt-List.md | 680 ------- docs/api/re/melange/Belt-Map-Dict.md | 281 --- docs/api/re/melange/Belt-Map-Int.md | 217 --- docs/api/re/melange/Belt-Map-String.md | 217 --- docs/api/re/melange/Belt-Map.md | 460 ----- docs/api/re/melange/Belt-MutableMap-Int.md | 165 -- docs/api/re/melange/Belt-MutableMap-String.md | 165 -- docs/api/re/melange/Belt-MutableMap.md | 206 --- docs/api/re/melange/Belt-MutableQueue.md | 114 -- docs/api/re/melange/Belt-MutableSet-Int.md | 166 -- docs/api/re/melange/Belt-MutableSet-String.md | 166 -- docs/api/re/melange/Belt-MutableSet.md | 189 -- docs/api/re/melange/Belt-MutableStack.md | 62 - docs/api/re/melange/Belt-Option.md | 200 --- docs/api/re/melange/Belt-Range.md | 62 - docs/api/re/melange/Belt-Result.md | 165 -- docs/api/re/melange/Belt-Set-Dict.md | 197 --- docs/api/re/melange/Belt-Set-Int.md | 163 -- docs/api/re/melange/Belt-Set-String.md | 163 -- docs/api/re/melange/Belt-Set.md | 377 ---- docs/api/re/melange/Belt-SortArray-Int.md | 39 - docs/api/re/melange/Belt-SortArray-String.md | 39 - docs/api/re/melange/Belt-SortArray.md | 81 - docs/api/re/melange/Belt.md | 168 -- docs/api/re/melange/Dom-Storage.md | 30 - docs/api/re/melange/Dom.md | 841 --------- docs/api/re/melange/Js-Array.md | 179 -- docs/api/re/melange/Js-Bigint.md | 71 - docs/api/re/melange/Js-Blob.md | 54 - docs/api/re/melange/Js-Console.md | 72 - docs/api/re/melange/Js-Date.md | 319 ---- docs/api/re/melange/Js-Dict.md | 74 - docs/api/re/melange/Js-Exn.md | 78 - docs/api/re/melange/Js-File.md | 72 - docs/api/re/melange/Js-Float.md | 140 -- docs/api/re/melange/Js-FormData.md | 90 - docs/api/re/melange/Js-Global.md | 150 -- docs/api/re/melange/Js-Int.md | 79 - docs/api/re/melange/Js-Iterator.md | 25 - docs/api/re/melange/Js-Json.md | 285 --- docs/api/re/melange/Js-Map.md | 49 - docs/api/re/melange/Js-Math.md | 299 ---- docs/api/re/melange/Js-Null.md | 74 - docs/api/re/melange/Js-Nullable.md | 79 - docs/api/re/melange/Js-Obj.md | 19 - docs/api/re/melange/Js-Promise.md | 57 - docs/api/re/melange/Js-Re.md | 178 -- docs/api/re/melange/Js-Set.md | 43 - docs/api/re/melange/Js-String.md | 464 ----- .../re/melange/Js-Typed_array-ArrayBuffer.md | 20 - .../api/re/melange/Js-Typed_array-DataView.md | 108 -- .../re/melange/Js-Typed_array-Float32Array.md | 165 -- .../re/melange/Js-Typed_array-Float64Array.md | 165 -- .../re/melange/Js-Typed_array-Int16Array.md | 165 -- .../re/melange/Js-Typed_array-Int32Array.md | 165 -- .../re/melange/Js-Typed_array-Int8Array.md | 165 -- .../re/melange/Js-Typed_array-Uint16Array.md | 165 -- .../re/melange/Js-Typed_array-Uint32Array.md | 165 -- .../re/melange/Js-Typed_array-Uint8Array.md | 165 -- .../Js-Typed_array-Uint8ClampedArray.md | 165 -- docs/api/re/melange/Js-Typed_array.md | 44 - docs/api/re/melange/Js-Types.md | 109 -- docs/api/re/melange/Js-Undefined.md | 79 - docs/api/re/melange/Js-WeakMap.md | 25 - docs/api/re/melange/Js-WeakSet.md | 22 - docs/api/re/melange/Js.md | 320 ---- docs/api/re/melange/Node-Buffer.md | 56 - docs/api/re/melange/Node-Child_process.md | 30 - docs/api/re/melange/Node-Fs-Watch.md | 33 - docs/api/re/melange/Node-Fs.md | 110 -- docs/api/re/melange/Node-Module.md | 8 - docs/api/re/melange/Node-Path.md | 56 - docs/api/re/melange/Node-Process.md | 38 - docs/api/re/melange/Node.md | 73 - docs/api/re/melange/Stdlib-Arg.md | 261 --- docs/api/re/melange/Stdlib-Array.md | 373 ---- docs/api/re/melange/Stdlib-ArrayLabels.md | 383 ---- docs/api/re/melange/Stdlib-Atomic.md | 144 -- docs/api/re/melange/Stdlib-Bool.md | 83 - docs/api/re/melange/Stdlib-Buffer.md | 282 --- docs/api/re/melange/Stdlib-Bytes.md | 683 ------- docs/api/re/melange/Stdlib-BytesLabels.md | 695 -------- docs/api/re/melange/Stdlib-Char.md | 61 - docs/api/re/melange/Stdlib-Complex.md | 106 -- docs/api/re/melange/Stdlib-Digest-BLAKE128.md | 78 - docs/api/re/melange/Stdlib-Digest-BLAKE256.md | 78 - docs/api/re/melange/Stdlib-Digest-BLAKE512.md | 78 - docs/api/re/melange/Stdlib-Digest-MD5.md | 78 - .../re/melange/Stdlib-Digest-module-type-S.md | 78 - docs/api/re/melange/Stdlib-Digest.md | 120 -- docs/api/re/melange/Stdlib-Domain-DLS.md | 45 - docs/api/re/melange/Stdlib-Domain.md | 89 - docs/api/re/melange/Stdlib-Dynarray.md | 582 ------ docs/api/re/melange/Stdlib-Either.md | 115 -- docs/api/re/melange/Stdlib-Filename.md | 167 -- docs/api/re/melange/Stdlib-Float-Array.md | 330 ---- docs/api/re/melange/Stdlib-Float.md | 482 ----- docs/api/re/melange/Stdlib-Format.md | 1401 --------------- docs/api/re/melange/Stdlib-Fun.md | 51 - docs/api/re/melange/Stdlib-Gc-Memprof.md | 113 -- docs/api/re/melange/Stdlib-Gc.md | 295 ---- .../Stdlib-Hashtbl-Make-argument-1-H.md | 21 - docs/api/re/melange/Stdlib-Hashtbl-Make.md | 96 - .../Stdlib-Hashtbl-MakeSeeded-argument-1-H.md | 17 - .../re/melange/Stdlib-Hashtbl-MakeSeeded.md | 95 - .../Stdlib-Hashtbl-module-type-HashedType.md | 23 - .../melange/Stdlib-Hashtbl-module-type-S.md | 87 - ...ib-Hashtbl-module-type-SeededHashedType.md | 20 - .../Stdlib-Hashtbl-module-type-SeededS.md | 86 - docs/api/re/melange/Stdlib-Hashtbl.md | 388 ---- docs/api/re/melange/Stdlib-In_channel.md | 238 --- docs/api/re/melange/Stdlib-Int.md | 176 -- docs/api/re/melange/Stdlib-Int32.md | 237 --- docs/api/re/melange/Stdlib-Int64.md | 257 --- docs/api/re/melange/Stdlib-LargeFile.md | 23 - docs/api/re/melange/Stdlib-Lazy.md | 95 - docs/api/re/melange/Stdlib-Lexing.md | 136 -- docs/api/re/melange/Stdlib-List.md | 482 ----- docs/api/re/melange/Stdlib-ListLabels.md | 482 ----- .../melange/Stdlib-Map-Make-argument-1-Ord.md | 12 - docs/api/re/melange/Stdlib-Map-Make.md | 315 ---- .../Stdlib-Map-module-type-OrderedType.md | 14 - .../re/melange/Stdlib-Map-module-type-S.md | 306 ---- docs/api/re/melange/Stdlib-Map.md | 39 - docs/api/re/melange/Stdlib-Marshal.md | 106 -- ...ib-MoreLabels-Hashtbl-Make-argument-1-H.md | 21 - .../melange/Stdlib-MoreLabels-Hashtbl-Make.md | 96 - ...eLabels-Hashtbl-MakeSeeded-argument-1-H.md | 17 - .../Stdlib-MoreLabels-Hashtbl-MakeSeeded.md | 95 - ...reLabels-Hashtbl-module-type-HashedType.md | 23 - ...Stdlib-MoreLabels-Hashtbl-module-type-S.md | 87 - ...ls-Hashtbl-module-type-SeededHashedType.md | 20 - ...-MoreLabels-Hashtbl-module-type-SeededS.md | 86 - .../re/melange/Stdlib-MoreLabels-Hashtbl.md | 399 ----- ...dlib-MoreLabels-Map-Make-argument-1-Ord.md | 12 - .../re/melange/Stdlib-MoreLabels-Map-Make.md | 315 ---- ...-MoreLabels-Map-module-type-OrderedType.md | 14 - .../Stdlib-MoreLabels-Map-module-type-S.md | 306 ---- docs/api/re/melange/Stdlib-MoreLabels-Map.md | 41 - ...dlib-MoreLabels-Set-Make-argument-1-Ord.md | 12 - .../re/melange/Stdlib-MoreLabels-Set-Make.md | 297 ---- ...-MoreLabels-Set-module-type-OrderedType.md | 14 - .../Stdlib-MoreLabels-Set-module-type-S.md | 288 --- docs/api/re/melange/Stdlib-MoreLabels-Set.md | 41 - docs/api/re/melange/Stdlib-MoreLabels.md | 30 - docs/api/re/melange/Stdlib-Mutex.md | 49 - docs/api/re/melange/Stdlib-Obj-Ephemeron.md | 65 - .../Stdlib-Obj-Extension_constructor.md | 15 - docs/api/re/melange/Stdlib-Obj.md | 139 -- docs/api/re/melange/Stdlib-Oo.md | 15 - docs/api/re/melange/Stdlib-Option.md | 111 -- docs/api/re/melange/Stdlib-Out_channel.md | 239 --- docs/api/re/melange/Stdlib-Parsing.md | 61 - docs/api/re/melange/Stdlib-Printexc-Slot.md | 45 - docs/api/re/melange/Stdlib-Printexc.md | 280 --- docs/api/re/melange/Stdlib-Printf.md | 144 -- docs/api/re/melange/Stdlib-Queue.md | 225 --- docs/api/re/melange/Stdlib-Random-State.md | 50 - docs/api/re/melange/Stdlib-Random.md | 103 -- docs/api/re/melange/Stdlib-Result.md | 137 -- docs/api/re/melange/Stdlib-Scanf-Scanning.md | 95 - docs/api/re/melange/Stdlib-Scanf.md | 265 --- docs/api/re/melange/Stdlib-Seq.md | 624 ------- .../melange/Stdlib-Set-Make-argument-1-Ord.md | 12 - docs/api/re/melange/Stdlib-Set-Make.md | 297 ---- .../Stdlib-Set-module-type-OrderedType.md | 14 - .../re/melange/Stdlib-Set-module-type-S.md | 288 --- docs/api/re/melange/Stdlib-Set.md | 39 - docs/api/re/melange/Stdlib-Stack.md | 111 -- docs/api/re/melange/Stdlib-StdLabels.md | 26 - docs/api/re/melange/Stdlib-String.md | 480 ----- docs/api/re/melange/Stdlib-StringLabels.md | 486 ----- ...s-Immediate64-Make-argument-1-Immediate.md | 6 - ...mediate64-Make-argument-2-Non_immediate.md | 6 - .../re/melange/Stdlib-Sys-Immediate64-Make.md | 33 - ...b-Sys-Immediate64-module-type-Immediate.md | 6 - ...s-Immediate64-module-type-Non_immediate.md | 6 - docs/api/re/melange/Stdlib-Sys-Immediate64.md | 18 - docs/api/re/melange/Stdlib-Sys.md | 476 ----- docs/api/re/melange/Stdlib-Type-Id.md | 80 - docs/api/re/melange/Stdlib-Type.md | 36 - docs/api/re/melange/Stdlib-Uchar.md | 144 -- docs/api/re/melange/Stdlib-Unit.md | 36 - .../melange/Stdlib-Weak-Make-argument-1-H.md | 21 - docs/api/re/melange/Stdlib-Weak-Make.md | 90 - .../re/melange/Stdlib-Weak-module-type-S.md | 81 - docs/api/re/melange/Stdlib-Weak.md | 88 - docs/api/re/melange/Stdlib.md | 1565 ----------------- 416 files changed, 66138 deletions(-) delete mode 100644 docs/api/ml/melange/Belt-Array.md delete mode 100644 docs/api/ml/melange/Belt-Float.md delete mode 100644 docs/api/ml/melange/Belt-HashMap-Int.md delete mode 100644 docs/api/ml/melange/Belt-HashMap-String.md delete mode 100644 docs/api/ml/melange/Belt-HashMap.md delete mode 100644 docs/api/ml/melange/Belt-HashSet-Int.md delete mode 100644 docs/api/ml/melange/Belt-HashSet-String.md delete mode 100644 docs/api/ml/melange/Belt-HashSet.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeComparable-argument-1-M.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeComparable.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeComparableU-argument-1-M.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeComparableU.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeHashable-argument-1-M.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeHashable.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeHashableU-argument-1-M.md delete mode 100644 docs/api/ml/melange/Belt-Id-MakeHashableU.md delete mode 100644 docs/api/ml/melange/Belt-Id-module-type-Comparable.md delete mode 100644 docs/api/ml/melange/Belt-Id-module-type-Hashable.md delete mode 100644 docs/api/ml/melange/Belt-Id.md delete mode 100644 docs/api/ml/melange/Belt-Int.md delete mode 100644 docs/api/ml/melange/Belt-List.md delete mode 100644 docs/api/ml/melange/Belt-Map-Dict.md delete mode 100644 docs/api/ml/melange/Belt-Map-Int.md delete mode 100644 docs/api/ml/melange/Belt-Map-String.md delete mode 100644 docs/api/ml/melange/Belt-Map.md delete mode 100644 docs/api/ml/melange/Belt-MutableMap-Int.md delete mode 100644 docs/api/ml/melange/Belt-MutableMap-String.md delete mode 100644 docs/api/ml/melange/Belt-MutableMap.md delete mode 100644 docs/api/ml/melange/Belt-MutableQueue.md delete mode 100644 docs/api/ml/melange/Belt-MutableSet-Int.md delete mode 100644 docs/api/ml/melange/Belt-MutableSet-String.md delete mode 100644 docs/api/ml/melange/Belt-MutableSet.md delete mode 100644 docs/api/ml/melange/Belt-MutableStack.md delete mode 100644 docs/api/ml/melange/Belt-Option.md delete mode 100644 docs/api/ml/melange/Belt-Range.md delete mode 100644 docs/api/ml/melange/Belt-Result.md delete mode 100644 docs/api/ml/melange/Belt-Set-Dict.md delete mode 100644 docs/api/ml/melange/Belt-Set-Int.md delete mode 100644 docs/api/ml/melange/Belt-Set-String.md delete mode 100644 docs/api/ml/melange/Belt-Set.md delete mode 100644 docs/api/ml/melange/Belt-SortArray-Int.md delete mode 100644 docs/api/ml/melange/Belt-SortArray-String.md delete mode 100644 docs/api/ml/melange/Belt-SortArray.md delete mode 100644 docs/api/ml/melange/Belt.md delete mode 100644 docs/api/ml/melange/Dom-Storage.md delete mode 100644 docs/api/ml/melange/Dom.md delete mode 100644 docs/api/ml/melange/Js-Array.md delete mode 100644 docs/api/ml/melange/Js-Bigint.md delete mode 100644 docs/api/ml/melange/Js-Blob.md delete mode 100644 docs/api/ml/melange/Js-Console.md delete mode 100644 docs/api/ml/melange/Js-Date.md delete mode 100644 docs/api/ml/melange/Js-Dict.md delete mode 100644 docs/api/ml/melange/Js-Exn.md delete mode 100644 docs/api/ml/melange/Js-File.md delete mode 100644 docs/api/ml/melange/Js-Float.md delete mode 100644 docs/api/ml/melange/Js-FormData.md delete mode 100644 docs/api/ml/melange/Js-Global.md delete mode 100644 docs/api/ml/melange/Js-Int.md delete mode 100644 docs/api/ml/melange/Js-Iterator.md delete mode 100644 docs/api/ml/melange/Js-Json.md delete mode 100644 docs/api/ml/melange/Js-Map.md delete mode 100644 docs/api/ml/melange/Js-Math.md delete mode 100644 docs/api/ml/melange/Js-Null.md delete mode 100644 docs/api/ml/melange/Js-Nullable.md delete mode 100644 docs/api/ml/melange/Js-Obj.md delete mode 100644 docs/api/ml/melange/Js-Promise.md delete mode 100644 docs/api/ml/melange/Js-Re.md delete mode 100644 docs/api/ml/melange/Js-Set.md delete mode 100644 docs/api/ml/melange/Js-String.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-ArrayBuffer.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-DataView.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Float32Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Float64Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Int16Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Int32Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Int8Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Uint16Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Uint32Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Uint8Array.md delete mode 100644 docs/api/ml/melange/Js-Typed_array-Uint8ClampedArray.md delete mode 100644 docs/api/ml/melange/Js-Typed_array.md delete mode 100644 docs/api/ml/melange/Js-Types.md delete mode 100644 docs/api/ml/melange/Js-Undefined.md delete mode 100644 docs/api/ml/melange/Js-WeakMap.md delete mode 100644 docs/api/ml/melange/Js-WeakSet.md delete mode 100644 docs/api/ml/melange/Js.md delete mode 100644 docs/api/ml/melange/Node-Buffer.md delete mode 100644 docs/api/ml/melange/Node-Child_process.md delete mode 100644 docs/api/ml/melange/Node-Fs-Watch.md delete mode 100644 docs/api/ml/melange/Node-Fs.md delete mode 100644 docs/api/ml/melange/Node-Module.md delete mode 100644 docs/api/ml/melange/Node-Path.md delete mode 100644 docs/api/ml/melange/Node-Process.md delete mode 100644 docs/api/ml/melange/Node.md delete mode 100644 docs/api/ml/melange/Stdlib-Arg.md delete mode 100644 docs/api/ml/melange/Stdlib-Array.md delete mode 100644 docs/api/ml/melange/Stdlib-ArrayLabels.md delete mode 100644 docs/api/ml/melange/Stdlib-Atomic.md delete mode 100644 docs/api/ml/melange/Stdlib-Bool.md delete mode 100644 docs/api/ml/melange/Stdlib-Buffer.md delete mode 100644 docs/api/ml/melange/Stdlib-Bytes.md delete mode 100644 docs/api/ml/melange/Stdlib-BytesLabels.md delete mode 100644 docs/api/ml/melange/Stdlib-Char.md delete mode 100644 docs/api/ml/melange/Stdlib-Complex.md delete mode 100644 docs/api/ml/melange/Stdlib-Digest-BLAKE128.md delete mode 100644 docs/api/ml/melange/Stdlib-Digest-BLAKE256.md delete mode 100644 docs/api/ml/melange/Stdlib-Digest-BLAKE512.md delete mode 100644 docs/api/ml/melange/Stdlib-Digest-MD5.md delete mode 100644 docs/api/ml/melange/Stdlib-Digest-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-Digest.md delete mode 100644 docs/api/ml/melange/Stdlib-Domain-DLS.md delete mode 100644 docs/api/ml/melange/Stdlib-Domain.md delete mode 100644 docs/api/ml/melange/Stdlib-Dynarray.md delete mode 100644 docs/api/ml/melange/Stdlib-Either.md delete mode 100644 docs/api/ml/melange/Stdlib-Filename.md delete mode 100644 docs/api/ml/melange/Stdlib-Float-Array.md delete mode 100644 docs/api/ml/melange/Stdlib-Float.md delete mode 100644 docs/api/ml/melange/Stdlib-Format.md delete mode 100644 docs/api/ml/melange/Stdlib-Fun.md delete mode 100644 docs/api/ml/melange/Stdlib-Gc-Memprof.md delete mode 100644 docs/api/ml/melange/Stdlib-Gc.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-Make-argument-1-H.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-module-type-HashedType.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededS.md delete mode 100644 docs/api/ml/melange/Stdlib-Hashtbl.md delete mode 100644 docs/api/ml/melange/Stdlib-In_channel.md delete mode 100644 docs/api/ml/melange/Stdlib-Int.md delete mode 100644 docs/api/ml/melange/Stdlib-Int32.md delete mode 100644 docs/api/ml/melange/Stdlib-Int64.md delete mode 100644 docs/api/ml/melange/Stdlib-LargeFile.md delete mode 100644 docs/api/ml/melange/Stdlib-Lazy.md delete mode 100644 docs/api/ml/melange/Stdlib-Lexing.md delete mode 100644 docs/api/ml/melange/Stdlib-List.md delete mode 100644 docs/api/ml/melange/Stdlib-ListLabels.md delete mode 100644 docs/api/ml/melange/Stdlib-Map-Make-argument-1-Ord.md delete mode 100644 docs/api/ml/melange/Stdlib-Map-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-Map-module-type-OrderedType.md delete mode 100644 docs/api/ml/melange/Stdlib-Map-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-Map.md delete mode 100644 docs/api/ml/melange/Stdlib-Marshal.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Map-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Map.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Set-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels-Set.md delete mode 100644 docs/api/ml/melange/Stdlib-MoreLabels.md delete mode 100644 docs/api/ml/melange/Stdlib-Mutex.md delete mode 100644 docs/api/ml/melange/Stdlib-Obj-Ephemeron.md delete mode 100644 docs/api/ml/melange/Stdlib-Obj-Extension_constructor.md delete mode 100644 docs/api/ml/melange/Stdlib-Obj.md delete mode 100644 docs/api/ml/melange/Stdlib-Oo.md delete mode 100644 docs/api/ml/melange/Stdlib-Option.md delete mode 100644 docs/api/ml/melange/Stdlib-Out_channel.md delete mode 100644 docs/api/ml/melange/Stdlib-Parsing.md delete mode 100644 docs/api/ml/melange/Stdlib-Printexc-Slot.md delete mode 100644 docs/api/ml/melange/Stdlib-Printexc.md delete mode 100644 docs/api/ml/melange/Stdlib-Printf.md delete mode 100644 docs/api/ml/melange/Stdlib-Queue.md delete mode 100644 docs/api/ml/melange/Stdlib-Random-State.md delete mode 100644 docs/api/ml/melange/Stdlib-Random.md delete mode 100644 docs/api/ml/melange/Stdlib-Result.md delete mode 100644 docs/api/ml/melange/Stdlib-Scanf-Scanning.md delete mode 100644 docs/api/ml/melange/Stdlib-Scanf.md delete mode 100644 docs/api/ml/melange/Stdlib-Seq.md delete mode 100644 docs/api/ml/melange/Stdlib-Set-Make-argument-1-Ord.md delete mode 100644 docs/api/ml/melange/Stdlib-Set-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-Set-module-type-OrderedType.md delete mode 100644 docs/api/ml/melange/Stdlib-Set-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-Set.md delete mode 100644 docs/api/ml/melange/Stdlib-Stack.md delete mode 100644 docs/api/ml/melange/Stdlib-StdLabels.md delete mode 100644 docs/api/ml/melange/Stdlib-String.md delete mode 100644 docs/api/ml/melange/Stdlib-StringLabels.md delete mode 100644 docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md delete mode 100644 docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md delete mode 100644 docs/api/ml/melange/Stdlib-Sys-Immediate64-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md delete mode 100644 docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md delete mode 100644 docs/api/ml/melange/Stdlib-Sys-Immediate64.md delete mode 100644 docs/api/ml/melange/Stdlib-Sys.md delete mode 100644 docs/api/ml/melange/Stdlib-Type-Id.md delete mode 100644 docs/api/ml/melange/Stdlib-Type.md delete mode 100644 docs/api/ml/melange/Stdlib-Uchar.md delete mode 100644 docs/api/ml/melange/Stdlib-Unit.md delete mode 100644 docs/api/ml/melange/Stdlib-Weak-Make-argument-1-H.md delete mode 100644 docs/api/ml/melange/Stdlib-Weak-Make.md delete mode 100644 docs/api/ml/melange/Stdlib-Weak-module-type-S.md delete mode 100644 docs/api/ml/melange/Stdlib-Weak.md delete mode 100644 docs/api/ml/melange/Stdlib.md delete mode 100644 docs/api/re/melange/Belt-Array.md delete mode 100644 docs/api/re/melange/Belt-Float.md delete mode 100644 docs/api/re/melange/Belt-HashMap-Int.md delete mode 100644 docs/api/re/melange/Belt-HashMap-String.md delete mode 100644 docs/api/re/melange/Belt-HashMap.md delete mode 100644 docs/api/re/melange/Belt-HashSet-Int.md delete mode 100644 docs/api/re/melange/Belt-HashSet-String.md delete mode 100644 docs/api/re/melange/Belt-HashSet.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeComparable.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeComparableU.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeHashable.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md delete mode 100644 docs/api/re/melange/Belt-Id-MakeHashableU.md delete mode 100644 docs/api/re/melange/Belt-Id-module-type-Comparable.md delete mode 100644 docs/api/re/melange/Belt-Id-module-type-Hashable.md delete mode 100644 docs/api/re/melange/Belt-Id.md delete mode 100644 docs/api/re/melange/Belt-Int.md delete mode 100644 docs/api/re/melange/Belt-List.md delete mode 100644 docs/api/re/melange/Belt-Map-Dict.md delete mode 100644 docs/api/re/melange/Belt-Map-Int.md delete mode 100644 docs/api/re/melange/Belt-Map-String.md delete mode 100644 docs/api/re/melange/Belt-Map.md delete mode 100644 docs/api/re/melange/Belt-MutableMap-Int.md delete mode 100644 docs/api/re/melange/Belt-MutableMap-String.md delete mode 100644 docs/api/re/melange/Belt-MutableMap.md delete mode 100644 docs/api/re/melange/Belt-MutableQueue.md delete mode 100644 docs/api/re/melange/Belt-MutableSet-Int.md delete mode 100644 docs/api/re/melange/Belt-MutableSet-String.md delete mode 100644 docs/api/re/melange/Belt-MutableSet.md delete mode 100644 docs/api/re/melange/Belt-MutableStack.md delete mode 100644 docs/api/re/melange/Belt-Option.md delete mode 100644 docs/api/re/melange/Belt-Range.md delete mode 100644 docs/api/re/melange/Belt-Result.md delete mode 100644 docs/api/re/melange/Belt-Set-Dict.md delete mode 100644 docs/api/re/melange/Belt-Set-Int.md delete mode 100644 docs/api/re/melange/Belt-Set-String.md delete mode 100644 docs/api/re/melange/Belt-Set.md delete mode 100644 docs/api/re/melange/Belt-SortArray-Int.md delete mode 100644 docs/api/re/melange/Belt-SortArray-String.md delete mode 100644 docs/api/re/melange/Belt-SortArray.md delete mode 100644 docs/api/re/melange/Belt.md delete mode 100644 docs/api/re/melange/Dom-Storage.md delete mode 100644 docs/api/re/melange/Dom.md delete mode 100644 docs/api/re/melange/Js-Array.md delete mode 100644 docs/api/re/melange/Js-Bigint.md delete mode 100644 docs/api/re/melange/Js-Blob.md delete mode 100644 docs/api/re/melange/Js-Console.md delete mode 100644 docs/api/re/melange/Js-Date.md delete mode 100644 docs/api/re/melange/Js-Dict.md delete mode 100644 docs/api/re/melange/Js-Exn.md delete mode 100644 docs/api/re/melange/Js-File.md delete mode 100644 docs/api/re/melange/Js-Float.md delete mode 100644 docs/api/re/melange/Js-FormData.md delete mode 100644 docs/api/re/melange/Js-Global.md delete mode 100644 docs/api/re/melange/Js-Int.md delete mode 100644 docs/api/re/melange/Js-Iterator.md delete mode 100644 docs/api/re/melange/Js-Json.md delete mode 100644 docs/api/re/melange/Js-Map.md delete mode 100644 docs/api/re/melange/Js-Math.md delete mode 100644 docs/api/re/melange/Js-Null.md delete mode 100644 docs/api/re/melange/Js-Nullable.md delete mode 100644 docs/api/re/melange/Js-Obj.md delete mode 100644 docs/api/re/melange/Js-Promise.md delete mode 100644 docs/api/re/melange/Js-Re.md delete mode 100644 docs/api/re/melange/Js-Set.md delete mode 100644 docs/api/re/melange/Js-String.md delete mode 100644 docs/api/re/melange/Js-Typed_array-ArrayBuffer.md delete mode 100644 docs/api/re/melange/Js-Typed_array-DataView.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Float32Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Float64Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Int16Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Int32Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Int8Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Uint16Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Uint32Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Uint8Array.md delete mode 100644 docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md delete mode 100644 docs/api/re/melange/Js-Typed_array.md delete mode 100644 docs/api/re/melange/Js-Types.md delete mode 100644 docs/api/re/melange/Js-Undefined.md delete mode 100644 docs/api/re/melange/Js-WeakMap.md delete mode 100644 docs/api/re/melange/Js-WeakSet.md delete mode 100644 docs/api/re/melange/Js.md delete mode 100644 docs/api/re/melange/Node-Buffer.md delete mode 100644 docs/api/re/melange/Node-Child_process.md delete mode 100644 docs/api/re/melange/Node-Fs-Watch.md delete mode 100644 docs/api/re/melange/Node-Fs.md delete mode 100644 docs/api/re/melange/Node-Module.md delete mode 100644 docs/api/re/melange/Node-Path.md delete mode 100644 docs/api/re/melange/Node-Process.md delete mode 100644 docs/api/re/melange/Node.md delete mode 100644 docs/api/re/melange/Stdlib-Arg.md delete mode 100644 docs/api/re/melange/Stdlib-Array.md delete mode 100644 docs/api/re/melange/Stdlib-ArrayLabels.md delete mode 100644 docs/api/re/melange/Stdlib-Atomic.md delete mode 100644 docs/api/re/melange/Stdlib-Bool.md delete mode 100644 docs/api/re/melange/Stdlib-Buffer.md delete mode 100644 docs/api/re/melange/Stdlib-Bytes.md delete mode 100644 docs/api/re/melange/Stdlib-BytesLabels.md delete mode 100644 docs/api/re/melange/Stdlib-Char.md delete mode 100644 docs/api/re/melange/Stdlib-Complex.md delete mode 100644 docs/api/re/melange/Stdlib-Digest-BLAKE128.md delete mode 100644 docs/api/re/melange/Stdlib-Digest-BLAKE256.md delete mode 100644 docs/api/re/melange/Stdlib-Digest-BLAKE512.md delete mode 100644 docs/api/re/melange/Stdlib-Digest-MD5.md delete mode 100644 docs/api/re/melange/Stdlib-Digest-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-Digest.md delete mode 100644 docs/api/re/melange/Stdlib-Domain-DLS.md delete mode 100644 docs/api/re/melange/Stdlib-Domain.md delete mode 100644 docs/api/re/melange/Stdlib-Dynarray.md delete mode 100644 docs/api/re/melange/Stdlib-Either.md delete mode 100644 docs/api/re/melange/Stdlib-Filename.md delete mode 100644 docs/api/re/melange/Stdlib-Float-Array.md delete mode 100644 docs/api/re/melange/Stdlib-Float.md delete mode 100644 docs/api/re/melange/Stdlib-Format.md delete mode 100644 docs/api/re/melange/Stdlib-Fun.md delete mode 100644 docs/api/re/melange/Stdlib-Gc-Memprof.md delete mode 100644 docs/api/re/melange/Stdlib-Gc.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-Make.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md delete mode 100644 docs/api/re/melange/Stdlib-Hashtbl.md delete mode 100644 docs/api/re/melange/Stdlib-In_channel.md delete mode 100644 docs/api/re/melange/Stdlib-Int.md delete mode 100644 docs/api/re/melange/Stdlib-Int32.md delete mode 100644 docs/api/re/melange/Stdlib-Int64.md delete mode 100644 docs/api/re/melange/Stdlib-LargeFile.md delete mode 100644 docs/api/re/melange/Stdlib-Lazy.md delete mode 100644 docs/api/re/melange/Stdlib-Lexing.md delete mode 100644 docs/api/re/melange/Stdlib-List.md delete mode 100644 docs/api/re/melange/Stdlib-ListLabels.md delete mode 100644 docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md delete mode 100644 docs/api/re/melange/Stdlib-Map-Make.md delete mode 100644 docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md delete mode 100644 docs/api/re/melange/Stdlib-Map-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-Map.md delete mode 100644 docs/api/re/melange/Stdlib-Marshal.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Map.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels-Set.md delete mode 100644 docs/api/re/melange/Stdlib-MoreLabels.md delete mode 100644 docs/api/re/melange/Stdlib-Mutex.md delete mode 100644 docs/api/re/melange/Stdlib-Obj-Ephemeron.md delete mode 100644 docs/api/re/melange/Stdlib-Obj-Extension_constructor.md delete mode 100644 docs/api/re/melange/Stdlib-Obj.md delete mode 100644 docs/api/re/melange/Stdlib-Oo.md delete mode 100644 docs/api/re/melange/Stdlib-Option.md delete mode 100644 docs/api/re/melange/Stdlib-Out_channel.md delete mode 100644 docs/api/re/melange/Stdlib-Parsing.md delete mode 100644 docs/api/re/melange/Stdlib-Printexc-Slot.md delete mode 100644 docs/api/re/melange/Stdlib-Printexc.md delete mode 100644 docs/api/re/melange/Stdlib-Printf.md delete mode 100644 docs/api/re/melange/Stdlib-Queue.md delete mode 100644 docs/api/re/melange/Stdlib-Random-State.md delete mode 100644 docs/api/re/melange/Stdlib-Random.md delete mode 100644 docs/api/re/melange/Stdlib-Result.md delete mode 100644 docs/api/re/melange/Stdlib-Scanf-Scanning.md delete mode 100644 docs/api/re/melange/Stdlib-Scanf.md delete mode 100644 docs/api/re/melange/Stdlib-Seq.md delete mode 100644 docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md delete mode 100644 docs/api/re/melange/Stdlib-Set-Make.md delete mode 100644 docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md delete mode 100644 docs/api/re/melange/Stdlib-Set-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-Set.md delete mode 100644 docs/api/re/melange/Stdlib-Stack.md delete mode 100644 docs/api/re/melange/Stdlib-StdLabels.md delete mode 100644 docs/api/re/melange/Stdlib-String.md delete mode 100644 docs/api/re/melange/Stdlib-StringLabels.md delete mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md delete mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md delete mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md delete mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md delete mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md delete mode 100644 docs/api/re/melange/Stdlib-Sys-Immediate64.md delete mode 100644 docs/api/re/melange/Stdlib-Sys.md delete mode 100644 docs/api/re/melange/Stdlib-Type-Id.md delete mode 100644 docs/api/re/melange/Stdlib-Type.md delete mode 100644 docs/api/re/melange/Stdlib-Uchar.md delete mode 100644 docs/api/re/melange/Stdlib-Unit.md delete mode 100644 docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md delete mode 100644 docs/api/re/melange/Stdlib-Weak-Make.md delete mode 100644 docs/api/re/melange/Stdlib-Weak-module-type-S.md delete mode 100644 docs/api/re/melange/Stdlib-Weak.md delete mode 100644 docs/api/re/melange/Stdlib.md diff --git a/docs/api/ml/melange/Belt-Array.md b/docs/api/ml/melange/Belt-Array.md deleted file mode 100644 index 31970e565..000000000 --- a/docs/api/ml/melange/Belt-Array.md +++ /dev/null @@ -1,654 +0,0 @@ - -# Module `Belt.Array` - -[`Belt.Array`](#) - -**mutable array**: Utilities functions - -[`Belt.Array`](#) Utililites for Array functions - -``` -type 'a t = 'a array -``` -``` -val length : 'a t -> int -``` -`length xs` return the size of the array - -``` -val size : 'a t -> int -``` -**See** [`length`](./#val-length) - -``` -val get : 'a t -> int -> 'a option -``` -`get arr i` - -If `i <= 0 <= length arr`;returns `Some value` where `value` is the item at index `i` If `i` is out of range;returns `None` - -```ocaml - Belt.Array.get [|"a";"b";"c"|] 0 = Some "a";; - Belt.Array.get [|"a";"b";"c"|] 3 = None;; - Belt.Array.get [|"a";"b";"c"|] (-1) = None;; -``` -``` -val getExn : 'a t -> int -> 'a -``` -`getExn arr i` - -**raise** an exception if `i` is out of range;otherwise return the value at index `i` in `arr` - -``` -val getUnsafe : 'a t -> int -> 'a -``` -`getUnsafe arr i` - -**Unsafe** - -no bounds checking;this would cause type error if `i` does not stay within range - -``` -val getUndefined : 'a t -> int -> 'a Js.undefined -``` -`getUndefined arr i` - -It does the samething in the runtime as [`getUnsafe`](./#val-getUnsafe); it is *type safe* since the return type still track whether it is in range or not - -``` -val set : 'a t -> int -> 'a -> bool -``` -`set arr n x` modifies `arr` in place; it replaces the nth element of `arr` with `x` - -returns false means not updated due to out of range -``` -val setExn : 'a t -> int -> 'a -> unit -``` -`setExn arr i x` **raise** an exception if `i` is out of range - -``` -val setUnsafe : 'a t -> int -> 'a -> unit -``` -``` -val shuffleInPlace : 'a t -> unit -``` -`shuffleInPlace arr` randomly re-orders the items in `arr` - -``` -val shuffle : 'a t -> 'a t -``` -`shuffle xs` - -returns a fresh array with items in original array randomly shuffled -``` -val reverseInPlace : 'a t -> unit -``` -`reverseInPlace arr` reverses items in `arr` in place - -```ocaml - let arr = [|10;11;12;13;14|];; - let () = reverseInPlace arr;; - arr = [|14;13;12;11;10|];; -``` -``` -val reverse : 'a t -> 'a t -``` -`reverse arr` - -returns a fresh array with items in arr in reverse order -```ocaml - reverse [|10;11;12;13;14|] = [|14;13;12;11;10|];; -``` -``` -val makeUninitialized : int -> 'a Js.undefined array -``` -`makeUninitialized n` creates an array of length `n` filled with the undefined value. You must specify the type of data that will eventually fill the array. - -```ocaml - let arr: string Js.undefined array = makeUninitialized 5;; - getExn arr 0 = Js.undefined;; -``` -``` -val makeUninitializedUnsafe : int -> 'a t -``` -\`makeUninitializedUnsafe n\` - -**Unsafe** - -```ocaml -let arr = Belt.Array.makeUninitializedUnsafe 5;; -let () = Js.log(Belt.Array.getExn arr 0);; (* undefined *) -Belt.Array.setExn arr 0 "example";; -let () = Js.log(Belt.Array.getExn arr 0 = "example");; -``` -``` -val make : int -> 'a -> 'a t -``` -`make n e` return an array of size `n` filled with value `e` - -returns an empty array when n is negative. -``` -val range : int -> int -> int t -``` -`range start finish` create an inclusive array - -```ocaml - range 0 3 = [|0;1;2;3|];; - range 3 0 = [||] ;; - range 3 3 = [|3|];; -``` -``` -val rangeBy : int -> int -> step:int -> int t -``` -`rangeBy start finish ~step` - -returns empty array when step is 0 or negative it also return empty array when start \> finish -```ocaml - rangeBy 0 10 ~step:3 = [|0;3;6;9|];; - rangeBy 0 12 ~step:3 = [|0;3;6;9;12|];; - rangeBy 33 0 ~step:1 = [||];; - rangeBy 33 0 ~step:(-1) = [||];; - rangeBy 3 12 ~step:(-1) = [||];; - rangeBy 3 3 ~step:0 = [||] ;; - rangeBy 3 3 ~step:(1) = [|3|] ;; -``` -``` -val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val makeBy : int -> (int -> 'a) -> 'a t -``` -`makeBy n f` - -return an empty array when `n` is negative return an array of size `n` populated by `f i` start from `0` to `n - 1` - -```ocaml - makeBy 5 (fun i -> i) = [|0;1;2;3;4|];; - makeBy 5 (fun i -> i * i) = [|0;1;4;9;16|] -``` -``` -val makeByAndShuffleU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val makeByAndShuffle : int -> (int -> 'a) -> 'a t -``` -`makeByAndShuffle n f` - -Equivalent to `shuffle (makeBy n f)` - -``` -val zip : 'a t -> 'b array -> ('a * 'b) array -``` -`zip a b` - -Create an array of pairs from corresponding elements of `a` and `b`. Stop with the shorter array - -```ocaml - zip [|1;2|] [|3;4;5|] = [|(1, 3);(2, 4)|] -``` -``` -val zipByU : 'a t -> 'b array -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c array -``` -``` -val zipBy : 'a t -> 'b array -> ('a -> 'b -> 'c) -> 'c array -``` -`zipBy xs ys f` - -Create an array by applying `f` to corresponding elements of `xs` and `ys` Stops with shorter array - -Equivalent to `map (zip xs ys) (fun (a,b) -> f a b) ` - -```ocaml - zipBy [|1;2;3|] [|4;5|] (fun a b -> 2 * a + b) = [|6;9|];; -``` -``` -val unzip : ('a * 'b) array -> 'a t * 'b array -``` -`unzip a` takes an array of pairs and creates a pair of arrays. The first array contains all the first items of the pairs; the second array contains all the second items. - -```ocaml - unzip [|(1,2) ; (3,4)|] = ([|1;3|], [|2;4|]);; - unzip [|(1,2) ; (3,4) ; (5,6) ; (7,8)|] = ([|1;3;5;7|], [|2;4;6;8|]);; -``` -``` -val concat : 'a t -> 'a t -> 'a t -``` -`concat xs ys` - -returns a fresh array containing the concatenation of the arrays v1 and v2;so even if v1 or v2 is empty;it can not be shared -```ocaml - concat [|1;2;3|] [|4;5|] = [|1;2;3;4;5|];; - concat [| |] [|"a";"b";"c"|] = [|"a";"b";"c"|];; -``` -``` -val concatMany : 'a t t -> 'a t -``` -`concatMany xss` - -returns a fresh array as the concatenation of xss (an array of arrays) -```ocaml - concatMany [| [|1;2;3|]; [|4;5;6|]; [|7;8|] |] = [|1;2;3;4;5;6;7;8|];; -``` -``` -val slice : 'a t -> offset:int -> len:int -> 'a t -``` -`slice xs offset len` creates a new array with the `len` elements of `xs` starting at `offset` for - -`offset` can be negative;and is evaluated as `length xs - offset` `slice xs -1 1` means get the last element as a singleton array - -`slice xs (-len) len` will return a copy of the array - -if the array does not have enough data;`slice` extracts through the end of sequence. - -if `len` is negative;returns the empty array. - -```ocaml - slice [|10;11;12;13;14;15;16|] ~offset: 2 ~len: 3 = [|12;13;14|];; - slice [|10;11;12;13;14;15;16|] ~offset: (-4) ~len: 3 = [|13;14;15|];; - slice [|10;11;12;13;14;15;16|] ~offset:4 ~len:9 = [|14;15;16|];; -``` -``` -val sliceToEnd : 'a t -> int -> 'a t -``` -`sliceToEnd xs offset` creates a new array with the elements of `xs` starting at `offset` - -`offset` can be negative;and is evaluated as `length xs - offset` `sliceToEnd xs -1` means get the last element as a singleton array - -`sliceToEnd xs 0` will return a copy of the array - -```ocaml - sliceToEnd [|10;11;12;13;14;15;16|] 2 = [|12;13;14;15;16|];; - sliceToEnd [|10;11;12;13;14;15;16|] (-4) = [|13;14;15;16|];; -``` -``` -val copy : 'a t -> 'a t -``` -`copy a` - -returns a copy of a;that is;a fresh array containing the same elements as a. -``` -val fill : 'a t -> offset:int -> len:int -> 'a -> unit -``` -`fill arr ~offset ~len x` - -Modifies `arr` in place, storing `x` in elements number `offset` to `offset + len - 1`. - -`offset` can be negative;and is evaluated as `length arr - offset` - -`fill arr ~offset:(-1) ~len:1` means fill the last element, if the array does not have enough data;`fill` will ignore it - -```ocaml - - let arr = makeBy 5 (fun i -> i) ;; - fill arr ~offset:2 ~len:2 9 ;; - arr = [|0;1;9;9;4|];; - fill arr ~offset:7 ~len:2 8;; - arr = [|0;1;9;9;4|];; -``` -``` -val blit : - src:'a t -> - srcOffset:int -> - dst:'a t -> - dstOffset:int -> - len:int -> - unit -``` -`blit ~src:v1 ~srcOffset:o1 ~dst:v2 ~dstOffset:o2 ~len` - -copies `len` elements from array `v1`;starting at element number `o1`;to array `v2`, starting at element number `o2`. - -It works correctly even if `v1` and `v2` are the same array;and the source and destination chunks overlap. - -`offset` can be negative;`-1` means `len - 1`;if `len + offset` is still negative;it will be set as 0 - -For each of the examples;presume that `v1 = [|10;11;12;13;14;15;16;17|]` and `v2 = [|20;21;22;23;24;25;26;27|]`. The result shown is the content of the destination array. - -```ocaml - Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v2 ~dstOffset: 2 ~len: 3 |. - [|20;21;14;15;16;25;26;27|] - Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v1 ~dstOffset: 2 ~len: 3 |. - [|10;11;14;15;16;15;16;17|] -``` -``` -val blitUnsafe : - src:'a t -> - srcOffset:int -> - dst:'a t -> - dstOffset:int -> - len:int -> - unit -``` -**Unsafe** blit without bounds checking - -``` -val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> unit) -> unit -``` -`forEach xs f` - -Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`;so no new array is created. Use `forEach` when you are primarily concerned with repetitively creating side effects. - -```ocaml - forEach [|"a";"b";"c"|] (fun x -> Js.log("Item: " ^ x));; - (* prints: - Item: a - Item: b - Item: c - *) - - let total = ref 0;; - forEach [|1;2;3;4|] (fun x -> total := !total + x);; - !total = 1 + 2 + 3 + 4;; - -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b array -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b array -``` -`map xs f ` - -returns a new array by calling f for each element of xs from the beginning to end -```ocaml - map [|1;2|] (fun x-> x + 10) = [|11;12|] -``` -``` -val flatMapU : 'a t -> ('a -> 'b t) Js.Fn.arity1 -> 'b t -``` -``` -val flatMap : 'a t -> ('a -> 'b t) -> 'b t -``` -`flatMap xs f` \*\*return\*\* a new array by calling \`f\` for each element of \`xs\` from the beginning to end, and then concatenating the results \``` flatMap `|1;2|` (fun x-\> `|x + 10;x + 20|`) \= `|11;21;12;22|` \``` - -``` -val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option -``` -``` -val getBy : 'a t -> ('a -> bool) -> 'a option -``` -`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. - -```ocaml - getBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 4 - getBy [|15;13;11|] (fun x -> x mod 2 = 0) = None -``` -``` -val getIndexByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> int option -``` -``` -val getIndexBy : 'a t -> ('a -> bool) -> int option -``` -`getIndexBy xs p` returns `Some index` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. - -```ocaml - getIndexBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 1 - getIndexBy [|15;13;11|] (fun x -> x mod 2 = 0) = None -``` -``` -val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t -``` -``` -val keep : 'a t -> ('a -> bool) -> 'a t -``` -`keep xs p ` - -returns a new array that keeps all elements satisfying p -```ocaml - keep [|1;2;3|] (fun x -> x mod 2 = 0) = [|2|] -``` -``` -val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t -``` -``` -val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t -``` -`keepWithIndex xs p ` - -returns a new array that keeps all elements satisfying p. The predicate p takes two arguments: the element from xs and the index starting from 0. -```ocaml - keepWithIndex [|1;2;3|] (fun _x i -> i = 1) = [|2|] -``` -``` -val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b array -``` -``` -val keepMap : 'a t -> ('a -> 'b option) -> 'b array -``` -`keepMap xs p` - -returns a new array that keeps all elements that return a non-None when applied to p -```ocaml - keepMap [|1;2;3|] (fun x -> if x mod 2 = 0 then Some x else None) - = [| 2 |] -``` -``` -val forEachWithIndexU : 'a t -> (int -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEachWithIndex : 'a t -> (int -> 'a -> unit) -> unit -``` -`forEachWithIndex xs f` - -The same as [`forEach`](./#val-forEach); except that `f` is supplied with two arguments: the index starting from 0 and the element from `xs` - -```ocaml - - forEachWithIndex [|"a";"b";"c"|] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; - (* prints: - Item 0 is a - Item 1 is b - Item 2 is c - *) - - let total = ref 0 ;; - forEachWithIndex [|10;11;12;13|] (fun i x -> total := !total + x + i);; - !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; -``` -``` -val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t -``` -`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. - -```ocaml - mapWithIndex [|1;2;3|] (fun i x -> i + x) = - [|0 + 1; 1 + 2; 2 + 3|] -``` -``` -val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t -``` -``` -val partition : 'a t -> ('a -> bool) -> 'a t * 'a t -``` -`partition f a` split array into tuple of two arrays based on predicate f; first of tuple where predicate cause true, second where predicate cause false - -```ocaml - partition [|1;2;3;4;5|] (fun x -> x mod 2 = 0 ) = ([|2;4|], [|1;2;3|]);; - partition [|1;2;3;4;5|] (fun x -> x mod 2 <> 0 ) = ([|1;2;3|], [|2;4|]);; -``` -``` -val reduceU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a -``` -`reduce xs init f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”;which starts with a value of `init`. `reduce` returns the final value of the accumulator. - -```ocaml - reduce [|2;3;4|] 1 (+) = 10;; - reduce [|"a";"b";"c";"d"|] "" (^) = "abcd";; -``` -``` -val reduceReverseU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduceReverse : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a -``` -`reduceReverse xs init f` - -Works like [`reduce`](./#val-reduce);except that function `f` is applied to each item of `xs` from the last back to the first. - -```ocaml - reduceReverse [|"a";"b";"c";"d"|] "" (^) = "dcba";; -``` -``` -val reduceReverse2U : - 'a t -> - 'b array -> - 'c -> - ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> - 'c -``` -``` -val reduceReverse2 : 'a t -> 'b array -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c -``` -`reduceReverse2 xs ys init f` Reduces two arrays `xs` and `ys`;taking items starting at `min (length xs) (length ys)` down to and including zero. - -```ocaml - reduceReverse2 [|1;2;3|] [|1;2|] 0 (fun acc x y -> acc + x + y) = 6 -``` -``` -val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b -``` -`reduceWithIndex xs f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the array and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. - -```ocaml - reduceWithIndex [|1;2;3;4|] 0 (fun acc x i -> acc + x + i) = 16; -``` -``` -val joinWithU : 'a t -> string -> ('a -> string) Js.Fn.arity1 -> string -``` -``` -val joinWith : 'a t -> string -> ('a -> string) -> string -``` -`joinWith xs sep toString` - -Concatenates all the elements of `xs` converted to string with `toString`, each separated by `sep`, the string given as the second argument, into a single string. If the array has only one element, then that element will be returned without using the separator. If the array is empty, the empty string will be returned. - -```ocaml - joinWith [|0; 1|] ", " string_of_int = "0, 1" - joinWith [||] " " string_of_int = "" - joinWith [|1|] " " string_of_int = "1" -``` -``` -val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : 'a t -> ('a -> bool) -> bool -``` -`some xs p` - -returns true if at least one of the elements in xs satifies p;where p is a predicate: a function taking an element and returning a bool. -```ocaml - some [|2; 3; 4|] (fun x -> x mod 2 = 1) = true;; - some [|-1; -3; -5|] (fun x -> x > 0) = false;; -``` -``` -val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : 'a t -> ('a -> bool) -> bool -``` -`every xs p` - -returns true if all elements satisfy p;where p is a predicate: a function taking an element and returning a bool. -```ocaml - every [|1; 3; 5|] (fun x -> x mod 2 = 1) = true;; - every [|1; -3; 5|] (fun x -> x > 0) = false;; -``` -``` -val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`every2 xs ys p` returns true if `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - every2 [|1;2;3|] [|0;1|] (>) = true;; - every2 [||] [|1|] (fun x y -> x > y) = true;; - every2 [|2;3|] [|1|] (fun x y -> x > y) = true;; - every2 [|0;1|] [|5;0|] (fun x y -> x > y) = false; -``` -``` -val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - some2 [|0;2|] [|1;0;3|] (>) = true ;; - (some2 [||] [|1|] (fun x y -> x > y)) = false;; - (some2 [|2;3|] [|1;4|] (fun x y -> x > y)) = true;; -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -`cmp xs ys f` - -- Compared by length if `length xs <> length ys`;returning \-1 if`length xs < length ys` or 1 if `length xs > length ys` -- Otherwise compare one by one `f x y`. `f` returns -- a negative number if `x` is “less than” `y` -- zero if `x` is “equal to” `y` -- a positive number if `x` is “greater than” `y` -- The comparison returns the first non-zero result of `f`;or zero if `f` returns zero for all `x` and `y`. -```ocaml - cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; - cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; - cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; -``` -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq xs ys` - -- return false if length is not the same -- otherwise compare items one by one using `f xi yi`;and return true if all results are true;false otherwise -```ocaml - eq [|1; 2; 3|] [|-1; -2; -3|] (fun a b -> abs a = abs b) = true -``` -``` -val truncateToLengthUnsafe : 'a t -> int -> unit -``` -**Unsafe** `truncateToLengthUnsafe xs n` sets length of array `xs` to `n`. - -If `n` is greater than the length of `xs`;the extra elements are set to `Js.Null_undefined.null` - -If `n` is less than zero;raises a `RangeError`. - -```ocaml - let arr = [|"ant";"bee";"cat";"dog";"elk"|];; - let () = truncateToLengthUnsafe arr 3;; - arr = [|"ant";"bee";"cat"|];; -``` -``` -val initU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val init : int -> (int -> 'a) -> 'a t -``` -``` -val push : 'a t -> 'a -> unit -``` -`arr->push(item)` push element \`item\` into the array diff --git a/docs/api/ml/melange/Belt-Float.md b/docs/api/ml/melange/Belt-Float.md deleted file mode 100644 index a05b382d7..000000000 --- a/docs/api/ml/melange/Belt-Float.md +++ /dev/null @@ -1,29 +0,0 @@ - -# Module `Belt.Float` - -[`Belt.Float`](#) Utililites for Float - -``` -val toInt : float -> int -``` -``` -val fromInt : int -> float -``` -``` -val fromString : string -> float option -``` -``` -val toString : float -> string -``` -``` -val (+) : float -> float -> float -``` -``` -val (-) : float -> float -> float -``` -``` -val (*) : float -> float -> float -``` -``` -val (/) : float -> float -> float -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-HashMap-Int.md b/docs/api/ml/melange/Belt-HashMap-Int.md deleted file mode 100644 index 46c1f54f7..000000000 --- a/docs/api/ml/melange/Belt-HashMap-Int.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `HashMap.Int` - -Specalized when key type is `int`, more efficient than the generic type - -``` -type key = int -``` -``` -type 'b t -``` -``` -val make : hintSize:int -> 'b t -``` -``` -val clear : 'b t -> unit -``` -``` -val isEmpty : _ t -> bool -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` - -``` -val copy : 'a t -> 'a t -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val has : 'b t -> key -> bool -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'b t -> (key -> 'b -> unit) -> unit -``` -``` -val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c -``` -``` -val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c -``` -``` -val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit -``` -``` -val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit -``` -``` -val size : _ t -> int -``` -``` -val toArray : 'a t -> (key * 'a) array -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val mergeMany : 'a t -> (key * 'a) array -> unit -``` -``` -val getBucketHistogram : _ t -> int array -``` -``` -val logStats : _ t -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-HashMap-String.md b/docs/api/ml/melange/Belt-HashMap-String.md deleted file mode 100644 index dc5e0eab3..000000000 --- a/docs/api/ml/melange/Belt-HashMap-String.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `HashMap.String` - -Specalized when key type is `string`, more efficient than the generic type - -``` -type key = string -``` -``` -type 'b t -``` -``` -val make : hintSize:int -> 'b t -``` -``` -val clear : 'b t -> unit -``` -``` -val isEmpty : _ t -> bool -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` - -``` -val copy : 'a t -> 'a t -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val has : 'b t -> key -> bool -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'b t -> (key -> 'b -> unit) -> unit -``` -``` -val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c -``` -``` -val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c -``` -``` -val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit -``` -``` -val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit -``` -``` -val size : _ t -> int -``` -``` -val toArray : 'a t -> (key * 'a) array -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val mergeMany : 'a t -> (key * 'a) array -> unit -``` -``` -val getBucketHistogram : _ t -> int array -``` -``` -val logStats : _ t -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-HashMap.md b/docs/api/ml/melange/Belt-HashMap.md deleted file mode 100644 index 0c0c8533e..000000000 --- a/docs/api/ml/melange/Belt-HashMap.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Belt.HashMap` - -[`Belt.HashMap`](#) - -The top level provides generic **mutable** hash map operations. - -It also has two specialized inner modules [`Belt.HashMap.Int`](./Belt-HashMap-Int.md) and [`Belt.HashMap.String`](./Belt-HashMap-String.md) - -A **mutable** Hash map which allows customized hash behavior. - -All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashMaps of ints* initialized with different *hash* functions will have different type. - -For example: - -```ocaml - type t = int - module I0 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s0 : (_, string,_) t = make ~hintSize:40 ~id:(module I0) - module I1 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s1 : (_, string,_) t = make ~hintSize:40 ~id:(module I1) -``` -The invariant must be held: for two elements who are *equal*, their hashed value should be the same - -Here the compiler would infer `s0` and `s1` having different type so that it would not mix. - -```ocaml - val s0 : (int, I0.identity) t - val s1 : (int, I1.identity) t -``` -We can add elements to the collection: - -```ocaml - - let () = - add s1 0 "3"; - add s1 1 "3" -``` -Since this is an mutable data strucure, `s1` will contain two pairs. - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -type ('key, 'value, 'id) t -``` -The type of hash tables from type `'key` to type `'value`. - -``` -type ('a, 'id) id = - (module Belt__.Belt_Id.Hashable - with type identity = 'id - and type t = 'a) -``` -``` -val make : hintSize:int -> id:('key, 'id) id -> ('key, 'value, 'id) t -``` -``` -val clear : ('key, 'value, 'id) t -> unit -``` -Empty a hash table. - -``` -val isEmpty : (_, _, _) t -> bool -``` -``` -val set : ('key, 'value, 'id) t -> 'key -> 'value -> unit -``` -`set tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` - -``` -val copy : ('key, 'value, 'id) t -> ('key, 'value, 'id) t -``` -``` -val get : ('key, 'value, 'id) t -> 'key -> 'value option -``` -``` -val has : ('key, 'value, 'id) t -> 'key -> bool -``` -`has tbl x` checks if `x` is bound in `tbl`. - -``` -val remove : ('key, 'value, 'id) t -> 'key -> unit -``` -``` -val forEachU : - ('key, 'value, 'id) t -> - ('key -> 'value -> unit) Js.Fn.arity2 -> - unit -``` -``` -val forEach : ('key, 'value, 'id) t -> ('key -> 'value -> unit) -> unit -``` -`forEach tbl f` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. - -``` -val reduceU : - ('key, 'value, 'id) t -> - 'c -> - ('c -> 'key -> 'value -> 'c) Js.Fn.arity3 -> - 'c -``` -``` -val reduce : ('key, 'value, 'id) t -> 'c -> ('c -> 'key -> 'value -> 'c) -> 'c -``` -`reduce tbl init f` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -``` -val keepMapInPlaceU : - ('key, 'value, 'id) t -> - ('key -> 'value -> 'value option) Js.Fn.arity2 -> - unit -``` -``` -val keepMapInPlace : - ('key, 'value, 'id) t -> - ('key -> 'value -> 'value option) -> - unit -``` -``` -val size : (_, _, _) t -> int -``` -`size tbl` returns the number of bindings in `tbl`. It takes constant time. - -``` -val toArray : ('key, 'value, 'id) t -> ('key * 'value) array -``` -``` -val keysToArray : ('key, _, _) t -> 'key array -``` -``` -val valuesToArray : (_, 'value, _) t -> 'value array -``` -``` -val fromArray : - ('key * 'value) array -> - id:('key, 'id) id -> - ('key, 'value, 'id) t -``` -``` -val mergeMany : ('key, 'value, 'id) t -> ('key * 'value) array -> unit -``` -``` -val getBucketHistogram : (_, _, _) t -> int array -``` -``` -val logStats : (_, _, _) t -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-HashSet-Int.md b/docs/api/ml/melange/Belt-HashSet-Int.md deleted file mode 100644 index e674b95e9..000000000 --- a/docs/api/ml/melange/Belt-HashSet-Int.md +++ /dev/null @@ -1,68 +0,0 @@ - -# Module `HashSet.Int` - -Specalized when key type is `int`, more efficient than the generic type - -This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.HashSet`](./Belt-HashSet.md) - -``` -type key = int -``` -``` -type t -``` -``` -val make : hintSize:int -> t -``` -``` -val clear : t -> unit -``` -``` -val isEmpty : t -> bool -``` -``` -val add : t -> key -> unit -``` -``` -val copy : t -> t -``` -``` -val has : t -> key -> bool -``` -``` -val remove : t -> key -> unit -``` -``` -val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (key -> unit) -> unit -``` -``` -val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c -``` -``` -val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c -``` -``` -val size : t -> int -``` -``` -val logStats : t -> unit -``` -``` -val toArray : t -> key array -``` -``` -val fromArray : key array -> t -``` -``` -val mergeMany : t -> key array -> unit -``` -``` -val getBucketHistogram : t -> int array -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-HashSet-String.md b/docs/api/ml/melange/Belt-HashSet-String.md deleted file mode 100644 index 299cc480d..000000000 --- a/docs/api/ml/melange/Belt-HashSet-String.md +++ /dev/null @@ -1,68 +0,0 @@ - -# Module `HashSet.String` - -Specalized when key type is `string`, more efficient than the generic type - -This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.HashSet`](./Belt-HashSet.md) - -``` -type key = string -``` -``` -type t -``` -``` -val make : hintSize:int -> t -``` -``` -val clear : t -> unit -``` -``` -val isEmpty : t -> bool -``` -``` -val add : t -> key -> unit -``` -``` -val copy : t -> t -``` -``` -val has : t -> key -> bool -``` -``` -val remove : t -> key -> unit -``` -``` -val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (key -> unit) -> unit -``` -``` -val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c -``` -``` -val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c -``` -``` -val size : t -> int -``` -``` -val logStats : t -> unit -``` -``` -val toArray : t -> key array -``` -``` -val fromArray : key array -> t -``` -``` -val mergeMany : t -> key array -> unit -``` -``` -val getBucketHistogram : t -> int array -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-HashSet.md b/docs/api/ml/melange/Belt-HashSet.md deleted file mode 100644 index 1f8647d50..000000000 --- a/docs/api/ml/melange/Belt-HashSet.md +++ /dev/null @@ -1,124 +0,0 @@ - -# Module `Belt.HashSet` - -[`Belt.HashSet`](#) - -The top level provides generic **mutable** hash set operations. - -It also has two specialized inner modules [`Belt.HashSet.Int`](./Belt-HashSet-Int.md) and [`Belt.HashSet.String`](./Belt-HashSet-String.md) - -A **mutable** Hash set which allows customized hash behavior. - -All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashSets of ints* initialized with different *hash* functions will have different type. - -For example: - -```ocaml - type t = int - module I0 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s0 = make ~id:(module I0) ~hintSize:40 - module I1 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s1 = make ~id:(module I1) ~hintSize:40 -``` -The invariant must be held: for two elements who are *equal*, their hashed value should be the same - -Here the compiler would infer `s0` and `s1` having different type so that it would not mix. - -```ocaml - val s0 : (int, I0.identity) t - val s1 : (int, I1.identity) t -``` -We can add elements to the collection: - -```ocaml - - let () = - add s1 0; - add s1 1 -``` -Since this is an mutable data strucure, `s1` will contain two pairs. - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -type ('a, 'id) t -``` -The type of hash tables from type `'a` to type `'b`. - -``` -type ('a, 'id) id = - (module Belt__.Belt_Id.Hashable - with type identity = 'id - and type t = 'a) -``` -``` -val make : hintSize:int -> id:('a, 'id) id -> ('a, 'id) t -``` -``` -val clear : ('a, 'id) t -> unit -``` -``` -val isEmpty : (_, _) t -> bool -``` -``` -val add : ('a, 'id) t -> 'a -> unit -``` -``` -val copy : ('a, 'id) t -> ('a, 'id) t -``` -``` -val has : ('a, 'id) t -> 'a -> bool -``` -``` -val remove : ('a, 'id) t -> 'a -> unit -``` -``` -val forEachU : ('a, 'id) t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('a, 'id) t -> ('a -> unit) -> unit -``` -Order unspecified. - -``` -val reduceU : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) Js.Fn.arity2 -> 'c -``` -``` -val reduce : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) -> 'c -``` -Order unspecified. - -``` -val size : ('a, 'id) t -> int -``` -``` -val logStats : (_, _) t -> unit -``` -``` -val toArray : ('a, 'id) t -> 'a array -``` -``` -val fromArray : 'a array -> id:('a, 'id) id -> ('a, 'id) t -``` -``` -val mergeMany : ('a, 'id) t -> 'a array -> unit -``` -``` -val getBucketHistogram : (_, _) t -> int array -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeComparable-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeComparable-argument-1-M.md deleted file mode 100644 index 7cdbeba8e..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeComparable-argument-1-M.md +++ /dev/null @@ -1,9 +0,0 @@ - -# Parameter `MakeComparable.M` - -``` -type t -``` -``` -val cmp : t -> t -> int -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeComparable.md b/docs/api/ml/melange/Belt-Id-MakeComparable.md deleted file mode 100644 index a4e124a8e..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeComparable.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Module `Id.MakeComparable` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val cmp : (t, identity) cmp -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeComparableU-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeComparableU-argument-1-M.md deleted file mode 100644 index 94b48d88a..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeComparableU-argument-1-M.md +++ /dev/null @@ -1,9 +0,0 @@ - -# Parameter `MakeComparableU.M` - -``` -type t -``` -``` -val cmp : (t -> t -> int) Js.Fn.arity2 -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeComparableU.md b/docs/api/ml/melange/Belt-Id-MakeComparableU.md deleted file mode 100644 index 6ade5dd1d..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeComparableU.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Module `Id.MakeComparableU` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val cmp : (t, identity) cmp -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeHashable-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeHashable-argument-1-M.md deleted file mode 100644 index 2ad08437b..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeHashable-argument-1-M.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `MakeHashable.M` - -``` -type t -``` -``` -val hash : t -> int -``` -``` -val eq : t -> t -> bool -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeHashable.md b/docs/api/ml/melange/Belt-Id-MakeHashable.md deleted file mode 100644 index 15f31e6d6..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeHashable.md +++ /dev/null @@ -1,24 +0,0 @@ - -# Module `Id.MakeHashable` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val hash : (t, identity) hash -``` -``` -val eq : (t, identity) eq -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeHashableU-argument-1-M.md b/docs/api/ml/melange/Belt-Id-MakeHashableU-argument-1-M.md deleted file mode 100644 index eb5a430a2..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeHashableU-argument-1-M.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `MakeHashableU.M` - -``` -type t -``` -``` -val hash : (t -> int) Js.Fn.arity1 -``` -``` -val eq : (t -> t -> bool) Js.Fn.arity2 -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-MakeHashableU.md b/docs/api/ml/melange/Belt-Id-MakeHashableU.md deleted file mode 100644 index a8834245f..000000000 --- a/docs/api/ml/melange/Belt-Id-MakeHashableU.md +++ /dev/null @@ -1,24 +0,0 @@ - -# Module `Id.MakeHashableU` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val hash : (t, identity) hash -``` -``` -val eq : (t, identity) eq -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-module-type-Comparable.md b/docs/api/ml/melange/Belt-Id-module-type-Comparable.md deleted file mode 100644 index 8f8f4244d..000000000 --- a/docs/api/ml/melange/Belt-Id-module-type-Comparable.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Module type `Id.Comparable` - -``` -type identity -``` -``` -type t -``` -``` -val cmp : (t, identity) cmp -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id-module-type-Hashable.md b/docs/api/ml/melange/Belt-Id-module-type-Hashable.md deleted file mode 100644 index 9758efeeb..000000000 --- a/docs/api/ml/melange/Belt-Id-module-type-Hashable.md +++ /dev/null @@ -1,15 +0,0 @@ - -# Module type `Id.Hashable` - -``` -type identity -``` -``` -type t -``` -``` -val hash : (t, identity) hash -``` -``` -val eq : (t, identity) eq -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Id.md b/docs/api/ml/melange/Belt-Id.md deleted file mode 100644 index d9072b719..000000000 --- a/docs/api/ml/melange/Belt-Id.md +++ /dev/null @@ -1,113 +0,0 @@ - -# Module `Belt.Id` - -[`Belt.Id`](#) - -Provide utilities to create identified comparators or hashes for data structures used below. - -It create a unique identifier per module of functions so that different data structures with slightly different comparison functions won't mix - -[`Belt.Id`](#) - -Provide utiliites to create identified comparators or hashes for data structures used below. - -It create a unique identifer per module of functions so that different data structures with slightly different comparison functions won't mix. - -``` -type ('a, 'id) hash -``` -`('a, 'id) hash` - -Its runtime represenation is a `hash` function, but signed with a type parameter, so that different hash functions type mismatch - -``` -type ('a, 'id) eq -``` -`('a, 'id) eq` - -Its runtime represenation is an `eq` function, but signed with a type parameter, so that different hash functions type mismatch - -``` -type ('a, 'id) cmp -``` -`('a,'id) cmp` - -Its runtime representation is a `cmp` function, but signed with a type parameter, so that different hash functions type mismatch - -``` -module type Comparable = sig ... end -``` -``` -type ('key, 'id) comparable = - (module Comparable - with type identity = 'id - and type t = 'key) -``` -`('key, 'id) cmparable` is a module of functions, here it only includes `cmp`. - -Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). - -It can be created using function [`comparableU`](./#val-comparableU) or [`comparable`](./#val-comparable). - -The idea of a unique identity when created is that it makes sure two sets would type mismatch if they use different comparison function - -``` -module MakeComparableU (M : sig ... end) : Comparable with type t = M.t -``` -``` -module MakeComparable (M : sig ... end) : Comparable with type t = M.t -``` -``` -val comparableU : - cmp:('a -> 'a -> int) Js.Fn.arity2 -> - (module Comparable - with type t = 'a) -``` -``` -val comparable : cmp:('a -> 'a -> int) -> (module Comparable with type t = 'a) -``` -```ocaml - module C = ( - val Belt.Id.comparable ~cmp:(compare : int -> int -> int) - ) - let m = Belt.Set.make(module C) -``` -Note that the name of C can not be ignored - -``` -module type Hashable = sig ... end -``` -``` -type ('key, 'id) hashable = - (module Hashable - with type identity = 'id - and type t = 'key) -``` -`('key, 'id) hashable` is a module of functions, here it only includes `hash`, `eq`. - -Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). - -It can be created using function [`hashableU`](./#val-hashableU) or [`hashable`](./#val-hashable). - -The idea of a unique identity when created is that it makes sure two hash sets would type mismatch if they use different comparison function - -``` -module MakeHashableU (M : sig ... end) : Hashable with type t = M.t -``` -``` -module MakeHashable (M : sig ... end) : Hashable with type t = M.t -``` -``` -val hashableU : - hash:('a -> int) Js.Fn.arity1 -> - eq:('a -> 'a -> bool) Js.Fn.arity2 -> - (module Hashable - with type t = 'a) -``` -``` -val hashable : - hash:('a -> int) -> - eq:('a -> 'a -> bool) -> - (module Hashable - with type t = 'a) -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Int.md b/docs/api/ml/melange/Belt-Int.md deleted file mode 100644 index e16080186..000000000 --- a/docs/api/ml/melange/Belt-Int.md +++ /dev/null @@ -1,29 +0,0 @@ - -# Module `Belt.Int` - -[`Belt.Int`](#) Utililites for Int - -``` -val toFloat : int -> float -``` -``` -val fromFloat : float -> int -``` -``` -val fromString : string -> int option -``` -``` -val toString : int -> string -``` -``` -val (+) : int -> int -> int -``` -``` -val (-) : int -> int -> int -``` -``` -val (*) : int -> int -> int -``` -``` -val (/) : int -> int -> int -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-List.md b/docs/api/ml/melange/Belt-List.md deleted file mode 100644 index eb9dee2fd..000000000 --- a/docs/api/ml/melange/Belt-List.md +++ /dev/null @@ -1,680 +0,0 @@ - -# Module `Belt.List` - -[`Belt.List`](#) - -Utilities for List data type - -[`Belt.List`](#) - -Utilities for List data type. - -This module is compatible with original ocaml stdlib. In general, all functions comes with the original stdlib also applies to this collection, however, this module provides faster and stack safer utilities - -``` -type 'a t = 'a list -``` -`'a t` is compatible with built-in `list` type - -``` -val length : 'a t -> int -``` -`length xs` - -returns the length of the list xs -``` -val size : 'a t -> int -``` -**See** [`length`](./#val-length) - -``` -val head : 'a t -> 'a option -``` -`head xs` returns `None` if `xs` is the empty list, otherwise it returns `Some value` where `value` is the first element in the list. - -```ocaml - head [] = None ;; - head [1;2;3] = Some 1 ;; -``` -``` -val headExn : 'a t -> 'a -``` -`headExn xs` - -**See** [`head`](./#val-head) - -**raise** an exception if `xs` is empty - -``` -val tail : 'a t -> 'a t option -``` -`tail xs` returns `None` if `xs` is empty; otherwise it returns `Some xs2` where `xs2` is everything except the first element of `xs`; - -```ocaml - tail [] = None;; - tail [1;2;3;4] = Some [2;3;4];; -``` -``` -val tailExn : 'a t -> 'a t -``` -`tailExn xs` - -**See** [`tail`](./#val-tail) - -**raise** an exception if `xs` is empty - -``` -val add : 'a t -> 'a -> 'a t -``` -`add xs y` adds `y` to the beginning of list `xs` - -```ocaml - add [1] 3 = [3;1];; -``` -``` -val get : 'a t -> int -> 'a option -``` -`get xs n` - -return the nth element in `xs`, or `None` if `n` is larger than the length - -```ocaml - get [0;3;32] 2 = Some 32 ;; - get [0;3;32] 3 = None;; -``` -``` -val getExn : 'a t -> int -> 'a -``` -`getExn xs n` - -**See** [`get`](./#val-get) - -**raise** an exception if `n` is larger than the length - -``` -val make : int -> 'a -> 'a t -``` -`make n v` - -- return a list of length `n` with each element filled with value `v` -- return the empty list if `n` is negative -```ocaml - make 3 1 = [1;1;1] -``` -``` -val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val makeBy : int -> (int -> 'a) -> 'a t -``` -`makeBy n f` - -- return a list of length `n` with element `i` initialized with `f i` -- return the empty list if `n` is negative -```ocaml - makeBy 5 (fun i -> i) = [0;1;2;3;4];; - makeBy 5 (fun i -> i * i) = [0;1;4;9;16];; -``` -``` -val shuffle : 'a t -> 'a t -``` -`shuffle xs` - -returns a new list in random order -``` -val drop : 'a t -> int -> 'a t option -``` -`drop xs n` - -return the list obtained by dropping the first `n` elements, or `None` if `xs` has fewer than `n` elements - -```ocaml - drop [1;2;3] 2 = Some [3];; - drop [1;2;3] 3 = Some [];; - drop [1;2;3] 4 = None;; -``` -``` -val take : 'a t -> int -> 'a t option -``` -`take xs n` - -return a list with the first `n` elements from `xs`, or `None` if `xs` has fewer than `n` elements - -```ocaml - take [1;2;3] 1 = Some [1];; - take [1;2;3] 2 = Some [1;2];; - take [1;2;3] 4 = None;; -``` -``` -val splitAt : 'a t -> int -> ('a list * 'a list) option -``` -`splitAt xs n` split the list `xs` at position `n` return None when the length of `xs` is less than `n` - -```ocaml - splitAt [0;1;2;3;4] 2 = Some ([0;1], [2;3;4]) -``` -``` -val concat : 'a t -> 'a t -> 'a t -``` -`concat xs ys` - -returns the list obtained by adding ys after xs -```ocaml - concat [1;2;3] [4;5] = [1;2;3;4;5] -``` -``` -val concatMany : 'a t array -> 'a t -``` -`concatMany a` return the list obtained by concatenating in order all the lists in array `a` - -```ocaml - concatMany [| [1;2;3] ; []; [3]; [4] |] = [1;2;3;3;4] -``` -``` -val reverseConcat : 'a t -> 'a t -> 'a t -``` -`reverseConcat xs ys` is equivalent to `concat (reverse xs) ys` - -```ocaml - reverseConcat [1;2] [3;4] = [2;1;3;4] -``` -``` -val flatten : 'a t t -> 'a t -``` -`flatten ls` return the list obtained by concatenating in order all the lists in list `ls` - -```ocaml - flatten [ [1;2;3] ; []; [3]; [4] ] = [1;2;3;3;4] -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -`map xs f` - -return the list obtained by applying `f` to each element of `xs` - -```ocaml - map [1;2] (fun x-> x + 1) = [3;4] -``` -``` -val zip : 'a t -> 'b t -> ('a * 'b) t -``` -`zip xs ys` - -returns a list of pairs from the two lists with the length of the shorter list -```ocaml - zip [1;2] [3;4;5] = [(1,3); (2,4)] -``` -``` -val zipByU : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t -``` -``` -val zipBy : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t -``` -`zipBy xs ys f` - -**See** [`zip`](./#val-zip) - -Equivalent to `zip xs ys |> List.map (fun (x,y) -> f x y)` - -```ocaml - zipBy [1;2;3] [4;5] (fun a b -> 2 * a + b) = [6;9];; -``` -``` -val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t -``` -`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. - -```ocaml - mapWithIndex [1;2;3] (fun i x -> i + x) = - [0 + 1; 1 + 2; 2 + 3 ] -``` -``` -val fromArray : 'a array -> 'a t -``` -`fromArray arr` converts the given array to a list - -```ocaml - fromArray [|1;2;3|] = [1;2;3] -``` -``` -val toArray : 'a t -> 'a array -``` -`toArray xs` converts the given list to an array - -```ocaml - toArray [1;2;3] = [|1;2;3|] -``` -``` -val reverse : 'a t -> 'a t -``` -`reverse xs` returns a new list whose elements are those of `xs` in reverse order. - -```ocaml - reverse [1;2;3] = [3;2;1] -``` -``` -val mapReverseU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val mapReverse : 'a t -> ('a -> 'b) -> 'b t -``` -`mapReverse xs f` - -Equivalent to `reverse (map xs f)` - -```ocaml - mapReverse [3;4;5] (fun x -> x * x) = [25;16;9];; -``` -``` -val forEachU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> 'b) -> unit -``` -`forEach xs f ` Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`, so no new array is created. Use `foreach` when you are primarily concerned with repetitively creating side effects. - -```ocaml - forEach ["a";"b";"c"] (fun x -> Js.log("Item: " ^ x));; - (* prints: - Item: a - Item: b - Item: c - *) - - let us = ref 0;; - forEach [1;2;3;4] (fun x -> us := !us + x);; - !us = 1 + 2 + 3 + 4;; -``` -``` -val forEachWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> unit -``` -``` -val forEachWithIndex : 'a t -> (int -> 'a -> 'b) -> unit -``` -`forEachWithIndex xs f` - -```ocaml - - forEach ["a";"b";"c"] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; - (* prints: - Item 0 is a - Item 1 is b - Item 2 is cc - *) - - let total = ref 0 ;; - forEachWithIndex [10;11;12;13] (fun i x -> total := !total + x + i);; - !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; -``` -``` -val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b -``` -`reduce xs f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”, which starts with a value of `init`. `reduce` returns the final value of the accumulator. - -```ocaml - reduce [1;2;3;4] 0 (+) = 10;; - reduce [1;2;3;4] 10 (-) = 0;; - reduce [1;2;3;4] [] add = [4;3;2;1]; -``` -``` -val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b -``` -`reduceWithIndex xs f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the list and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. - -```ocaml - reduceWithIndex [1;2;3;4] 0 (fun acc x i -> acc + x + i) = 16;; -``` -``` -val reduceReverseU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b -``` -``` -val reduceReverse : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b -``` -`reduceReverse xs f` - -Works like [`reduce`](./#val-reduce), except that function `f` is applied to each item of `xs` from the last back to the first. - -```ocaml - reduceReverse [1;2;3;4] 0 (+) = 10;; - reduceReverse [1;2;3;4] 10 (-) = 0;; - reduceReverse [1;2;3;4] [] add = [1;2;3;4];; -``` -``` -val mapReverse2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t -``` -``` -val mapReverse2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t -``` -`mapReverse2 xs ys f` - -equivalent to `reverse (zipBy xs ys f)` - -```ocaml - mapReverse2 [1;2;3] [1;2] (+) = [4;2] -``` -``` -val forEach2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> unit -``` -``` -val forEach2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> unit -``` -`forEach2 xs ys f` stop with the shorter list - -``` -val reduce2U : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) Js.Fn.arity3 -> 'a -``` -``` -val reduce2 : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) -> 'a -``` -`reduce2 xs ys init f ` - -Applies `f` to each element of `xs` and `ys` from beginning to end. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. - -```ocaml - reduce2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; - reduce2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [2 +5;1 + 4 ];; (*add appends at end *) -``` -``` -val reduceReverse2U : - 'a t -> - 'b t -> - 'c -> - ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> - 'c -``` -``` -val reduceReverse2 : 'a t -> 'b t -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c -``` -`reduceReverse2 xs ys init f ` - -Applies `f` to each element of `xs` and `ys` from end to beginning. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. - -```ocaml - reduceReverse2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; - reduceReverse2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [1 + 4;2 + 5];; (*add appends at end *) -``` -``` -val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : 'a t -> ('a -> bool) -> bool -``` -`every xs p` - -returns true if all elements satisfy p, where p is a predicate: a function taking an element and returning a bool. -```ocaml - every [] (fun x -> x mod 2 = 0) = true;; - every [2;4;6] (fun x -> x mod 2 = 0 ) = true;; - every [1;-3;5] (fun x -> x > 0) = false;; -``` -``` -val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : 'a t -> ('a -> bool) -> bool -``` -`some xs p` - -returns true if at least one of the elements in xs satifies p, where p is a predicate: a function taking an element and returning a bool. -```ocaml - some [] (fun x -> x mod 2 = 0) = false ;; - some [1;2;4] (fun x -> x mod 2 = 0) = true;; - some [-1;-3;-5] (fun x -> x > 0) = false;; -``` -``` -val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`every2 xs ys p` returns true if predicate `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - every2 [1;2;3] [0;1] (>) = true;; - every2 [] [1] (fun x y -> x > y) = true;; - every2 [2;3] [1] (fun x y -> x > y) = true;; - every2 [0;1] [5;0] (fun x y -> x > y) = false; -``` -``` -val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - some2 [0;2] [1;0;3] (>) = true ;; - some2 [] [1] (fun x y -> x > y) = false;; - some2 [2;3] [1;4] (fun x y -> x > y) = true;; -``` -``` -val cmpByLength : 'a t -> 'a t -> int -``` -`cmpByLength l1 l2` - -Compare two lists solely by length. Returns \-1 if `length l1` is less than `length l2`, 0 if `length l1` equals `length l2`, and 1 if `length l1` is greater than `length l2`. - -```ocaml -cmpByLength [1;2] [3;4;5;6] = -1;; -cmpByLength [1;2;3] [4;5;6] = 0;; -cmpByLength [1;2;3;4] [5;6] = 1;; -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -Compare elements one by one `f x y`. `f` returns - -- a negative number if `x` is “less than” `y` -- zero if `x` is “equal to” `y` -- a positive number if `x` is “greater than” `y` The comparison returns the first non-zero result of `f`, or zero if `f` returns zero for all `x` and `y`. If all items have compared equal, but `xs` is exhausted first, return \-1. (`xs` is shorter) If all items have compared equal, but `ys` is exhausted first, return 1 (`xs` is longer) -```ocaml - cmp [3] [3;7] (fun a b -> compare a b) = -1 - cmp [5;3] [5] (fun a b -> compare a b) = 1 - cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; - cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; - cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; -``` -**Attention**: The total ordering of List is different from Array, for Array, we compare the length first and, only if the lengths are equal, elements one by one. For lists, we just compare elements one by one - -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq xs ys eqElem` check equality of `xs` and `ys` using `eqElem` for equality on elements, where `eqElem` is a function that returns true if items `x` and `y` meet some criterion for equality, false otherwise. `eq` false if length of `xs` and `ys` are not the same. - -```ocaml - eq [1;2;3] [1;2] (=) = false ;; - eq [1;2] [1;2] (=) = true;; - eq [1; 2; 3] [-1; -2; -3] (fun a b -> abs a = abs b) = true;; -``` -``` -val hasU : 'a t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val has : 'a t -> 'b -> ('a -> 'b -> bool) -> bool -``` -`has xs eqFcn` returns true if the list contains at least one element for which `eqFcn x` returns true - -```ocaml - has [1;2;3] 2 (=) = true;; - has [1;2;3] 4 (=) = false;; - has [-1;-2;-3] 2 (fun a b -> abs a = abs b) = true;; -``` -``` -val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option -``` -``` -val getBy : 'a t -> ('a -> bool) -> 'a option -``` -`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. - -```ocaml - getBy [1;4;3;2] (fun x -> x mod 2 = 0) = Some 4 - getBy [15;13;11] (fun x -> x mod 2 = 0) = None -``` -``` -val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t -``` -``` -val keep : 'a t -> ('a -> bool) -> 'a t -``` -`keep xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` - -```ocaml - keep [1;2;3;4] (fun x -> x mod 2 = 0) = - [2;4] -``` -``` -val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t -``` -``` -val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t -``` -`keepWithIndex xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` - -```ocaml - keepWithIndex [1;2;3;4] (fun _x i -> i mod 2 = 0) - = - [1;3] -``` -``` -val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b t -``` -``` -val keepMap : 'a t -> ('a -> 'b option) -> 'b t -``` -`keepMap xs f` applies `f` to each element of `xs`. If `f xi` returns `Some value`, then `value` is kept in the resulting list; if `f xi` returns `None`, the element is not retained in the result. - -```ocaml - keepMap [1;2;3;4] (fun x -> if x mod 2 = 0 then Some (-x ) else None) - = - [-2;-4] -``` -``` -val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t -``` -``` -val partition : 'a t -> ('a -> bool) -> 'a t * 'a t -``` -`partition xs p` creates a pair of lists; the first list consists of all elements of `xs` that satisfy the predicate function `p`; the second list consists of all elements of `xs` that do not satisfy `p` - -```ocaml - partition [1;2;3;4] (fun x -> x mod 2 = 0) = - ([2;4], [1;3]) -``` -``` -val unzip : ('a * 'b) t -> 'a t * 'b t -``` -`unzip xs` takes a list of pairs and creates a pair of lists. The first list contains all the first items of the pairs; the second list contains all the second items. - -```ocaml - unzip [(1,2) ; (3,4)] = ([1;3], [2;4]);; - unzip [(1,2) ; (3,4) ; (5,6) ; (7,8)] = ([1;3;5;7], [2;4;6;8]);; -``` -``` -val getAssocU : - ('a * 'c) t -> - 'b -> - ('a -> 'b -> bool) Js.Fn.arity2 -> - 'c option -``` -``` -val getAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> 'c option -``` -`getAssoc xs k eq` - -return the second element of a pair in `xs` where the first element equals `x` as per the predicate function `eq`, or `None` if not found - -```ocaml - getAssoc [ 1, "a"; 2, "b"; 3, "c"] 2 (=) = Some "b" - getAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = Some "afternoon" -``` -``` -val hasAssocU : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val hasAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> bool -``` -`hasAssoc xs k eq` return true if there is a pair in `xs` where the first element equals `k` as per the predicate funtion `eq` - -```ocaml - hasAssoc [1, "a"; 2, "b"; 3,"c"] 1 (=) = true;; - hasAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = true;; -``` -``` -val removeAssocU : - ('a * 'c) t -> - 'b -> - ('a -> 'b -> bool) Js.Fn.arity2 -> - ('a * 'c) t -``` -``` -val removeAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> ('a * 'c) t -``` -`removeAssoc xs k eq` Return a list after removing the first pair whose first value is `k` per the equality predicate `eq`; if not found, return a new list identical to `xs`. - -```ocaml - removeAssoc [1,"a"; 2, "b"; 3, "c" ] 1 (=) = - [2, "b"; 3, "c"] - removeAssoc [1,"a"; 2, "b"; 3, "c" ] 99 (=) = - [1, "a"; 2, "b"; 3, "c"] -``` -``` -val setAssocU : - ('a * 'c) t -> - 'a -> - 'c -> - ('a -> 'a -> bool) Js.Fn.arity2 -> - ('a * 'c) t -``` -``` -val setAssoc : ('a * 'c) t -> 'a -> 'c -> ('a -> 'a -> bool) -> ('a * 'c) t -``` -`setAssoc xs k v eq` if `k` exists in `xs` by satisfying the `eq` predicate, return a new list with the key and value replaced by the new `k` and `v`; otherwise, return a new list with the pair `k, v` added to the head of `xs`. - -```ocaml - setAssoc [1,"a"; 2, "b"; 3, "c"] 2 "x" (=) = - [1,"a"; 2, "x"; 3,"c"] ;; - - setAssoc [1,"a"; 3, "c"] 2 "b" (=) = - [2,"b"; 1,"a"; 3, "c"] - - setAssoc [9, "morning"; 3, "morning?!"; 22, "night"] 15 "afternoon" - (fun a b -> a mod 12 = b mod 12) = [9, "morning"; 15, "afternoon"; 22, "night"] -``` -Note carefully the last example\! Since `15 mod 12` equals `3 mod 12`, *both* the key and value are replaced in the list. - -``` -val sortU : 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a t -``` -``` -val sort : 'a t -> ('a -> 'a -> int) -> 'a t -``` -`sort xs` Returns a sorted list. - -```ocaml - sort [5; 4; 9; 3; 7] (fun a b -> a - b) = [3; 4; 5; 7; 9] -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Map-Dict.md b/docs/api/ml/melange/Belt-Map-Dict.md deleted file mode 100644 index 61b1e8167..000000000 --- a/docs/api/ml/melange/Belt-Map-Dict.md +++ /dev/null @@ -1,281 +0,0 @@ - -# Module `Map.Dict` - -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -**Advanced usage only** - -``` -type ('key, 'value, 'id) t -``` -``` -type ('key, 'id) cmp -``` -``` -val empty : ('k, 'v, 'id) t -``` -``` -val isEmpty : ('k, 'v, 'id) t -> bool -``` -``` -val has : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> bool -``` -``` -val cmpU : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - kcmp:('k, 'id) cmp -> - vcmp:('v -> 'v -> int) Js.Fn.arity2 -> - int -``` -``` -val cmp : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - kcmp:('k, 'id) cmp -> - vcmp:('v -> 'v -> int) -> - int -``` -``` -val eqU : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - kcmp:('k, 'id) cmp -> - veq:('a -> 'a -> bool) Js.Fn.arity2 -> - bool -``` -``` -val eq : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - kcmp:('k, 'id) cmp -> - veq:('a -> 'a -> bool) -> - bool -``` -`eq m1 m2 cmp` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val findFirstByU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k * 'v) option -``` -``` -val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : - ('k, 'a, 'id) t -> - 'b -> - ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> - 'b -``` -``` -val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : ('k, 'a, 'id) t -> int -``` -``` -val toList : ('k, 'a, 'id) t -> ('k * 'a) list -``` -In increasing order. - -``` -val toArray : ('k, 'a, 'id) t -> ('k * 'a) array -``` -``` -val fromArray : ('k * 'a) array -> cmp:('k, 'id) cmp -> ('k, 'a, 'id) t -``` -``` -val keysToArray : ('k, 'a, 'id) t -> 'k array -``` -``` -val valuesToArray : ('k, 'a, 'id) t -> 'a array -``` -``` -val minKey : ('k, _, _) t -> 'k option -``` -``` -val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val maxKey : ('k, _, _) t -> 'k option -``` -``` -val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val minimum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val maximum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val get : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a option -``` -``` -val getUndefined : - ('k, 'a, 'id) t -> - 'k -> - cmp:('k, 'id) cmp -> - 'a Js.undefined -``` -``` -val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> cmp:('k, 'id) cmp -> 'a -``` -``` -val getExn : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a -``` -``` -val checkInvariantInternal : (_, _, _) t -> unit -``` -**raise** when invariant is not held - -``` -val remove : ('a, 'b, 'id) t -> 'a -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t -``` -`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. - -``` -val removeMany : - ('a, 'b, 'id) t -> - 'a array -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val set : ('a, 'b, 'id) t -> 'a -> 'b -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t -``` -`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : - ('a, 'b, 'id) t -> - 'a -> - ('b option -> 'b option) Js.Fn.arity1 -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val update : - ('a, 'b, 'id) t -> - 'a -> - ('b option -> 'b option) -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val mergeU : - ('a, 'b, 'id) t -> - ('a, 'c, 'id) t -> - ('a -> 'b option -> 'c option -> 'd option) Js.Fn.arity3 -> - cmp:('a, 'id) cmp -> - ('a, 'd, 'id) t -``` -``` -val merge : - ('a, 'b, 'id) t -> - ('a, 'c, 'id) t -> - ('a -> 'b option -> 'c option -> 'd option) -> - cmp:('a, 'id) cmp -> - ('a, 'd, 'id) t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val mergeMany : - ('a, 'b, 'id) t -> - ('a * 'b) array -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val keepU : - ('k, 'a, 'id) t -> - ('k -> 'a -> bool) Js.Fn.arity2 -> - ('k, 'a, 'id) t -``` -``` -val keep : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> ('k, 'a, 'id) t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : - ('k, 'a, 'id) t -> - ('k -> 'a -> bool) Js.Fn.arity2 -> - ('k, 'a, 'id) t * ('k, 'a, 'id) t -``` -``` -val partition : - ('k, 'a, 'id) t -> - ('k -> 'a -> bool) -> - ('k, 'a, 'id) t * ('k, 'a, 'id) t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : - ('a, 'b, 'id) t -> - 'a -> - cmp:('a, 'id) cmp -> - (('a, 'b, 'id) t * ('a, 'b, 'id) t) * 'b option -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t -``` -``` -val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : - ('k, 'a, 'id) t -> - ('k -> 'a -> 'b) Js.Fn.arity2 -> - ('k, 'b, 'id) t -``` -``` -val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Map-Int.md b/docs/api/ml/melange/Belt-Map-Int.md deleted file mode 100644 index fe3ddaa90..000000000 --- a/docs/api/ml/melange/Belt-Map-Int.md +++ /dev/null @@ -1,217 +0,0 @@ - -# Module `Map.Int` - -Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -type key = int -``` -``` -type 'value t -``` -The type of maps from type `key` to type `'value`. - -``` -val empty : 'v t -``` -``` -val isEmpty : 'v t -> bool -``` -``` -val has : 'v t -> key -> bool -``` -``` -val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int -``` -``` -val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool -``` -`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. - -``` -val findFirstByU : - 'v t -> - (key -> 'v -> bool) Js.Fn.arity2 -> - (key * 'v) option -``` -``` -val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'v t -> (key -> 'v -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 -``` -``` -val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'v t -> (key -> 'v -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'v t -> (key -> 'v -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : 'v t -> int -``` -``` -val toList : 'v t -> (key * 'v) list -``` -In increasing order. - -``` -val toArray : 'v t -> (key * 'v) array -``` -``` -val fromArray : (key * 'v) array -> 'v t -``` -``` -val keysToArray : 'v t -> key array -``` -``` -val valuesToArray : 'v t -> 'v array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'v t -> (key * 'v) option -``` -``` -val minUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val maximum : 'v t -> (key * 'v) option -``` -``` -val maxUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val get : 'v t -> key -> 'v option -``` -``` -val getUndefined : 'v t -> key -> 'v Js.undefined -``` -``` -val getWithDefault : 'v t -> key -> 'v -> 'v -``` -``` -val getExn : 'v t -> key -> 'v -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'v t -> key -> 'v t -``` -`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. - -``` -val removeMany : 'v t -> key array -> 'v t -``` -``` -val set : 'v t -> key -> 'v -> 'v t -``` -`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t -``` -``` -val update : 'v t -> key -> ('v option -> 'v option) -> 'v t -``` -``` -val mergeU : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> - 'c t -``` -``` -val merge : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) -> - 'c t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val mergeMany : 'v t -> (key * 'v) array -> 'v t -``` -``` -val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t -``` -``` -val keep : 'v t -> (key -> 'v -> bool) -> 'v t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t -``` -``` -val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : key -> 'v t -> 'v t * 'v option * 'v t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t -``` -``` -val map : 'v t -> ('v -> 'v2) -> 'v2 t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t -``` -``` -val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Map-String.md b/docs/api/ml/melange/Belt-Map-String.md deleted file mode 100644 index 1fa79b3e6..000000000 --- a/docs/api/ml/melange/Belt-Map-String.md +++ /dev/null @@ -1,217 +0,0 @@ - -# Module `Map.String` - -specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -type key = string -``` -``` -type 'value t -``` -The type of maps from type `key` to type `'value`. - -``` -val empty : 'v t -``` -``` -val isEmpty : 'v t -> bool -``` -``` -val has : 'v t -> key -> bool -``` -``` -val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int -``` -``` -val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool -``` -`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. - -``` -val findFirstByU : - 'v t -> - (key -> 'v -> bool) Js.Fn.arity2 -> - (key * 'v) option -``` -``` -val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'v t -> (key -> 'v -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 -``` -``` -val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'v t -> (key -> 'v -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'v t -> (key -> 'v -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : 'v t -> int -``` -``` -val toList : 'v t -> (key * 'v) list -``` -In increasing order. - -``` -val toArray : 'v t -> (key * 'v) array -``` -``` -val fromArray : (key * 'v) array -> 'v t -``` -``` -val keysToArray : 'v t -> key array -``` -``` -val valuesToArray : 'v t -> 'v array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'v t -> (key * 'v) option -``` -``` -val minUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val maximum : 'v t -> (key * 'v) option -``` -``` -val maxUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val get : 'v t -> key -> 'v option -``` -``` -val getUndefined : 'v t -> key -> 'v Js.undefined -``` -``` -val getWithDefault : 'v t -> key -> 'v -> 'v -``` -``` -val getExn : 'v t -> key -> 'v -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'v t -> key -> 'v t -``` -`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. - -``` -val removeMany : 'v t -> key array -> 'v t -``` -``` -val set : 'v t -> key -> 'v -> 'v t -``` -`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t -``` -``` -val update : 'v t -> key -> ('v option -> 'v option) -> 'v t -``` -``` -val mergeU : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> - 'c t -``` -``` -val merge : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) -> - 'c t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val mergeMany : 'v t -> (key * 'v) array -> 'v t -``` -``` -val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t -``` -``` -val keep : 'v t -> (key -> 'v -> bool) -> 'v t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t -``` -``` -val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : key -> 'v t -> 'v t * 'v option * 'v t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t -``` -``` -val map : 'v t -> ('v -> 'v2) -> 'v2 t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t -``` -``` -val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Map.md b/docs/api/ml/melange/Belt-Map.md deleted file mode 100644 index 23dfe9607..000000000 --- a/docs/api/ml/melange/Belt-Map.md +++ /dev/null @@ -1,460 +0,0 @@ - -# Module `Belt.Map` - -[`Belt.Map`](#), - -The top level provides generic **immutable** map operations. - -It also has three specialized inner modules [`Belt.Map.Int`](./Belt-Map-Int.md), [`Belt.Map.String`](./Belt-Map-String.md) and - -[`Belt.Map.Dict`](./Belt-Map-Dict.md): This module separates data from function which is more verbose but slightly more efficient - -A *immutable* sorted map module which allows customize *compare* behavior. - -The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. - -Example usage: - -```ocaml - module PairComparator = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c - end) - - let myMap = Belt.Map.make ~id:(module PairComparator) - let myMap2 = Belt.Map.set myMap (1, 2) "myValue" -``` -The API documentation below will assume a predeclared comparator module for integers, IntCmp - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module String : sig ... end -``` -specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module Dict : sig ... end -``` -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -``` -type ('key, 'value, 'identity) t -``` -`('key, 'identity) t` - -`'key` is the field type - -`'value` is the element type - -`'identity` the identity of the collection - -``` -type ('key, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'key) -``` -The identity needed for making an empty map - -``` -val make : id:('k, 'id) id -> ('k, 'v, 'id) t -``` -`make ~id` creates a new map by taking in the comparator - -```ocaml - let m = Belt.Map.make ~id:(module IntCmp) -``` -``` -val isEmpty : (_, _, _) t -> bool -``` -`isEmpty m` checks whether a map m is empty - -```ocaml - isEmpty (fromArray [|1,"1"|] ~id:(module IntCmp)) = false -``` -``` -val has : ('k, 'v, 'id) t -> 'k -> bool -``` -`has m k` checks whether m has the key k - -```ocaml - has (fromArray [|1,"1"|] ~id:(module IntCmp)) 1 = true -``` -``` -val cmpU : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - ('v -> 'v -> int) Js.Fn.arity2 -> - int -``` -``` -val cmp : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> int) -> int -``` -`cmp m0 m1 vcmp` - -Total ordering of map given total ordering of value function. - -It will compare size first and each element following the order one by one. - -``` -val eqU : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - ('v -> 'v -> bool) Js.Fn.arity2 -> - bool -``` -``` -val eq : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> bool) -> bool -``` -`eq m1 m2 veq` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `veq` is the equality predicate used to compare the data associated with the keys. - -``` -val findFirstByU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k * 'v) option -``` -``` -val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : ('k, 'v, 'id) t -> ('k -> 'v -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : ('k, 'v, 'id) t -> ('k -> 'v -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - let acc = ref [] ;; - forEach s0 (fun k v -> acc := (k,v) :: !acc);; - - !acc = [4,"4"; 3,"3"; 2,"2"; 1,"1"] -``` -``` -val reduceU : - ('k, 'v, 'id) t -> - 'acc -> - ('acc -> 'k -> 'v -> 'acc) Js.Fn.arity3 -> - 'acc -``` -``` -val reduce : ('k, 'v, 'id) t -> 'acc -> ('acc -> 'k -> 'v -> 'acc) -> 'acc -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - reduce s0 [] (fun acc k v -> (k,v) acc ) = [4,"4";3,"3";2,"2";1,"1"];; -``` -``` -val everyU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : ('k, 'v, 'id) t -> int -``` -`size s` - -```ocaml - size (fromArray [2,"2"; 2,"1"; 3,"3"] ~id:(module IntCmp)) = 2 ;; -``` -``` -val toArray : ('k, 'v, 'id) t -> ('k * 'v) array -``` -`toArray s` - -```ocaml - toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] -``` -``` -val toList : ('k, 'v, 'id) t -> ('k * 'v) list -``` -In increasing order - -**See** [`toArray`](./#val-toArray) - -``` -val fromArray : ('k * 'v) array -> id:('k, 'id) id -> ('k, 'v, 'id) t -``` -`fromArray kvs ~id` - -```ocaml - toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] -``` -``` -val keysToArray : ('k, 'v, 'id) t -> 'k array -``` -`keysToArray s` - -```ocaml - keysToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = - [|1;2;3|];; -``` -``` -val valuesToArray : ('k, 'v, 'id) t -> 'v array -``` -`valuesToArray s` - -```ocaml - valuesToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = - [|"1";"2";"3"|];; -``` -``` -val minKey : ('k, _, _) t -> 'k option -``` -`minKey s` - -returns the minimum key, None if not exist -``` -val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -**See** [`minKey`](./#val-minKey) - -``` -val maxKey : ('k, _, _) t -> 'k option -``` -`maxKey s` - -returns the maximum key, None if not exist -``` -val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -**See** [`maxKey`](./#val-maxKey) - -``` -val minimum : ('k, 'v, _) t -> ('k * 'v) option -``` -`minimum s` - -returns the minimum key value pair, None if not exist -``` -val minUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined -``` -**See** [`minimum`](./#val-minimum) - -``` -val maximum : ('k, 'v, _) t -> ('k * 'v) option -``` -`maximum s` - -returns the maximum key value pair, None if not exist -``` -val maxUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined -``` -**See** [`maximum`](./#val-maximum) - -``` -val get : ('k, 'v, 'id) t -> 'k -> 'v option -``` -`get s k` - -```ocaml - get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = - Some "2";; - get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = - None;; -``` -``` -val getUndefined : ('k, 'v, 'id) t -> 'k -> 'v Js.undefined -``` -**See** [`get`](./#val-get) - -returns undefined when not found -``` -val getWithDefault : ('k, 'v, 'id) t -> 'k -> 'v -> 'v -``` -`getWithDefault s k default` - -**See** [`get`](./#val-get) - -returns default when k is not found -``` -val getExn : ('k, 'v, 'id) t -> 'k -> 'v -``` -`getExn s k` - -**See** [`getExn`](./#val-getExn) - -**raise** when `k` not exist - -``` -val remove : ('k, 'v, 'id) t -> 'k -> ('k, 'v, 'id) t -``` -`remove m x` when `x` is not in `m`, `m` is returned reference unchanged. - -```ocaml - let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; - - let s1 = remove s0 1;; - let s2 = remove s1 1;; - s1 == s2 ;; - keysToArray s1 = [|2;3|];; -``` -``` -val removeMany : ('k, 'v, 'id) t -> 'k array -> ('k, 'v, 'id) t -``` -`removeMany s xs` - -Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` - -``` -val set : ('k, 'v, 'id) t -> 'k -> 'v -> ('k, 'v, 'id) t -``` -`set m x y ` returns a map containing the same bindings as `m`, with a new binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -```ocaml - let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; - - let s1 = set s0 2 "3";; - - valuesToArray s1 = ["1";"3";"3"];; -``` -``` -val updateU : - ('k, 'v, 'id) t -> - 'k -> - ('v option -> 'v option) Js.Fn.arity1 -> - ('k, 'v, 'id) t -``` -``` -val update : - ('k, 'v, 'id) t -> - 'k -> - ('v option -> 'v option) -> - ('k, 'v, 'id) t -``` -`update m x f` returns a map containing the same bindings as `m`, except for the binding of `x`. Depending on the value of `y` where `y` is `f (get x m)`, the binding of `x` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `x` is associated to `z` in the resulting map. - -``` -val mergeMany : ('k, 'v, 'id) t -> ('k * 'v) array -> ('k, 'v, 'id) t -``` -`mergeMany s xs` - -Add each of `xs` to `s`, note unlike [`set`](./#val-set), the reference of return value might be changed even if all values in `xs` exist `s` - -``` -val mergeU : - ('k, 'v, 'id) t -> - ('k, 'v2, 'id) t -> - ('k -> 'v option -> 'v2 option -> 'v3 option) Js.Fn.arity3 -> - ('k, 'v3, 'id) t -``` -``` -val merge : - ('k, 'v, 'id) t -> - ('k, 'v2, 'id) t -> - ('k -> 'v option -> 'v2 option -> 'v3 option) -> - ('k, 'v3, 'id) t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val keepU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k, 'v, 'id) t -``` -``` -val keep : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k, 'v, 'id) t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k, 'v, 'id) t * ('k, 'v, 'id) t -``` -``` -val partition : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) -> - ('k, 'v, 'id) t * ('k, 'v, 'id) t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : - ('k, 'v, 'id) t -> - 'k -> - (('k, 'v, 'id) t * ('k, 'v, 'id) t) * 'v option -``` -`split x m` returns a tuple `(l r), data`, where `l` is the map with all the bindings of `m` whose 'k is strictly less than `x`; `r` is the map with all the bindings of `m` whose 'k is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : ('k, 'v, 'id) t -> ('v -> 'v2) Js.Fn.arity1 -> ('k, 'v2, 'id) t -``` -``` -val map : ('k, 'v, 'id) t -> ('v -> 'v2) -> ('k, 'v2, 'id) t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : - ('k, 'v, 'id) t -> - ('k -> 'v -> 'v2) Js.Fn.arity2 -> - ('k, 'v2, 'id) t -``` -``` -val mapWithKey : ('k, 'v, 'id) t -> ('k -> 'v -> 'v2) -> ('k, 'v2, 'id) t -``` -`mapWithKey m f` - -The same as [`map`](./#val-map) except that `f` is supplied with one more argument: the key - -``` -val getData : ('k, 'v, 'id) t -> ('k, 'v, 'id) Belt__.Belt_MapDict.t -``` -`getData s0` - -**Advanced usage only** - -returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing -``` -val getId : ('k, 'v, 'id) t -> ('k, 'id) id -``` -`getId s0` - -**Advanced usage only** - -returns the identity of s0 -``` -val packIdData : - id:('k, 'id) id -> - data:('k, 'v, 'id) Belt__.Belt_MapDict.t -> - ('k, 'v, 'id) t -``` -`packIdData ~id ~data` - -**Advanced usage only** - -returns the packed collection \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-MutableMap-Int.md b/docs/api/ml/melange/Belt-MutableMap-Int.md deleted file mode 100644 index 09b46fa13..000000000 --- a/docs/api/ml/melange/Belt-MutableMap-Int.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `MutableMap.Int` - -``` -type key = int -``` -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val isEmpty : 'a t -> bool -``` -``` -val has : 'a t -> key -> bool -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair - -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq m1 m2 cmp` - -``` -val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'a t -> (key -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. - -``` -val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'a t -> (key -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'a t -> (key -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val size : 'a t -> int -``` -``` -val toList : 'a t -> (key * 'a) list -``` -In increasing order - -``` -val toArray : 'a t -> (key * 'a) array -``` -In increasing order - -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'a t -> (key * 'a) option -``` -``` -val minUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val maximum : 'a t -> (key * 'a) option -``` -``` -val maxUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val getUndefined : 'a t -> key -> 'a Js.undefined -``` -``` -val getWithDefault : 'a t -> key -> 'a -> 'a -``` -``` -val getExn : 'a t -> key -> 'a -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'a t -> key -> unit -``` -`remove m x` do the in-place modification - -``` -val removeMany : 'a t -> key array -> unit -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit -``` -``` -val update : 'a t -> key -> ('a option -> 'a option) -> unit -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-MutableMap-String.md b/docs/api/ml/melange/Belt-MutableMap-String.md deleted file mode 100644 index 8743e1b84..000000000 --- a/docs/api/ml/melange/Belt-MutableMap-String.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `MutableMap.String` - -``` -type key = string -``` -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val isEmpty : 'a t -> bool -``` -``` -val has : 'a t -> key -> bool -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair - -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq m1 m2 cmp` - -``` -val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'a t -> (key -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. - -``` -val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'a t -> (key -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'a t -> (key -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val size : 'a t -> int -``` -``` -val toList : 'a t -> (key * 'a) list -``` -In increasing order - -``` -val toArray : 'a t -> (key * 'a) array -``` -In increasing order - -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'a t -> (key * 'a) option -``` -``` -val minUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val maximum : 'a t -> (key * 'a) option -``` -``` -val maxUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val getUndefined : 'a t -> key -> 'a Js.undefined -``` -``` -val getWithDefault : 'a t -> key -> 'a -> 'a -``` -``` -val getExn : 'a t -> key -> 'a -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'a t -> key -> unit -``` -`remove m x` do the in-place modification - -``` -val removeMany : 'a t -> key array -> unit -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit -``` -``` -val update : 'a t -> key -> ('a option -> 'a option) -> unit -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-MutableMap.md b/docs/api/ml/melange/Belt-MutableMap.md deleted file mode 100644 index cf079ddd2..000000000 --- a/docs/api/ml/melange/Belt-MutableMap.md +++ /dev/null @@ -1,206 +0,0 @@ - -# Module `Belt.MutableMap` - -[`Belt.MutableMap`](#) - -The top level provides generic **mutable** map operations. - -It also has two specialized inner modules [`Belt.MutableMap.Int`](./Belt-MutableMap-Int.md) and [`Belt.MutableMap.String`](./Belt-MutableMap-String.md) - -``` -module Int : sig ... end -``` -``` -module String : sig ... end -``` -A **mutable** sorted map module which allows customize *compare* behavior. - -Same as Belt.Map, but mutable. - -``` -type ('k, 'v, 'id) t -``` -``` -type ('key, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'key) -``` -``` -val make : id:('k, 'id) id -> ('k, 'a, 'id) t -``` -``` -val clear : (_, _, _) t -> unit -``` -``` -val isEmpty : (_, _, _) t -> bool -``` -``` -val has : ('k, _, _) t -> 'k -> bool -``` -``` -val cmpU : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - ('a -> 'a -> int) Js.Fn.arity2 -> - int -``` -``` -val cmp : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> int) -> int -``` -`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair - -``` -val eqU : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - ('a -> 'a -> bool) Js.Fn.arity2 -> - bool -``` -``` -val eq : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> bool) -> bool -``` -`eq m1 m2 eqf` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `eqf` is the equality predicate used to compare the data associated with the keys. - -``` -val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : - ('k, 'a, 'id) t -> - 'b -> - ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> - 'b -``` -``` -val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. - -``` -val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. - -``` -val size : ('k, 'a, 'id) t -> int -``` -``` -val toList : ('k, 'a, 'id) t -> ('k * 'a) list -``` -In increasing order - -``` -val toArray : ('k, 'a, 'id) t -> ('k * 'a) array -``` -In increasing order - -``` -val fromArray : ('k * 'a) array -> id:('k, 'id) id -> ('k, 'a, 'id) t -``` -``` -val keysToArray : ('k, _, _) t -> 'k array -``` -``` -val valuesToArray : (_, 'a, _) t -> 'a array -``` -``` -val minKey : ('k, _, _) t -> 'k option -``` -``` -val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val maxKey : ('k, _, _) t -> 'k option -``` -``` -val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val minimum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val maximum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val get : ('k, 'a, 'id) t -> 'k -> 'a option -``` -``` -val getUndefined : ('k, 'a, 'id) t -> 'k -> 'a Js.undefined -``` -``` -val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> 'a -``` -``` -val getExn : ('k, 'a, 'id) t -> 'k -> 'a -``` -``` -val checkInvariantInternal : (_, _, _) t -> unit -``` -**raise** when invariant is not held - -``` -val remove : ('k, 'a, 'id) t -> 'k -> unit -``` -`remove m x` do the in-place modification, - -``` -val removeMany : ('k, 'a, 'id) t -> 'k array -> unit -``` -``` -val set : ('k, 'a, 'id) t -> 'k -> 'a -> unit -``` -`set m x y ` do the in-place modification - -``` -val updateU : - ('k, 'a, 'id) t -> - 'k -> - ('a option -> 'a option) Js.Fn.arity1 -> - unit -``` -``` -val update : ('k, 'a, 'id) t -> 'k -> ('a option -> 'a option) -> unit -``` -``` -val mergeMany : ('k, 'a, 'id) t -> ('k * 'a) array -> unit -``` -``` -val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t -``` -``` -val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : - ('k, 'a, 'id) t -> - ('k -> 'a -> 'b) Js.Fn.arity2 -> - ('k, 'b, 'id) t -``` -``` -val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-MutableQueue.md b/docs/api/ml/melange/Belt-MutableQueue.md deleted file mode 100644 index fcb94e0a5..000000000 --- a/docs/api/ml/melange/Belt-MutableQueue.md +++ /dev/null @@ -1,114 +0,0 @@ - -# Module `Belt.MutableQueue` - -[`Belt.MutableQueue`](#) - -An FIFO(first in first out) queue data structure - -First-in first-out queues. - -This module implements queues (FIFOs), with in-place modification. - -``` -type 'a t -``` -The type of queues containing elements of type `'a`. - -``` -val make : unit -> 'a t -``` -returns a new queue, initially empty. -``` -val clear : 'a t -> unit -``` -Discard all elements from the queue. - -``` -val isEmpty : 'a t -> bool -``` -returns true if the given queue is empty, false otherwise. -``` -val fromArray : 'a array -> 'a t -``` -`fromArray a` is equivalent to `Array.forEach a (add q a)` - -``` -val add : 'a t -> 'a -> unit -``` -`add q x` adds the element `x` at the end of the queue `q`. - -``` -val peek : 'a t -> 'a option -``` -`peekOpt q` returns the first element in queue `q`, without removing it from the queue. - -``` -val peekUndefined : 'a t -> 'a Js.undefined -``` -`peekUndefined q` returns `undefined` if not found - -``` -val peekExn : 'a t -> 'a -``` -`peekExn q` - -**raise** an exception if `q` is empty - -``` -val pop : 'a t -> 'a option -``` -`pop q` removes and returns the first element in queue `q`. - -``` -val popUndefined : 'a t -> 'a Js.undefined -``` -`popUndefined q` removes and returns the first element in queue `q`. it will return undefined if it is already empty - -``` -val popExn : 'a t -> 'a -``` -`popExn q` - -**raise** an exception if `q` is empty - -``` -val copy : 'a t -> 'a t -``` -`copy q` - -returns a fresh queue -``` -val size : 'a t -> int -``` -returns the number of elements in a queue. -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -``` -val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> unit) -> unit -``` -`forEach q f` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. - -``` -val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b -``` -`reduce q accu f` is equivalent to `List.reduce l accu f`, where `l` is the list of `q`'s elements. The queue remains unchanged. - -``` -val transfer : 'a t -> 'a t -> unit -``` -`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `forEach (fun x -> add x q2) q1; clear q1`, but runs in constant time. - -``` -val toArray : 'a t -> 'a array -``` -First added will be in the beginning of the array diff --git a/docs/api/ml/melange/Belt-MutableSet-Int.md b/docs/api/ml/melange/Belt-MutableSet-Int.md deleted file mode 100644 index 5c5d225e5..000000000 --- a/docs/api/ml/melange/Belt-MutableSet-Int.md +++ /dev/null @@ -1,166 +0,0 @@ - -# Module `MutableSet.Int` - -Specalized when key type is `int`, more efficient than the generic type - -This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.MutableSet`](./Belt-MutableSet.md) - -``` -type value = int -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val make : unit -> t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val copy : t -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> unit -``` -``` -val addCheck : t -> value -> bool -``` -``` -val mergeMany : t -> value array -> unit -``` -``` -val remove : t -> value -> unit -``` -``` -val removeCheck : t -> value -> bool -``` -``` -val removeMany : t -> value array -> unit -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -``` -val cmp : t -> t -> int -``` -``` -val eq : t -> t -> bool -``` -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order with respect - -``` -val toArray : t -> value array -``` -In increasing order with respect - -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split s key` return a fresh copy of each - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/ml/melange/Belt-MutableSet-String.md b/docs/api/ml/melange/Belt-MutableSet-String.md deleted file mode 100644 index df5e825f6..000000000 --- a/docs/api/ml/melange/Belt-MutableSet-String.md +++ /dev/null @@ -1,166 +0,0 @@ - -# Module `MutableSet.String` - -Specalized when key type is `string`, more efficient than the generic type - -This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.MutableSet`](./Belt-MutableSet.md) - -``` -type value = string -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val make : unit -> t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val copy : t -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> unit -``` -``` -val addCheck : t -> value -> bool -``` -``` -val mergeMany : t -> value array -> unit -``` -``` -val remove : t -> value -> unit -``` -``` -val removeCheck : t -> value -> bool -``` -``` -val removeMany : t -> value array -> unit -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -``` -val cmp : t -> t -> int -``` -``` -val eq : t -> t -> bool -``` -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order with respect - -``` -val toArray : t -> value array -``` -In increasing order with respect - -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split s key` return a fresh copy of each - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/ml/melange/Belt-MutableSet.md b/docs/api/ml/melange/Belt-MutableSet.md deleted file mode 100644 index ab101f1c9..000000000 --- a/docs/api/ml/melange/Belt-MutableSet.md +++ /dev/null @@ -1,189 +0,0 @@ - -# Module `Belt.MutableSet` - -[`Belt.MutableSet`](#) - -The top level provides generic **mutable** set operations. - -It also has two specialized inner modules [`Belt.MutableSet.Int`](./Belt-MutableSet-Int.md) and [`Belt.MutableSet.String`](./Belt-MutableSet-String.md) - -A *mutable* sorted set module which allows customize *compare* behavior. - -Same as Belt.Set, but mutable. - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -type ('k, 'id) t -``` -``` -type ('k, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'k) -``` -``` -val make : id:('value, 'id) id -> ('value, 'id) t -``` -``` -val fromArray : 'k array -> id:('k, 'id) id -> ('k, 'id) t -``` -``` -val fromSortedArrayUnsafe : - 'value array -> - id:('value, 'id) id -> - ('value, 'id) t -``` -``` -val copy : ('k, 'id) t -> ('k, 'id) t -``` -``` -val isEmpty : (_, _) t -> bool -``` -``` -val has : ('value, _) t -> 'value -> bool -``` -``` -val add : ('value, 'id) t -> 'value -> unit -``` -``` -val addCheck : ('value, 'id) t -> 'value -> bool -``` -``` -val mergeMany : ('value, 'id) t -> 'value array -> unit -``` -``` -val remove : ('value, 'id) t -> 'value -> unit -``` -``` -val removeCheck : ('value, 'id) t -> 'value -> bool -``` -``` -val removeMany : ('value, 'id) t -> 'value array -> unit -``` -``` -val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -``` -val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -``` -val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -``` -val subset : ('value, 'id) t -> ('value, 'id) t -> bool -``` -``` -val cmp : ('value, 'id) t -> ('value, 'id) t -> int -``` -``` -val eq : ('value, 'id) t -> ('value, 'id) t -> bool -``` -``` -val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('value, 'id) t -> ('value -> unit) -> unit -``` -`forEach m f` applies `f` in turn to all elements of `m`. In increasing order - -``` -val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a -``` -In increasing order. - -``` -val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : ('value, 'id) t -> ('value -> bool) -> bool -``` -`every s p` checks if all elements of the set satisfy the predicate `p`. Order unspecified - -``` -val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : ('value, 'id) t -> ('value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. - -``` -val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t -``` -``` -val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t -``` -`keep s p` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : - ('value, 'id) t -> - ('value -> bool) Js.Fn.arity1 -> - ('value, 'id) t * ('value, 'id) t -``` -``` -val partition : - ('value, 'id) t -> - ('value -> bool) -> - ('value, 'id) t * ('value, 'id) t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : ('value, 'id) t -> int -``` -``` -val toList : ('value, 'id) t -> 'value list -``` -In increasing order - -``` -val toArray : ('value, 'id) t -> 'value array -``` -In increasing order - -``` -val minimum : ('value, 'id) t -> 'value option -``` -``` -val minUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val maximum : ('value, 'id) t -> 'value option -``` -``` -val maxUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val get : ('value, 'id) t -> 'value -> 'value option -``` -``` -val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined -``` -``` -val getExn : ('value, 'id) t -> 'value -> 'value -``` -``` -val split : - ('value, 'id) t -> - 'value -> - (('value, 'id) t * ('value, 'id) t) * bool -``` -`split s x` returns a triple `((l, r), present)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. `l,r` are freshly made, no sharing with `s` - -``` -val checkInvariantInternal : (_, _) t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/ml/melange/Belt-MutableStack.md b/docs/api/ml/melange/Belt-MutableStack.md deleted file mode 100644 index 291f3caa3..000000000 --- a/docs/api/ml/melange/Belt-MutableStack.md +++ /dev/null @@ -1,62 +0,0 @@ - -# Module `Belt.MutableStack` - -[`Belt.MutableStack`](#) - -An FILO(first in last out) stack data structure - -First in last out stack. - -This module implements stacks, with in-place modification. - -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -returns a new stack, initially empty. -``` -val clear : 'a t -> unit -``` -Discard all elements from the stack. - -``` -val copy : 'a t -> 'a t -``` -`copy x` O(1) operation, return a new stack - -``` -val push : 'a t -> 'a -> unit -``` -``` -val popUndefined : 'a t -> 'a Js.undefined -``` -``` -val pop : 'a t -> 'a option -``` -``` -val topUndefined : 'a t -> 'a Js.undefined -``` -``` -val top : 'a t -> 'a option -``` -``` -val isEmpty : 'a t -> bool -``` -``` -val size : 'a t -> int -``` -``` -val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> unit) -> unit -``` -``` -val dynamicPopIterU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val dynamicPopIter : 'a t -> ('a -> unit) -> unit -``` -`dynamicPopIter s f ` apply `f` to each element of `s`. The item is poped before applying `f`, `s` will be empty after this opeartion. This function is useful for worklist algorithm diff --git a/docs/api/ml/melange/Belt-Option.md b/docs/api/ml/melange/Belt-Option.md deleted file mode 100644 index a13563de7..000000000 --- a/docs/api/ml/melange/Belt-Option.md +++ /dev/null @@ -1,200 +0,0 @@ - -# Module `Belt.Option` - -[`Belt.Option`](#) - -Utilities for option data type. - -[`Belt.Option`](#) - -Utilities for option data type - -``` -val keepU : 'a option -> ('a -> bool) Js.Fn.arity1 -> 'a option -``` -Uncurried version of `keep` - -``` -val keep : 'a option -> ('a -> bool) -> 'a option -``` -`keep optionValue p` - -If `optionValue` is `Some value` and `p value = true`, it returns `Some value`; otherwise returns `None` - -```ocaml - keep (Some 10)(fun x -> x > 5);; (* returns [Some 10] *) - keep (Some 4)(fun x -> x > 5);; (* returns [None] *) - keep None (fun x -> x > 5);; (* returns [None] *) -``` -``` -val forEachU : 'a option -> ('a -> unit) Js.Fn.arity1 -> unit -``` -Uncurried version of `forEach` - -``` -val forEach : 'a option -> ('a -> unit) -> unit -``` -`forEach optionValue f` - -If `optionValue` is `Some value`, it calls `f value`; otherwise returns `()` - -```ocaml - forEach (Some "thing")(fun x -> Js.log x);; (* logs "thing" *) - forEach None (fun x -> Js.log x);; (* returns () *) -``` -``` -val getExn : 'a option -> 'a -``` -`getExn optionalValue` Returns `value` if `optionalValue` is `Some value`, otherwise raises `getExn` - -```ocaml - getExn (Some 3) = 3;; - getExn None (* Raises getExn error *) -``` -``` -val getUnsafe : 'a option -> 'a -``` -`getUnsafe x` returns x This is an unsafe operation, it assumes x is neither not None or (Some (None .. )) - -``` -val mapWithDefaultU : 'a option -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b -``` -Uncurried version of `mapWithDefault` - -``` -val mapWithDefault : 'a option -> 'b -> ('a -> 'b) -> 'b -``` -`mapWithDefault optionValue default f` - -If `optionValue` is `Some value`, returns `f value`; otherwise returns `default` - -```ocaml - mapWithDefault (Some 3) 0 (fun x -> x + 5) = 8;; - mapWithDefault None 0 (fun x -> x + 5) = 0;; -``` -``` -val mapU : 'a option -> ('a -> 'b) Js.Fn.arity1 -> 'b option -``` -Uncurried version of `map` - -``` -val map : 'a option -> ('a -> 'b) -> 'b option -``` -`map optionValue f` - -If `optionValue` is `Some value`, returns `Some (f value)`; otherwise returns `None` - -```ocaml - map (Some 3) (fun x -> x * x) = (Some 9);; - map None (fun x -> x * x) = None;; -``` -``` -val flatMapU : 'a option -> ('a -> 'b option) Js.Fn.arity1 -> 'b option -``` -Uncurried version of `flatMap` - -``` -val flatMap : 'a option -> ('a -> 'b option) -> 'b option -``` -`flatMap optionValue f` - -If `optionValue` is `Some value`, returns `f value`; otherwise returns `None` The function `f` must have a return type of `'a option` - -```ocaml - let f (x : float) = - if x >= 0.0 then - Some (sqrt x) - else - None;; - - flatMap (Some 4.0) f = Some 2.0;; - flatMap (Some (-4.0)) f = None;; - flatMap None f = None;; -``` -``` -val getWithDefault : 'a option -> 'a -> 'a -``` -`getWithDefault optionalValue default` - -If `optionalValue` is `Some value`, returns `value`, otherwise `default` - -```ocaml - getWithDefault (Some 1812) 1066 = 1812;; - getWithDefault None 1066 = 1066;; -``` -``` -val orElse : 'a option -> 'a option -> 'a option -``` -`orElse optionalValue otherOptional` - -If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOptional` - -```ocaml - orElse (Some 1812) (Some 1066) = Some 1812;; - orElse None (Some 1066) = Some 1066;; - orElse None None = None;; -``` -``` -val isSome : 'a option -> bool -``` -Returns `true` if the argument is `Some value`, `false` otherwise - -``` -val isNone : 'a option -> bool -``` -Returns `true` if the argument is `None`, `false` otherwise - -``` -val eqU : 'a option -> 'b option -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -Uncurried version of `eq` - -``` -val eq : 'a option -> 'b option -> ('a -> 'b -> bool) -> bool -``` -`eq optValue1 optvalue2 predicate` - -Evaluates two optional values for equality with respect to a predicate function. - -If both `optValue1` and `optValue2` are `None`, returns `true`. - -If one of the arguments is `Some value` and the other is `None`, returns `false` - -If arguments are `Some value1` and `Some value2`, returns the result of `predicate value1 value2`; the `predicate` function must return a `bool` - -```ocaml - let clockEqual = (fun a b -> a mod 12 = b mod 12);; - eq (Some 3) (Some 15) clockEqual = true;; - eq (Some 3) None clockEqual = false;; - eq None (Some 3) clockEqual = false;; - eq None None clockEqual = true;; -``` -``` -val cmpU : 'a option -> 'b option -> ('a -> 'b -> int) Js.Fn.arity2 -> int -``` -Uncurried version of `cmp` - -``` -val cmp : 'a option -> 'b option -> ('a -> 'b -> int) -> int -``` -`cmp optValue1 optvalue2 comparisonFcn` - -Compares two optional values with respect to a comparison function - -If both `optValue1` and `optValue2` are `None`, returns 0. - -If the first argument is `Some value1` and the second is `None`, returns 1 (something is greater than nothing) - -If the first argument is `None` and the second is `Some value2`, returns \-1 (nothing is less than something) - -If the arguments are `Some value1` and `Some value2`, returns the result of `comparisonFcn value1 value2`; `comparisonFcn` takes two arguments and returns \-1 if the first argument is less than the second, 0 if the arguments are equal, and 1 if the first argument is greater than the second. - -```ocaml - let clockCompare = fun a b -> compare (a mod 12) (b mod 12);; - cmp (Some 3) (Some 15) clockCompare = 0;; - cmp (Some 3) (Some 14) clockCompare = 1;; - cmp (Some 2) (Some 15) clockCompare = -1;; - cmp None (Some 15) clockCompare = -1;; - cmp (Some 14) None clockCompare = 1;; - cmp None None clockCompare = 0;; -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Range.md b/docs/api/ml/melange/Belt-Range.md deleted file mode 100644 index fabb4625e..000000000 --- a/docs/api/ml/melange/Belt-Range.md +++ /dev/null @@ -1,62 +0,0 @@ - -# Module `Belt.Range` - -[`Belt.Range`](#) - -Utilities for a closed range `(from, start)` - -A small module to provide a inclusive range operations `[start, finsish]`, it use a for-loop internally instead of creating an array - -``` -val forEachU : int -> int -> (int -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : int -> int -> (int -> unit) -> unit -``` -`forEach start finish action` - -equivalent to `Belt.Array.(forEach (range start finish) action)` - -``` -val everyU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : int -> int -> (int -> bool) -> bool -``` -`every start finish p` - -equivalent to `Belt.Array.(every (range start finish) p )` - -``` -val everyByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val everyBy : int -> int -> step:int -> (int -> bool) -> bool -``` -`everyBy start finish ~step p` - -**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) - -equivalent to `Belt.Array.(every (rangeBy start finish ~step) p)` - -``` -val someU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : int -> int -> (int -> bool) -> bool -``` -`some start finish p` - -equivalent to `Belt.Array.(some (range start finish) p)` - -``` -val someByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val someBy : int -> int -> step:int -> (int -> bool) -> bool -``` -`someBy start finish ~step p` - -**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) - -equivalent to `Belt.Array.(some (rangeBy start finish ~step) p)` diff --git a/docs/api/ml/melange/Belt-Result.md b/docs/api/ml/melange/Belt-Result.md deleted file mode 100644 index 093023ba0..000000000 --- a/docs/api/ml/melange/Belt-Result.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Belt.Result` - -[`Belt.Result`](#) - -Utilities for result data type. - -`Belt.Result` is a data type with two variants: `Ok` and `Error`. Each of these variants can contain data, and those two pieces of data need not have the same data type. `Belt.Result` is useful when you need to not only determine whether some data is valid or not (use `Belt.Option` for that), but also keep information about the invalid data. - -In the examples, we presume the existence of two variables: - -```ocaml -let good = Ok 42 -let bad = Error "Invalid data" -``` -``` -type ('a, 'b) t = ('a, 'b) result = -``` -``` -| Ok of 'a -``` -``` -| Error of 'b -``` -``` - -``` -``` -val getExn : ('a, 'b) t -> 'a -``` -`getExn res` - -when `res` is `Ok n`, returns `n` when `res` is `Error m`, **raise** an exception - -```ocaml - getExn good = 42;; - getExn bad;; (* raises exception *) -``` -``` -val mapWithDefaultU : ('a, 'c) t -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b -``` -``` -val mapWithDefault : ('a, 'c) t -> 'b -> ('a -> 'b) -> 'b -``` -`mapWithDefault res default f` - -When `res` is `Ok n`, returns `f n`, otherwise `default`. - -```ocaml - mapWithDefault good 0 (fun x -> x / 2) = 21 - mapWithDefault bad 0 (fun x -> x / 2) = 0 -``` -``` -val mapU : ('a, 'c) t -> ('a -> 'b) Js.Fn.arity1 -> ('b, 'c) t -``` -``` -val map : ('a, 'c) t -> ('a -> 'b) -> ('b, 'c) t -``` -`map res f` - -When `res` is `Ok n`, returns `Ok (f n)`. Otherwise returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns an ordinary value. - -```ocaml - let f x = sqrt (float_of_int x) - map (Ok 64) f = Ok 8.0 - map (Error "Invalid data") f = Error "Invalid data" -``` -``` -val flatMapU : ('a, 'c) t -> ('a -> ('b, 'c) t) Js.Fn.arity1 -> ('b, 'c) t -``` -``` -val flatMap : ('a, 'c) t -> ('a -> ('b, 'c) t) -> ('b, 'c) t -``` -`flatMap res f` - -When `res` is `Ok n`, returns `f n`. Otherwise, returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns a `Belt.Result`. - -```ocaml -let recip x = - if x != 0.0 - then - Ok (1.0 /. x) - else - Error "Divide by zero" - - flatMap (Ok 2.0) recip = Ok 0.5 - flatMap (Ok 0.0) recip = Error "Divide by zero" - flatMap (Error "Already bad") recip = Error "Already bad" -``` -``` -val getWithDefault : ('a, 'b) t -> 'a -> 'a -``` -`getWithDefault res defaultValue` - -if `res` is `Ok n`, returns `n`, otherwise `default` - -```ocaml - getWithDefault (Ok 42) 0 = 42 - getWithDefault (Error "Invalid Data") = 0 -``` -``` -val isOk : ('a, 'b) t -> bool -``` -`isOk res` - -Returns `true` if `res` is of the form `Ok n`, `false` if it is the `Error e` variant. - -``` -val isError : ('a, 'b) t -> bool -``` -`isError res` - -Returns `true` if `res` is of the form `Error e`, `false` if it is the `Ok n` variant. - -``` -val eqU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) -> bool -``` -`eq res1 res2 f` - -Determine if two `Belt.Result` variables are equal with respect to an equality function. If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If one of `res1` and `res2` are of the form `Error e`, return false If both `res1` and `res2` are of the form `Error e`, return true - -```ocaml - let good1 = Ok 42 - let good2 = Ok 32 - let bad1 = Error "invalid" - let bad2 = Error "really invalid" - - let mod10equal a b = - a mod 10 == b mod 10 - - eq good1 good2 mod10equal = true - eq good1 bad1 mod10equal = false - eq bad2 good2 mod10equal = false - eq bad1 bad2 mod10equal = true -``` -``` -val cmpU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) -> int -``` -`cmp res1 res2 f` - -Compare two `Belt.Result` variables with respect to a comparison function. The comparison function returns \-1 if the first variable is "less than" the second, 0 if the two variables are equal, and 1 if the first is "greater than" the second. - -If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If `res1` is of the form `Error e` and `res2` of the form `Ok n`, return \-1 (nothing is less than something) If `res1` is of the form `Ok n` and `res2` of the form `Error e`, return 1 (something is greater than nothing) If both `res1` and `res2` are of the form `Error e`, return 0 (equal) - -```ocaml - let good1 = Ok 59 - let good2 = Ok 37 - let bad1 = Error "invalid" - let bad2 = Error "really invalid" - - let mod10cmp a b = - Pervasives.compare (a mod 10) (b mod 10) - - cmp (Ok 39) (Ok 57) mod10cmp = 1 - cmp (Ok 57) (Ok 39) mod10cmp = -1 - cmp (Ok 39) (Error "y") mod10cmp = 1 - cmp (Error "x") (Ok 57) mod10cmp = -1 - cmp (Error "x") (Error "y") mod10cmp = 0 -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-Set-Dict.md b/docs/api/ml/melange/Belt-Set-Dict.md deleted file mode 100644 index 249bfc951..000000000 --- a/docs/api/ml/melange/Belt-Set-Dict.md +++ /dev/null @@ -1,197 +0,0 @@ - -# Module `Set.Dict` - -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -``` -type ('value, 'identity) t -``` -``` -type ('value, 'id) cmp -``` -``` -val empty : ('value, 'id) t -``` -``` -val fromArray : 'value array -> cmp:('value, 'id) cmp -> ('value, 'id) t -``` -``` -val fromSortedArrayUnsafe : 'value array -> ('value, 'id) t -``` -``` -val isEmpty : (_, _) t -> bool -``` -``` -val has : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> bool -``` -``` -val add : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> ('value, 'id) t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -``` -val mergeMany : - ('value, 'id) t -> - 'value array -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val remove : - ('value, 'id) t -> - 'value -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -``` -val removeMany : - ('value, 'id) t -> - 'value array -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val union : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val intersect : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val diff : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val subset : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val cmp : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val eq : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> bool -``` -`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('value, 'id) t -> ('value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -``` -val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : ('value, 'id) t -> ('value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : ('value, 'id) t -> ('value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t -``` -``` -val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t -``` -`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : - ('value, 'id) t -> - ('value -> bool) Js.Fn.arity1 -> - ('value, 'id) t * ('value, 'id) t -``` -``` -val partition : - ('value, 'id) t -> - ('value -> bool) -> - ('value, 'id) t * ('value, 'id) t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : ('value, 'id) t -> int -``` -``` -val toList : ('value, 'id) t -> 'value list -``` -In increasing order - -``` -val toArray : ('value, 'id) t -> 'value array -``` -``` -val minimum : ('value, 'id) t -> 'value option -``` -``` -val minUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val maximum : ('value, 'id) t -> 'value option -``` -``` -val maxUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val get : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value option -``` -``` -val getUndefined : - ('value, 'id) t -> - 'value -> - cmp:('value, 'id) cmp -> - 'value Js.undefined -``` -``` -val getExn : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value -``` -``` -val split : - ('value, 'id) t -> - 'value -> - cmp:('value, 'id) cmp -> - (('value, 'id) t * ('value, 'id) t) * bool -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - -``` -val checkInvariantInternal : (_, _) t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/ml/melange/Belt-Set-Int.md b/docs/api/ml/melange/Belt-Set-Int.md deleted file mode 100644 index 697d28cf4..000000000 --- a/docs/api/ml/melange/Belt-Set-Int.md +++ /dev/null @@ -1,163 +0,0 @@ - -# Module `Set.Int` - -Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.Set`](./Belt-Set.md) - -``` -type value = int -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -``` -val mergeMany : t -> value array -> t -``` -``` -val remove : t -> value -> t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -``` -val removeMany : t -> value array -> t -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val cmp : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val eq : t -> t -> bool -``` -`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order - -``` -val toArray : t -> value array -``` -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/ml/melange/Belt-Set-String.md b/docs/api/ml/melange/Belt-Set-String.md deleted file mode 100644 index cd17e0b37..000000000 --- a/docs/api/ml/melange/Belt-Set-String.md +++ /dev/null @@ -1,163 +0,0 @@ - -# Module `Set.String` - -Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.Set`](./Belt-Set.md) - -``` -type value = string -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -``` -val mergeMany : t -> value array -> t -``` -``` -val remove : t -> value -> t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -``` -val removeMany : t -> value array -> t -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val cmp : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val eq : t -> t -> bool -``` -`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order - -``` -val toArray : t -> value array -``` -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/ml/melange/Belt-Set.md b/docs/api/ml/melange/Belt-Set.md deleted file mode 100644 index d923eb6f2..000000000 --- a/docs/api/ml/melange/Belt-Set.md +++ /dev/null @@ -1,377 +0,0 @@ - -# Module `Belt.Set` - -[`Belt.Set`](#) - -The top level provides generic **immutable** set operations. - -It also has three specialized inner modules [`Belt.Set.Int`](./Belt-Set-Int.md), [`Belt.Set.String`](./Belt-Set-String.md) and - -[`Belt.Set.Dict`](./Belt-Set-Dict.md): This module separates data from function which is more verbose but slightly more efficient - -A *immutable* sorted set module which allows customize *compare* behavior. - -The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. - -Example usage: - -```ocaml - module PairComparator = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c - end) - - let mySet = Belt.Set.make ~id:(module PairComparator) - let mySet2 = Belt.Set.add mySet (1, 2) -``` -The API documentation below will assume a predeclared comparator module for integers, IntCmp - -``` -module Int : sig ... end -``` -Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module String : sig ... end -``` -Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module Dict : sig ... end -``` -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -``` -type ('value, 'identity) t -``` -`('value, 'identity) t` - -`'value` is the element type - -`'identity` the identity of the collection - -``` -type ('value, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'value) -``` -The identity needed for making a set from scratch - -``` -val make : id:('value, 'id) id -> ('value, 'id) t -``` -`make ~id` creates a new set by taking in the comparator - -```ocaml - let s = make ~id:(module IntCmp) -``` -``` -val fromArray : 'value array -> id:('value, 'id) id -> ('value, 'id) t -``` -`fromArray xs ~id` - -```ocaml - toArray (fromArray [1;3;2;4] (module IntCmp)) = [1;2;3;4] -``` -``` -val fromSortedArrayUnsafe : - 'value array -> - id:('value, 'id) id -> - ('value, 'id) t -``` -`fromSortedArrayUnsafe xs ~id` - -The same as [`fromArray`](./#val-fromArray) except it is after assuming the input array `x` is already sorted - -**Unsafe** - -``` -val isEmpty : (_, _) t -> bool -``` -```ocaml - isEmpty (fromArray [||] ~id:(module IntCmp)) = true;; - isEmpty (fromArray [|1|] ~id:(module IntCmp)) = true;; -``` -``` -val has : ('value, 'id) t -> 'value -> bool -``` -```ocaml - let v = fromArray [|1;4;2;5|] ~id:(module IntCmp);; - has v 3 = false;; - has v 1 = true;; -``` -``` -val add : ('value, 'id) t -> 'value -> ('value, 'id) t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -```ocaml - let s0 = make ~id:(module IntCmp);; - let s1 = add s0 1 ;; - let s2 = add s1 2;; - let s3 = add s2 2;; - toArray s0 = [||];; - toArray s1 = [|1|];; - toArray s2 = [|1;2|];; - toArray s3 = [|1;2|];; - s2 == s3;; -``` -``` -val mergeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t -``` -`mergeMany s xs` - -Adding each of `xs` to `s`, note unlike [`add`](./#val-add), the reference of return value might be changed even if all values in `xs` exist `s` - -``` -val remove : ('value, 'id) t -> 'value -> ('value, 'id) t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|2;3;1;4;5|];; - let s1 = remove s0 1 ;; - let s2 = remove s1 3 ;; - let s3 = remove s2 3 ;; - - toArray s1 = [|2;3;4;5|];; - toArray s2 = [|2;4;5|];; - s2 == s3;; -``` -``` -val removeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t -``` -`removeMany s xs` - -Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` - -``` -val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -`union s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - toArray (union s0 s1) = [|1;2;3;4;5;6|] -``` -``` -val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -`intersect s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - toArray (intersect s0 s1) = [|2;3;5|] -``` -``` -val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -`diff s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - toArray (diff s0 s1) = [|6|];; - toArray (diff s1 s0) = [|1;4|];; -``` -``` -val subset : ('value, 'id) t -> ('value, 'id) t -> bool -``` -`subset s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - let s2 = intersect s0 s1;; - subset s2 s0 = true;; - subset s2 s1 = true;; - subset s1 s0 = false;; -``` -``` -val cmp : ('value, 'id) t -> ('value, 'id) t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. It compare `size` first and then iterate over each element following the order of elements - -``` -val eq : ('value, 'id) t -> ('value, 'id) t -> bool -``` -`eq s0 s1` - -returns true if toArray s0 = toArray s1 -``` -val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('value, 'id) t -> ('value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let acc = ref [] ;; - forEach s0 (fun x -> acc := x !acc);; - !acc = [6;5;3;2];; -``` -``` -val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a -``` -In increasing order. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - reduce s0 [] Belt.List.add = [6;5;3;2];; -``` -``` -val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : ('value, 'id) t -> ('value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : ('value, 'id) t -> ('value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. - -``` -val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t -``` -``` -val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t -``` -`keep m p` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : - ('value, 'id) t -> - ('value -> bool) Js.Fn.arity1 -> - ('value, 'id) t * ('value, 'id) t -``` -``` -val partition : - ('value, 'id) t -> - ('value -> bool) -> - ('value, 'id) t * ('value, 'id) t -``` -`partition m p` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : ('value, 'id) t -> int -``` -`size s` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - size s0 = 4;; -``` -``` -val toArray : ('value, 'id) t -> 'value array -``` -`toArray s0` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - toArray s0 = [|2;3;5;6|];; -``` -``` -val toList : ('value, 'id) t -> 'value list -``` -In increasing order - -**See** [`toArray`](./#val-toArray) - -``` -val minimum : ('value, 'id) t -> 'value option -``` -`minimum s0` - -returns the minimum element of the collection, None if it is empty -``` -val minUndefined : ('value, 'id) t -> 'value Js.undefined -``` -`minUndefined s0` - -returns the minimum element of the collection, undefined if it is empty -``` -val maximum : ('value, 'id) t -> 'value option -``` -`maximum s0` - -returns the maximum element of the collection, None if it is empty -``` -val maxUndefined : ('value, 'id) t -> 'value Js.undefined -``` -`maxUndefined s0` - -returns the maximum element of the collection, undefined if it is empty -``` -val get : ('value, 'id) t -> 'value -> 'value option -``` -`get s0 k` - -returns the reference of the value k' which is equivalent to k using the comparator specifiecd by this collection, None if it does not exist -``` -val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined -``` -**See** [`get`](./#val-get) - -``` -val getExn : ('value, 'id) t -> 'value -> 'value -``` -**See** [`get`](./#val-get) - -**raise** if not exist - -``` -val split : - ('value, 'id) t -> - 'value -> - (('value, 'id) t * ('value, 'id) t) * bool -``` -`split set ele` - -returns a tuple ((smaller, larger), present), present is true when ele exist in set -Below are operations only when better performance needed, it is still safe API but more verbose. More API will be exposed by needs - -``` -val getData : ('value, 'id) t -> ('value, 'id) Belt__.Belt_SetDict.t -``` -`getData s0` - -**Advanced usage only** - -returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing -``` -val getId : ('value, 'id) t -> ('value, 'id) id -``` -`getId s0` - -**Advanced usage only** - -returns the identity of s0 -``` -val packIdData : - id:('value, 'id) id -> - data:('value, 'id) Belt__.Belt_SetDict.t -> - ('value, 'id) t -``` -`packIdData ~id ~data` - -**Advanced usage only** - -returns the packed collection \ No newline at end of file diff --git a/docs/api/ml/melange/Belt-SortArray-Int.md b/docs/api/ml/melange/Belt-SortArray-Int.md deleted file mode 100644 index 44bd7b00f..000000000 --- a/docs/api/ml/melange/Belt-SortArray-Int.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `SortArray.Int` - -Specalized when key type is `int`, more efficient than the generic type - -This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined - -``` -type element = int -``` -``` -val strictlySortedLength : element array -> int -``` -The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed - -returns \+n means increasing order -n means negative order -``` -val isSorted : element array -> bool -``` -`sorted xs` return true if `xs` is in non strict increasing order - -``` -val stableSortInPlace : element array -> unit -``` -The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed - -``` -val stableSort : element array -> element array -``` -The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed - -``` -val binarySearch : element array -> element -> int -``` -If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. - -If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) - -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/ml/melange/Belt-SortArray-String.md b/docs/api/ml/melange/Belt-SortArray-String.md deleted file mode 100644 index 842fd2dd0..000000000 --- a/docs/api/ml/melange/Belt-SortArray-String.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `SortArray.String` - -Specalized when key type is `string`, more efficient than the generic type - -This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined - -``` -type element = string -``` -``` -val strictlySortedLength : element array -> int -``` -The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed - -returns \+n means increasing order -n means negative order -``` -val isSorted : element array -> bool -``` -`sorted xs` return true if `xs` is in non strict increasing order - -``` -val stableSortInPlace : element array -> unit -``` -The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed - -``` -val stableSort : element array -> element array -``` -The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed - -``` -val binarySearch : element array -> element -> int -``` -If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. - -If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) - -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/ml/melange/Belt-SortArray.md b/docs/api/ml/melange/Belt-SortArray.md deleted file mode 100644 index 67893ed3b..000000000 --- a/docs/api/ml/melange/Belt-SortArray.md +++ /dev/null @@ -1,81 +0,0 @@ - -# Module `Belt.SortArray` - -[`Belt.SortArray`](#) - -The top level provides some generic sort related utilities. - -It also has two specialized inner modules [`Belt.SortArray.Int`](./Belt-SortArray-Int.md) and [`Belt.SortArray.String`](./Belt-SortArray-String.md) - -A module for Array sort relevant utiliites - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -val strictlySortedLengthU : 'a array -> ('a -> 'a -> bool) Js.Fn.arity2 -> int -``` -``` -val strictlySortedLength : 'a array -> ('a -> 'a -> bool) -> int -``` -`strictlySortedLenght xs cmp` return `+n` means increasing order `-n` means negative order - -```ocaml - strictlySortedLength [|1;2;3;4;3|] (fun x y -> x < y) = 4;; - strictlySortedLength [||] (fun x y -> x < y) = 0;; - strictlySortedLength [|1|] (fun x y -> x < y) = 1;; - strictlySortedLength [|4;3;2;1|] (fun x y -> x < y) = -4;; -``` -``` -val isSortedU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> bool -``` -``` -val isSorted : 'a array -> ('a -> 'a -> int) -> bool -``` -`isSorted arr cmp` - -returns true if array is increasingly sorted (equal is okay ) isSorted \[\|1;1;2;3;4\|\] (fun x y -\> compare x y) = true -``` -val stableSortInPlaceByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> unit -``` -``` -val stableSortInPlaceBy : 'a array -> ('a -> 'a -> int) -> unit -``` -`stableSortBy xs cmp` - -Sort xs in place using comparator `cmp`, the stable means if the elements are equal, their order will be preserved - -``` -val stableSortByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a array -``` -``` -val stableSortBy : 'a array -> ('a -> 'a -> int) -> 'a array -``` -`stableSort xs cmp` - -returns a fresh array -The same as [`stableSortInPlaceBy`](./#val-stableSortInPlaceBy) except that `xs` is not modified - -``` -val binarySearchByU : 'a array -> 'a -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val binarySearchBy : 'a array -> 'a -> ('a -> 'a -> int) -> int -``` -If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. - -If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) - -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` - -```ocaml - binarySearchBy [|1;2;3;4;33;35;36|] 33 = 4;; - lnot (binarySearchBy [|1;3;5;7|] 4) = 2;; -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Belt.md b/docs/api/ml/melange/Belt.md deleted file mode 100644 index 59effce75..000000000 --- a/docs/api/ml/melange/Belt.md +++ /dev/null @@ -1,168 +0,0 @@ - -# Module `Belt` - -A stdlib shipped with Melange - -This stdlib is still in *beta* but we encourage you to try it out and give us feedback. - -**Motivation** - -The motivation for creating such library is to provide Melange users a better end-to-end user experience, since the original OCaml stdlib was not written with JS in mind. Below is a list of areas this lib aims to improve: - -1. Consistency in name convention: camlCase, and arguments order -2. Exception thrown functions are all suffixed with *Exn*, e.g, *getExn* -3. Better performance and smaller code size running on JS platform -**Name Convention** - -For higher order functions, it will be suffixed **U** if it takes uncurried callback. - -```ocaml - val forEach : 'a t -> ('a -> unit) -> unit - val forEachU : 'a t -> ('a -> unit [\@u]) -> unit -``` -In general, uncurried version will be faster, but it may be less familiar to people who have a background in functional programming. - -**A special encoding for collection safety** - -When we create a collection library for a custom data type we need a way to provide a comparator function. Take *Set* for example, suppose its element type is a pair of ints, it needs a custom *compare* function that takes two tuples and returns their order. The *Set* could not just be typed as ` Set.t (int * int) `, its customized *compare* function needs to manifest itself in the signature, otherwise, if the user creates another customized *compare* function, the two collection could mix which would result in runtime error. - -The original OCaml stdlib solved the problem using *functor* which creates a big closure at runtime and makes dead code elimination much harder. We use a phantom type to solve the problem: - -```ocaml - module Comparable1 = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c - end) - -let mySet1 = Belt.Set.make ~id:(module Comparable1) - -module Comparable2 = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c -end) - -let mySet2 = Belt.Set.make ~id:(module Comparable2) -``` -Here, the compiler would infer `mySet1` and `mySet2` having different type, so e.g. a \`merge\` operation that tries to merge these two sets will correctly fail. - -```ocaml - val mySet1 : ((int * int), Comparable1.identity) t - val mySet2 : ((int * int), Comparable2.identity) t -``` -`Comparable1.identity` and `Comparable2.identity` are not the same using our encoding scheme. - -**Collection Hierarchy** - -In general, we provide a generic collection module, but also create specialized modules for commonly used data type. Take *Belt.Set* for example, we provide: - -```ocaml - Belt.Set - Belt.Set.Int - Belt.Set.String -``` -The specialized modules *Belt.Set.Int*, *Belt.Set.String* are in general more efficient. - -Currently, both *Belt\_Set* and *Belt.Set* are accessible to users for some technical reasons, we **strongly recommend** users stick to qualified import, *Belt.Set*, we may hide the internal, *i.e*, *Belt\_Set* in the future - -``` -module Id : sig ... end -``` -[`Belt.Id`](./Belt-Id.md) - -``` -module Array : sig ... end -``` -[`Belt.Array`](./Belt-Array.md) - -``` -module SortArray : sig ... end -``` -[`Belt.SortArray`](./Belt-SortArray.md) - -``` -module MutableQueue : sig ... end -``` -[`Belt.MutableQueue`](./Belt-MutableQueue.md) - -``` -module MutableStack : sig ... end -``` -[`Belt.MutableStack`](./Belt-MutableStack.md) - -``` -module List : sig ... end -``` -[`Belt.List`](./Belt-List.md) - -``` -module Range : sig ... end -``` -[`Belt.Range`](./Belt-Range.md) - -``` -module Set : sig ... end -``` -[`Belt.Set`](./Belt-Set.md) - -``` -module Map : sig ... end -``` -[`Belt.Map`](./Belt-Map.md), - -``` -module MutableSet : sig ... end -``` -[`Belt.MutableSet`](./Belt-MutableSet.md) - -``` -module MutableMap : sig ... end -``` -[`Belt.MutableMap`](./Belt-MutableMap.md) - -``` -module HashSet : sig ... end -``` -[`Belt.HashSet`](./Belt-HashSet.md) - -``` -module HashMap : sig ... end -``` -[`Belt.HashMap`](./Belt-HashMap.md) - -``` -module Option : sig ... end -``` -[`Belt.Option`](./Belt-Option.md) - -[`Belt.Result`](./Belt-Result.md) - -Utilities for result data type. - -``` -module Result : sig ... end -``` -[`Belt.Result`](./Belt-Result.md) - -[`Belt.Int`](./Belt-Int.md) - -Utilities for Int. - -``` -module Int : sig ... end -``` -[`Belt.Int`](./Belt-Int.md) Utililites for Int - -[`Belt.Float`](./Belt-Float.md) - -Utilities for Float. - -``` -module Float : sig ... end -``` -[`Belt.Float`](./Belt-Float.md) Utililites for Float diff --git a/docs/api/ml/melange/Dom-Storage.md b/docs/api/ml/melange/Dom-Storage.md deleted file mode 100644 index 5196172ac..000000000 --- a/docs/api/ml/melange/Dom-Storage.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Module `Dom.Storage` - -``` -type t -``` -``` -val getItem : string -> t -> string option -``` -``` -val setItem : string -> string -> t -> unit -``` -``` -val removeItem : string -> t -> unit -``` -``` -val clear : t -> unit -``` -``` -val key : int -> t -> string option -``` -``` -val length : t -> int -``` -``` -val localStorage : t -``` -``` -val sessionStorage : t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Dom.md b/docs/api/ml/melange/Dom.md deleted file mode 100644 index 37f92a4ef..000000000 --- a/docs/api/ml/melange/Dom.md +++ /dev/null @@ -1,841 +0,0 @@ - -# Module `Dom` - -``` -type _baseClass -``` -``` -type animation -``` -``` -type cssStyleDeclaration -``` -``` -type cssStyleSheet -``` -``` -type 'a eventTarget_like -``` -``` -type eventTarget = _baseClass eventTarget_like -``` -``` -type _messagePort -``` -``` -type messagePort = _messagePort eventTarget_like -``` -``` -type _serviceWorker -``` -``` -type serviceWorker = _serviceWorker eventTarget_like -``` -``` -type _worker -``` -``` -type worker = _worker eventTarget_like -``` -``` -type 'a _workerGlobalScope -``` -``` -type workerGlobalScope = _baseClass _workerGlobalScope eventTarget_like -``` -``` -type _dedicatedWorkerGlobalScope -``` -``` -type dedicatedWorkerGlobalScope = - _dedicatedWorkerGlobalScope _workerGlobalScope eventTarget_like -``` -``` -type _serviceWorkerGlobalScope -``` -``` -type serviceWorkerGlobalScope = - _serviceWorkerGlobalScope _workerGlobalScope eventTarget_like -``` -``` -type _sharedWorkerGlobalScope -``` -``` -type sharedWorkerGlobalScope = - _sharedWorkerGlobalScope _workerGlobalScope eventTarget_like -``` -``` -type 'a _node -``` -``` -type 'a node_like = 'a _node eventTarget_like -``` -``` -type node = _baseClass node_like -``` -``` -type _attr -``` -``` -type attr = _attr node_like -``` -``` -type 'a _characterData -``` -``` -type 'a characterData_like = 'a _characterData node_like -``` -``` -type characterData = _baseClass characterData_like -``` -``` -type _cdataSection -``` -``` -type cdataSection = _cdataSection characterData_like -``` -``` -type _comment -``` -``` -type comment = _comment characterData_like -``` -``` -type 'a _document -``` -``` -type 'a document_like = 'a _document node_like -``` -``` -type document = _baseClass document_like -``` -``` -type _documentFragment -``` -``` -type documentFragment = _documentFragment node_like -``` -``` -type _documentType -``` -``` -type documentType = _documentType node_like -``` -``` -type domImplementation -``` -``` -type 'a _element -``` -``` -type 'a element_like = 'a _element node_like -``` -``` -type element = _baseClass element_like -``` -``` -type htmlCollection -``` -``` -type htmlFormControlsCollection -``` -``` -type htmlOptionsCollection -``` -``` -type intersectionObserver -``` -``` -type intersectionObserverEntry -``` -``` -type mutationObserver -``` -``` -type mutationRecord -``` -``` -type performanceObserver -``` -``` -type performanceObserverEntryList -``` -``` -type reportingObserver -``` -``` -type reportingObserverOptions -``` -``` -type resizeObserver -``` -``` -type resizeObserverEntry -``` -``` -type namedNodeMap -``` -``` -type nodeList -``` -``` -type radioNodeList -``` -``` -type processingInstruction -``` -``` -type _shadowRoot -``` -``` -type shadowRoot = _shadowRoot node_like -``` -``` -type _text -``` -``` -type text = _text characterData_like -``` -``` -type domRect -``` -``` -type dataTransfer -``` -``` -type domStringMap -``` -``` -type history -``` -``` -type _htmlDocument -``` -``` -type htmlDocument = _htmlDocument document_like -``` -``` -type 'a _htmlElement -``` -``` -type 'a htmlElement_like = 'a _htmlElement element_like -``` -``` -type htmlElement = _baseClass htmlElement_like -``` -``` -type _htmlAnchorElement -``` -``` -type htmlAnchorElement = _htmlAnchorElement htmlElement_like -``` -``` -type _htmlAreaElement -``` -``` -type htmlAreaElement = _htmlAreaElement htmlElement_like -``` -``` -type _htmlAudioElement -``` -``` -type htmlAudioElement = _htmlAudioElement htmlElement_like -``` -``` -type _htmlBaseElement -``` -``` -type htmlBaseElement = _htmlBaseElement htmlElement_like -``` -``` -type _htmlBodyElement -``` -``` -type htmlBodyElement = _htmlBodyElement htmlElement_like -``` -``` -type _htmlBrElement -``` -``` -type htmlBrElement = _htmlBrElement htmlElement_like -``` -``` -type _htmlButtonElement -``` -``` -type htmlButtonElement = _htmlButtonElement htmlElement_like -``` -``` -type _htmlCanvasElement -``` -``` -type htmlCanvasElement = _htmlCanvasElement htmlElement_like -``` -``` -type _htmlDataElement -``` -``` -type htmlDataElement = _htmlDataElement htmlElement_like -``` -``` -type _htmlDataListElement -``` -``` -type htmlDataListElement = _htmlDataListElement htmlElement_like -``` -``` -type _htmlDialogElement -``` -``` -type htmlDialogElement = _htmlDialogElement htmlElement_like -``` -``` -type _htmlDivElement -``` -``` -type htmlDivElement = _htmlDivElement htmlElement_like -``` -``` -type _htmlDlistElement -``` -``` -type htmlDlistElement = _htmlDlistElement htmlElement_like -``` -``` -type _htmlEmbedElement -``` -``` -type htmlEmbedElement = _htmlEmbedElement htmlElement_like -``` -``` -type _htmlFieldSetElement -``` -``` -type htmlFieldSetElement = _htmlFieldSetElement htmlElement_like -``` -``` -type _htmlFormElement -``` -``` -type htmlFormElement = _htmlFormElement htmlElement_like -``` -``` -type _htmlHeadElement -``` -``` -type htmlHeadElement = _htmlHeadElement htmlElement_like -``` -``` -type _htmlHeadingElement -``` -``` -type htmlHeadingElement = _htmlHeadingElement htmlElement_like -``` -``` -type _htmlHrElement -``` -``` -type htmlHrElement = _htmlHrElement htmlElement_like -``` -``` -type _htmlHtmlElement -``` -``` -type htmlHtmlElement = _htmlHtmlElement htmlElement_like -``` -``` -type _htmlIframeElement -``` -``` -type htmlIframeElement = _htmlIframeElement htmlElement_like -``` -``` -type _htmlImageElement -``` -``` -type htmlImageElement = _htmlImageElement htmlElement_like -``` -``` -type _htmlInputElement -``` -``` -type htmlInputElement = _htmlInputElement htmlElement_like -``` -``` -type _htmlLabelElement -``` -``` -type htmlLabelElement = _htmlLabelElement htmlElement_like -``` -``` -type _htmlLegendElement -``` -``` -type htmlLegendElement = _htmlLegendElement htmlElement_like -``` -``` -type _htmlLiElement -``` -``` -type htmlLiElement = _htmlLiElement htmlElement_like -``` -``` -type _htmlLinkElement -``` -``` -type htmlLinkElement = _htmlLinkElement htmlElement_like -``` -``` -type _htmlMapElement -``` -``` -type htmlMapElement = _htmlMapElement htmlElement_like -``` -``` -type _htmlMediaElement -``` -``` -type htmlMediaElement = _htmlMediaElement htmlElement_like -``` -``` -type _htmlMenuElement -``` -``` -type htmlMenuElement = _htmlMenuElement htmlElement_like -``` -``` -type _htmlMetaElement -``` -``` -type htmlMetaElement = _htmlMetaElement htmlElement_like -``` -``` -type _htmlMeterElement -``` -``` -type htmlMeterElement = _htmlMeterElement htmlElement_like -``` -``` -type _htmlModElement -``` -``` -type htmlModElement = _htmlModElement htmlElement_like -``` -``` -type _htmlOListElement -``` -``` -type htmlOListElement = _htmlOListElement htmlElement_like -``` -``` -type _htmlObjectElement -``` -``` -type htmlObjectElement = _htmlObjectElement htmlElement_like -``` -``` -type _htmlOptGroupElement -``` -``` -type htmlOptGroupElement = _htmlOptGroupElement htmlElement_like -``` -``` -type _htmlOptionElement -``` -``` -type htmlOptionElement = _htmlOptionElement htmlElement_like -``` -``` -type _htmlOutputElement -``` -``` -type htmlOutputElement = _htmlOutputElement htmlElement_like -``` -``` -type _htmlParagraphElement -``` -``` -type htmlParagraphElement = _htmlParagraphElement htmlElement_like -``` -``` -type _htmlParamElement -``` -``` -type htmlParamElement = _htmlParamElement htmlElement_like -``` -``` -type _htmlPreElement -``` -``` -type htmlPreElement = _htmlPreElement htmlElement_like -``` -``` -type _htmlProgressElement -``` -``` -type htmlProgressElement = _htmlProgressElement htmlElement_like -``` -``` -type _htmlQuoteElement -``` -``` -type htmlQuoteElement = _htmlQuoteElement htmlElement_like -``` -``` -type _htmlScriptElement -``` -``` -type htmlScriptElement = _htmlScriptElement htmlElement_like -``` -``` -type _htmlSelectElement -``` -``` -type htmlSelectElement = _htmlSelectElement htmlElement_like -``` -``` -type _htmlSlotElement -``` -``` -type htmlSlotElement = _htmlSlotElement htmlElement_like -``` -``` -type _htmlSourceElement -``` -``` -type htmlSourceElement = _htmlSourceElement htmlElement_like -``` -``` -type _htmlSpanElement -``` -``` -type htmlSpanElement = _htmlSpanElement htmlElement_like -``` -``` -type _htmlStyleElement -``` -``` -type htmlStyleElement = _htmlStyleElement htmlElement_like -``` -``` -type _htmlTableCaptionElement -``` -``` -type htmlTableCaptionElement = _htmlTableCaptionElement htmlElement_like -``` -``` -type _htmlTableCellElement -``` -``` -type htmlTableCellElement = _htmlTableCellElement htmlElement_like -``` -``` -type _htmlTableColElement -``` -``` -type htmlTableColElement = _htmlTableColElement htmlElement_like -``` -``` -type _htmlTableDataCellElement -``` -``` -type htmlTableDataCellElement = _htmlTableDataCellElement htmlElement_like -``` -``` -type _htmlTableElement -``` -``` -type htmlTableElement = _htmlTableElement htmlElement_like -``` -``` -type _htmlTableHeaderCellElement -``` -``` -type htmlTableHeaderCellElement = _htmlTableHeaderCellElement htmlElement_like -``` -``` -type _htmlTableRowElement -``` -``` -type htmlTableRowElement = _htmlTableRowElement htmlElement_like -``` -``` -type _htmlTableSectionElement -``` -``` -type htmlTableSectionElement = _htmlTableSectionElement htmlElement_like -``` -``` -type _htmlTextAreaElement -``` -``` -type htmlTextAreaElement = _htmlTextAreaElement htmlElement_like -``` -``` -type _htmlTimeElement -``` -``` -type htmlTimeElement = _htmlTimeElement htmlElement_like -``` -``` -type _htmlTitleElement -``` -``` -type htmlTitleElement = _htmlTitleElement htmlElement_like -``` -``` -type _htmlTrackElement -``` -``` -type htmlTrackElement = _htmlTrackElement htmlElement_like -``` -``` -type _htmlUlistElement -``` -``` -type htmlUlistElement = _htmlUlistElement htmlElement_like -``` -``` -type _htmlUnknownElement -``` -``` -type htmlUnknownElement = _htmlUnknownElement htmlElement_like -``` -``` -type _htmlVideoElement -``` -``` -type htmlVideoElement = _htmlVideoElement htmlElement_like -``` -``` -type location -``` -``` -type window -``` -``` -type _xmlDocument -``` -``` -type xmlDocument = _xmlDocument document_like -``` -``` -type 'a event_like -``` -``` -type event = _baseClass event_like -``` -``` -type 'a _uiEvent -``` -``` -type 'a uiEvent_like = 'a _uiEvent event_like -``` -``` -type uiEvent = _baseClass uiEvent_like -``` -``` -type _animationEvent -``` -``` -type animationEvent = _animationEvent event_like -``` -``` -type _beforeUnloadEvent -``` -``` -type beforeUnloadEvent = _beforeUnloadEvent event_like -``` -``` -type _clipboardEvent -``` -``` -type clipboardEvent = _clipboardEvent event_like -``` -``` -type _closeEvent -``` -``` -type closeEvent = _closeEvent event_like -``` -``` -type _compositionEvent -``` -``` -type compositionEvent = _compositionEvent uiEvent_like -``` -``` -type _customEvent -``` -``` -type customEvent = _customEvent event_like -``` -``` -type _dragEvent -``` -``` -type dragEvent = _dragEvent event_like -``` -``` -type _errorEvent -``` -``` -type errorEvent = _errorEvent event_like -``` -``` -type _focusEvent -``` -``` -type focusEvent = _focusEvent uiEvent_like -``` -``` -type _idbVersionChangeEvent -``` -``` -type idbVersionChangeEvent = _idbVersionChangeEvent event_like -``` -``` -type _inputEvent -``` -``` -type inputEvent = _inputEvent uiEvent_like -``` -``` -type _keyboardEvent -``` -``` -type keyboardEvent = _keyboardEvent uiEvent_like -``` -``` -type _messageEvent -``` -``` -type messageEvent = _messageEvent event_like -``` -``` -type 'a _mouseEvent -``` -``` -type 'a mouseEvent_like = 'a _mouseEvent uiEvent_like -``` -``` -type mouseEvent = _baseClass mouseEvent_like -``` -``` -type _pageTransitionEvent -``` -``` -type pageTransitionEvent = _pageTransitionEvent event_like -``` -``` -type _pointerEvent -``` -``` -type pointerEvent = _pointerEvent mouseEvent_like -``` -``` -type _popStateEvent -``` -``` -type popStateEvent = _popStateEvent event_like -``` -``` -type _progressEvent -``` -``` -type progressEvent = _progressEvent event_like -``` -``` -type _relatedEvent -``` -``` -type relatedEvent = _relatedEvent event_like -``` -``` -type _storageEvent -``` -``` -type storageEvent = _storageEvent event_like -``` -``` -type _svgZoomEvent -``` -``` -type svgZoomEvent = _svgZoomEvent event_like -``` -``` -type _timeEvent -``` -``` -type timeEvent = _timeEvent event_like -``` -``` -type _touchEvent -``` -``` -type touchEvent = _touchEvent uiEvent_like -``` -``` -type _trackEvent -``` -``` -type trackEvent = _trackEvent event_like -``` -``` -type _transitionEvent -``` -``` -type transitionEvent = _transitionEvent event_like -``` -``` -type _webGlContextEvent -``` -``` -type webGlContextEvent = _webGlContextEvent event_like -``` -``` -type _wheelEvent -``` -``` -type wheelEvent = _wheelEvent uiEvent_like -``` -``` -type range -``` -``` -type selection -``` -``` -type domTokenList -``` -``` -type domSettableTokenList -``` -``` -type nodeFilter = { -``` -`acceptNode : element -> int;` -``` -} -``` -``` -type nodeIterator -``` -``` -type treeWalker -``` -``` -type svgRect -``` -``` -type svgPoint -``` -``` -type eventPointerId -``` -``` -type messageChannel -``` -``` -module Storage : sig ... end -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Array.md b/docs/api/ml/melange/Js-Array.md deleted file mode 100644 index dff910797..000000000 --- a/docs/api/ml/melange/Js-Array.md +++ /dev/null @@ -1,179 +0,0 @@ - -# Module `Js.Array` - -Bindings to the functions in `Array.prototype` - -JavaScript Array API - -``` -type 'a t = 'a array -``` -``` -type 'a array_like = 'a Js.array_like -``` -``` -val from : 'a array_like -> 'a array -``` -``` -val fromMap : 'a array_like -> f:('a -> 'b) -> 'b array -``` -``` -val isArray : 'a -> bool -``` -``` -val length : 'a array -> int -``` -Mutating functions - -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> 'a t -> 'a t -``` -``` -val fill : value:'a -> ?start:int -> ?end_:int -> 'a t -> 'a t -``` -``` -val pop : 'a t -> 'a option -``` -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/push - -``` -val push : value:'a -> 'a t -> int -``` -``` -val pushMany : values:'a array -> 'a t -> int -``` -``` -val reverseInPlace : 'a t -> 'a t -``` -``` -val shift : 'a t -> 'a option -``` -``` -val sortInPlace : 'a t -> 'a t -``` -``` -val sortInPlaceWith : f:('a -> 'a -> int) -> 'a t -> 'a t -``` -``` -val spliceInPlace : start:int -> remove:int -> add:'a array -> 'a t -> 'a t -``` -``` -val removeFromInPlace : start:int -> 'a t -> 'a t -``` -``` -val removeCountInPlace : start:int -> count:int -> 'a t -> 'a t -``` -``` -val unshift : value:'a -> 'a t -> int -``` -``` -val unshiftMany : values:'a array -> 'a t -> int -``` -``` -val concat : other:'a t -> 'a t -> 'a t -``` -``` -val concatMany : arrays:'a t array -> 'a t -> 'a t -``` -``` -val includes : value:'a -> 'a t -> bool -``` -ES2015 - -``` -val join : ?sep:string -> 'a t -> string -``` -Accessor functions - -``` -val indexOf : value:'a -> ?start:int -> 'a t -> int -``` -``` -val lastIndexOf : value:'a -> 'a t -> int -``` -``` -val lastIndexOfFrom : value:'a -> start:int -> 'a t -> int -``` -``` -val copy : 'a t -> 'a t -``` -``` -val slice : ?start:int -> ?end_:int -> 'a t -> 'a t -``` -``` -val toString : 'a t -> string -``` -``` -val toLocaleString : 'a t -> string -``` -Iteration functions - -``` -val entries : 'a t -> (int * 'a) Js.iterator -``` -``` -val every : f:('a -> bool) -> 'a t -> bool -``` -``` -val everyi : f:('a -> int -> bool) -> 'a t -> bool -``` -``` -val filter : f:('a -> bool) -> 'a t -> 'a t -``` -``` -val filteri : f:('a -> int -> bool) -> 'a t -> 'a t -``` -``` -val find : f:('a -> bool) -> 'a t -> 'a option -``` -``` -val findi : f:('a -> int -> bool) -> 'a t -> 'a option -``` -``` -val findIndex : f:('a -> bool) -> 'a t -> int -``` -``` -val findIndexi : f:('a -> int -> bool) -> 'a t -> int -``` -``` -val forEach : f:('a -> unit) -> 'a t -> unit -``` -``` -val forEachi : f:('a -> int -> unit) -> 'a t -> unit -``` -``` -val keys : 'a t -> int Js.iterator -``` -``` -val map : f:('a -> 'b) -> 'a t -> 'b t -``` -``` -val mapi : f:('a -> int -> 'b) -> 'a t -> 'b t -``` -``` -val reduce : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val reducei : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val reduceRight : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val reduceRighti : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val some : f:('a -> bool) -> 'a t -> bool -``` -``` -val somei : f:('a -> int -> bool) -> 'a t -> bool -``` -``` -val values : 'a t -> 'a Js.iterator -``` -``` -val unsafe_get : 'a array -> int -> 'a -``` -``` -val unsafe_set : 'a array -> int -> 'a -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Bigint.md b/docs/api/ml/melange/Js-Bigint.md deleted file mode 100644 index d4b488ac6..000000000 --- a/docs/api/ml/melange/Js-Bigint.md +++ /dev/null @@ -1,71 +0,0 @@ - -# Module `Js.Bigint` - -Bindings to functions in JavaScript's `BigInt` - -JavaScript BigInt API - -``` -type t = Js.bigint -``` -``` -val make : 'a -> t -``` -`make repr` creates a new BigInt from the representation `repr`. `repr` can be a number, a string, boolean, etc. - -``` -val asIntN : precision:int -> t -> t -``` -`asIntN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as a signed integer. - -``` -val asUintN : precision:int -> t -> t -``` -`asUintN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as an unsigned integer. - -``` -type toLocaleStringOptions = { -``` -`style : string;` -`currency : string;` -``` -} -``` -``` -val toLocaleString : - locale:string -> - ?options:toLocaleStringOptions -> - t -> - string -``` -`toLocaleString bigint` returns a string with a language-sensitive representation of this BigInt. - -``` -val toString : t -> string -``` -`toString bigint` returns a string representing the specified BigInt value. - -``` -val neg : t -> t -``` -``` -val add : t -> t -> t -``` -``` -val sub : t -> t -> t -``` -Subtraction. - -``` -val mul : t -> t -> t -``` -Multiplication. - -``` -val div : t -> t -> t -``` -Division. - -``` -val rem : t -> t -> t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Blob.md b/docs/api/ml/melange/Js-Blob.md deleted file mode 100644 index 89b228319..000000000 --- a/docs/api/ml/melange/Js-Blob.md +++ /dev/null @@ -1,54 +0,0 @@ - -# Module `Js.Blob` - -Bindings to Blob - -``` -type t = Js.blob -``` -``` -type options = { -``` -`type_ : string option;` -A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". - -``endings : [ `transparent | `native ] option;`` -How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the blob without changing them. To convert newlines to the host system's native convention, specify the value native. - -``` -} -``` -``` -val make : string Js.iterator -> ?options:options -> unit -> t -``` -`make (Js.Array.values contents_array)` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. - -``` -val size : t -> float -``` -`size t` returns the size of the Blob in bytes - -``` -val type_ : t -> string -``` -`type_ t` returns the MIME type of the file. - -``` -val arrayBuffer : t -> Js.arrayBuffer Js.promise -``` -`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. - -``` -val bytes : t -> Js.uint8Array Js.promise -``` -`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the blob as an array of bytes. - -``` -val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t -``` -`slice ?start ?end_ ?contentType t` creates and returns a new Blob object which contains data from a subset of the blob on which it's called. - -``` -val text : t -> string Js.promise -``` -`text t` returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. diff --git a/docs/api/ml/melange/Js-Console.md b/docs/api/ml/melange/Js-Console.md deleted file mode 100644 index b68a7e2de..000000000 --- a/docs/api/ml/melange/Js-Console.md +++ /dev/null @@ -1,72 +0,0 @@ - -# Module `Js.Console` - -``` -val log : 'a -> unit -``` -``` -val log2 : 'a -> 'b -> unit -``` -``` -val log3 : 'a -> 'b -> 'c -> unit -``` -``` -val log4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val logMany : 'a array -> unit -``` -``` -val info : 'a -> unit -``` -``` -val info2 : 'a -> 'b -> unit -``` -``` -val info3 : 'a -> 'b -> 'c -> unit -``` -``` -val info4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val infoMany : 'a array -> unit -``` -``` -val warn : 'a -> unit -``` -``` -val warn2 : 'a -> 'b -> unit -``` -``` -val warn3 : 'a -> 'b -> 'c -> unit -``` -``` -val warn4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val warnMany : 'a array -> unit -``` -``` -val error : 'a -> unit -``` -``` -val error2 : 'a -> 'b -> unit -``` -``` -val error3 : 'a -> 'b -> 'c -> unit -``` -``` -val error4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val errorMany : 'a array -> unit -``` -``` -val trace : unit -> unit -``` -``` -val timeStart : string -> unit -``` -``` -val timeEnd : string -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Date.md b/docs/api/ml/melange/Js-Date.md deleted file mode 100644 index 3d66c2b18..000000000 --- a/docs/api/ml/melange/Js-Date.md +++ /dev/null @@ -1,319 +0,0 @@ - -# Module `Js.Date` - -Bindings to the functions in JS's `Date.prototype` - -JavaScript Date API - -``` -type t -``` -``` -val valueOf : t -> float -``` -returns the primitive value of this date, equivalent to getTime - -``` -val make : unit -> t -``` -returns a date representing the current time - -``` -val fromFloat : float -> t -``` -``` -val fromString : string -> t -``` -``` -val makeWithYM : year:float -> month:float -> t -``` -``` -val makeWithYMD : year:float -> month:float -> date:float -> t -``` -``` -val makeWithYMDH : year:float -> month:float -> date:float -> hours:float -> t -``` -``` -val makeWithYMDHM : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - t -``` -``` -val makeWithYMDHMS : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - seconds:float -> - t -``` -``` -val utcWithYM : year:float -> month:float -> float -``` -``` -val utcWithYMD : year:float -> month:float -> date:float -> float -``` -``` -val utcWithYMDH : - year:float -> - month:float -> - date:float -> - hours:float -> - float -``` -``` -val utcWithYMDHM : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - float -``` -``` -val utcWithYMDHMS : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - seconds:float -> - float -``` -``` -val now : unit -> float -``` -returns the number of milliseconds since Unix epoch - -``` -val parseAsFloat : string -> float -``` -returns NaN if passed invalid date string - -``` -val getDate : t -> float -``` -return the day of the month (1-31) - -``` -val getDay : t -> float -``` -returns the day of the week (0-6) - -``` -val getFullYear : t -> float -``` -``` -val getHours : t -> float -``` -``` -val getMilliseconds : t -> float -``` -``` -val getMinutes : t -> float -``` -``` -val getMonth : t -> float -``` -returns the month (0-11) - -``` -val getSeconds : t -> float -``` -``` -val getTime : t -> float -``` -returns the number of milliseconds since Unix epoch - -``` -val getTimezoneOffset : t -> float -``` -``` -val getUTCDate : t -> float -``` -return the day of the month (1-31) - -``` -val getUTCDay : t -> float -``` -returns the day of the week (0-6) - -``` -val getUTCFullYear : t -> float -``` -``` -val getUTCHours : t -> float -``` -``` -val getUTCMilliseconds : t -> float -``` -``` -val getUTCMinutes : t -> float -``` -``` -val getUTCMonth : t -> float -``` -returns the month (0-11) - -``` -val getUTCSeconds : t -> float -``` -``` -val setDate : date:float -> t -> float -``` -``` -val setFullYear : year:float -> t -> float -``` -``` -val setFullYearM : year:float -> month:float -> t -> float -``` -``` -val setFullYearMD : year:float -> month:float -> date:float -> t -> float -``` -``` -val setHours : hours:float -> t -> float -``` -``` -val setHoursM : hours:float -> minutes:float -> t -> float -``` -``` -val setHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float -``` -``` -val setHoursMSMs : - hours:float -> - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setMilliseconds : milliseconds:float -> t -> float -``` -``` -val setMinutes : minutes:float -> t -> float -``` -``` -val setMinutesS : minutes:float -> seconds:float -> t -> float -``` -``` -val setMinutesSMs : - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setMonth : month:float -> t -> float -``` -``` -val setMonthD : month:float -> date:float -> t -> float -``` -``` -val setSeconds : seconds:float -> t -> float -``` -``` -val setSecondsMs : seconds:float -> milliseconds:float -> t -> float -``` -``` -val setTime : time:float -> t -> float -``` -``` -val setUTCDate : date:float -> t -> float -``` -``` -val setUTCFullYear : year:float -> t -> float -``` -``` -val setUTCFullYearM : year:float -> month:float -> t -> float -``` -``` -val setUTCFullYearMD : year:float -> month:float -> date:float -> t -> float -``` -``` -val setUTCHours : hours:float -> t -> float -``` -``` -val setUTCHoursM : hours:float -> minutes:float -> t -> float -``` -``` -val setUTCHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float -``` -``` -val setUTCHoursMSMs : - hours:float -> - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setUTCMilliseconds : milliseconds:float -> t -> float -``` -``` -val setUTCMinutes : minutes:float -> t -> float -``` -``` -val setUTCMinutesS : minutes:float -> seconds:float -> t -> float -``` -``` -val setUTCMinutesSMs : - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setUTCMonth : month:float -> t -> float -``` -``` -val setUTCMonthD : month:float -> date:float -> t -> float -``` -``` -val setUTCSeconds : seconds:float -> t -> float -``` -``` -val setUTCSecondsMs : seconds:float -> milliseconds:float -> t -> float -``` -``` -val setUTCTime : time:float -> t -> float -``` -``` -val toDateString : t -> string -``` -``` -val toISOString : t -> string -``` -``` -val toJSON : t -> string option -``` -``` -val toJSONUnsafe : t -> string -``` -``` -val toLocaleDateString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val toLocaleTimeString : t -> string -``` -``` -val toString : t -> string -``` -``` -val toTimeString : t -> string -``` -``` -val toUTCString : t -> string -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Dict.md b/docs/api/ml/melange/Js-Dict.md deleted file mode 100644 index 3a0f74eb6..000000000 --- a/docs/api/ml/melange/Js-Dict.md +++ /dev/null @@ -1,74 +0,0 @@ - -# Module `Js.Dict` - -Utility functions to treat a JS object as a dictionary - -``` -type 'a t = 'a Js.dict -``` -Dictionary type (ie an '{ }' JS object). However it is restricted to hold a single type; therefore values must have the same type. - -This Dictionary type is mostly used with the `Js_json.t` type. - -``` -type key = string -``` -Key type - -``` -val get : 'a t -> key -> 'a option -``` -`get dict key` returns `None` if the `key` is not found in the dictionary, `Some value` otherwise - -``` -val unsafeGet : 'a t -> key -> 'a -``` -`unsafeGet dict key` return the value if the `key` exists, otherwise an **undefined** value is returned. Must be used only when the existence of a key is certain. (i.e. when having called `keys` function previously. - -```ocaml -Array.iter (fun key -> Js.log (Js_dict.unsafeGet dic key)) (Js_dict.keys dict) -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`set dict key value` sets the `key`/`value` in `dict` - -``` -val keys : 'a t -> string array -``` -`keys dict` returns all the keys in the dictionary `dict` - -``` -val empty : unit -> 'a t -``` -`empty ()` returns an empty dictionary - -``` -val unsafeDeleteKey : (string t -> string -> unit) Js.Fn.arity2 -``` -Experimental internal function - -``` -val entries : 'a t -> (key * 'a) array -``` -`entries dict` returns the key value pairs in `dict` (ES2017) - -``` -val values : 'a t -> 'a array -``` -`values dict` returns the values in `dict` (ES2017) - -``` -val fromList : (key * 'a) list -> 'a t -``` -`fromList entries` creates a new dictionary containing each `(key, value)` pair in `entries` - -``` -val fromArray : (key * 'a) array -> 'a t -``` -`fromArray entries` creates a new dictionary containing each `(key, value)` pair in `entries` - -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -`map f dict` maps `dict` to a new dictionary with the same keys, using `f` to map each value diff --git a/docs/api/ml/melange/Js-Exn.md b/docs/api/ml/melange/Js-Exn.md deleted file mode 100644 index afea42336..000000000 --- a/docs/api/ml/melange/Js-Exn.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Js.Exn` - -Utilities for dealing with Js exceptions - -``` -type t -``` -``` -type exn += private -``` -``` -| Error of t -``` -``` - -``` -``` -val asJsExn : exn -> t option -``` -``` -val stack : t -> string option -``` -``` -val message : t -> string option -``` -``` -val name : t -> string option -``` -``` -val fileName : t -> string option -``` -``` -val isCamlExceptionOrOpenVariant : 'a -> bool -``` -internal use only - -``` -val anyToExnInternal : 'a -> exn -``` -`anyToExnInternal obj` will take any value `obj` and wrap it in a Js.Exn.Error if given value is not an exn already. If `obj` is an exn, it will return `obj` without any changes. - -This function is mostly useful for cases where you want to unify a type of a value that potentially is either exn, a JS error, or any other JS value really (e.g. for a value passed to a Promise.catch callback) - -IMPORTANT: This is an internal API and may be changed / removed any time in the future. - -```ocaml - switch (Js.Exn.unsafeAnyToExn("test")) { - | Js.Exn.Error(v) => - switch (Js.Exn.message(v)) { - | Some(str) => Js.log("We won't end up here") - | None => Js.log2("We will land here: ", v) - } - } -``` -``` -val raiseError : string -> 'a -``` -Raise Js exception Error object with stacktrace - -``` -val raiseEvalError : string -> 'a -``` -``` -val raiseRangeError : string -> 'a -``` -``` -val raiseReferenceError : string -> 'a -``` -``` -val raiseSyntaxError : string -> 'a -``` -``` -val raiseTypeError : string -> 'a -``` -``` -val raiseUriError : string -> 'a -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-File.md b/docs/api/ml/melange/Js-File.md deleted file mode 100644 index 71a732734..000000000 --- a/docs/api/ml/melange/Js-File.md +++ /dev/null @@ -1,72 +0,0 @@ - -# Module `Js.File` - -Bindings to File - -``` -type t = Js.file -``` -``` -type options = { -``` -`type_ : string option;` -A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". - -``endings : [ `transparent | `native ] option;`` -How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the file without changing them. To convert newlines to the host system's native convention, specify the value native. - -`lastModified : float option;` -A number representing the number of milliseconds between the Unix time epoch and when the file was last modified. Defaults to a value of Date.now(). - -``` -} -``` -``` -val make : - string Js.iterator -> - filename:string -> - ?options:options -> - unit -> - t -``` -`make contents_array ~filename` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. - -``` -val lastModified : t -> float -``` -`lastModified t` accesses the read-only property of the File interface, which provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. - -``` -val name : t -> string -``` -The `name t` read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property. - -``` -val size : t -> float -``` -`size t` returns the size of the File in bytes - -``` -val type_ : t -> string -``` -`type_ t` returns the MIME type of the file. - -``` -val arrayBuffer : t -> Js.arrayBuffer Js.promise -``` -`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. - -``` -val bytes : t -> Js.uint8Array Js.promise -``` -`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the file as an array of bytes. - -``` -val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t -``` -`slice ?start ?end_ ?contentType t` creates and returns a new File object which contains data from a subset of the file on which it's called. - -``` -val text : t -> string Js.promise -``` -`text t` returns a Promise that resolves with a string containing the contents of the file, interpreted as UTF-8. diff --git a/docs/api/ml/melange/Js-Float.md b/docs/api/ml/melange/Js-Float.md deleted file mode 100644 index fa4803615..000000000 --- a/docs/api/ml/melange/Js-Float.md +++ /dev/null @@ -1,140 +0,0 @@ - -# Module `Js.Float` - -Bindings to functions in JavaScript's `Number` that deal with floats - -Provides functions for inspecting and manipulating `float`s - -``` -type t = float -``` -``` -val _NaN : t -``` -The special value "Not a Number" - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) MDN -``` -val isNaN : t -> bool -``` -Tests if the given value is `_NaN` - -Note that both `_NaN = _NaN` and `_NaN == _NaN` will return `false`. `isNaN` is therefore necessary to test for `_NaN`. - -**Returns** `true` if the given value is `_NaN`, `false` otherwise - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) MDN -``` -val isFinite : t -> bool -``` -Tests if the given value is finite - -**Returns** `true` if the given value is a finite number, `false` otherwise - -```ocaml -(* returns [false] *) -let _ = Js.Float.isFinite infinity - -(* returns [false] *) -let _ = Js.Float.isFinite neg_infinity - -(* returns [false] *) -let _ = Js.Float.isFinite _NaN - -(* returns [true] *) -let _ = Js.Float.isFinite 1234 -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) MDN -``` -val toExponential : ?digits:int -> t -> string -``` -Formats a `float` using exponential (scientific) notation - -**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). - -**Returns** a `string` representing the given value in exponential notation - -The output will be rounded or padded with zeroes if necessary. - -raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) -```ocaml - Js.Float.toExponential 77.1234 = "7.71234e+1" - Js.Float.toExponential 77. = "7.7e+1" - Js.Float.toExponential ~digits:2 77.1234 = "7.71e+1" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN -``` -val toFixed : ?digits:int -> t -> string -``` -Formats a `float` using fixed point notation - -**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). Defaults to `0`. - -**Returns** a `string` representing the given value in fixed-point notation (usually) - -The output will be rounded or padded with zeroes if necessary. - -raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) -```ocaml - Js.Float.toFixed 12345.6789 = "12346" - Js.Float.toFixed 1.2e21 = "1.2e+21" - Js.Float.toFixed ~digits:1 12345.6789 = "12345.7" - Js.Float.toFixed ~digits:2 0. = "0.00" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toFixed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) MDN -``` -val toPrecision : ?digits:int -> t -> string -``` -Formats a `float` using some fairly arbitrary rules - -**digits** specifies how many digits should appear in total. The value must between 0 and some arbitrary number that's hopefully at least larger than 20 (for Node it's 21. Why? Who knows). - -**Returns** a `string` representing the given value in fixed-point or scientific notation - -The output will be rounded or padded with zeroes if necessary. - -`toPrecision` differs from `toFixed` in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. - -raises `RangeError` if digits is not in the range accepted by this function (what do you mean "vague"?) -```ocaml - Js.Float.toPrecision 12345.6789 = "12345.6789" - Js.Float.toPrecision 1.2e21 = "1.2e+21" - Js.Float.toPrecision ~digits:1 12345.6789 = "1e+4" - Js.Float.toPrecision ~digits:2 0. = "0.0" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN -``` -val toString : ?radix:int -> t -> string -``` -Formats a `float` as a string - -**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). - -**Returns** a `string` representing the given value in fixed-point (usually) - -raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) -```ocaml - Js.Float.toString 12345.6789 = "12345.6789" - Js.Float.toString ~radix:2 6. = "110" - Js.Float.toString ~radix:2 3.14 = "11.001000111101011100001010001111010111000010100011111" - Js.Float.toString ~radix:16 3735928559. = "deadbeef" - Js.Float.toString ~radix:36 123.456 = "3f.gez4w97ry0a18ymf6qadcxr" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN -``` -val fromString : string -> t -``` -Parses the given `string` into a `float` using JavaScript semantics - -**Returns** the number as a `float` if successfully parsed, `_NaN` otherwise. - -```ocaml -Js.Float.fromString "123" = 123. -Js.Float.fromString "12.3" = 12.3 -Js.Float.fromString "" = 0. -Js.Float.fromString "0x11" = 17. -Js.Float.fromString "0b11" = 3. -Js.Float.fromString "0o11" = 9. -Js.Float.fromString "foo" = _NaN -Js.Float.fromString "100a" = _NaN -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-FormData.md b/docs/api/ml/melange/Js-FormData.md deleted file mode 100644 index 57c30522d..000000000 --- a/docs/api/ml/melange/Js-FormData.md +++ /dev/null @@ -1,90 +0,0 @@ - -# Module `Js.FormData` - -Bindings to FormData - -``` -type t -``` -``` -type entryValue -``` -The values returned by the \`get`,All`\` and iteration functions is either a string or a Blob. Melange uses an abstract type and defers to users of the API to handle it according to their application needs. - -``` -val make : unit -> t -``` -`make ()` creates a new `FormData` object, initially empty. - -``` -val append : - name:string -> - value:[ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> - t -> - unit -``` -`append t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. - -``` -val appendBlob : - name:string -> - value:[ `Blob of Js.blob | `File of Js.file ] -> - ?filename:string -> - t -> - unit -``` -`appendBlob t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. This method differs from `append` in that instances in the Blob hierarchy can pass a third filename argument. - -``` -val delete : name:string -> t -> unit -``` -`delete t ~name` deletes a key and its value(s) from a FormData object. - -``` -val get : name:string -> t -> entryValue option -``` -`get t ~name` returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use [`getAll`](./#val-getAll) instead. - -``` -val getAll : name:string -> t -> entryValue array -``` -`getAll t ~name` returns all the values associated with a given key from within a FormData object. - -``` -val set : - name:string -> - [ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> - t -> - unit -``` -`set t ~name ~value` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. - -``` -val setBlob : - name:string -> - [ `Blob of Js.blob | `File of Js.file ] -> - ?filename:string -> - t -> - unit -``` -`setBlob t ~name ~value ?filename` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. This method differs from `set` in that instances in the Blob hierarchy can pass a third filename argument. - -``` -val has : name:string -> t -> bool -``` -`has ~name t` returns whether a FormData object contains a certain key. - -``` -val keys : t -> string Js.iterator -``` -`keys t` returns an iterator which iterates through all keys contained in the FormData. The keys are strings. - -``` -val values : t -> entryValue Js.iterator -``` -`values t` returns an iterator which iterates through all values contained in the FormData. The values are strings or Blob objects. - -``` -val entries : t -> (string * entryValue) Js.iterator -``` -`entries t` returns an iterator which iterates through all key/value pairs contained in the FormData. diff --git a/docs/api/ml/melange/Js-Global.md b/docs/api/ml/melange/Js-Global.md deleted file mode 100644 index b8e00b08f..000000000 --- a/docs/api/ml/melange/Js-Global.md +++ /dev/null @@ -1,150 +0,0 @@ - -# Module `Js.Global` - -Bindings to functions in the JS global namespace - -Contains functions available in the global scope (`window` in a browser context) - -``` -type intervalId -``` -Identify an interval started by [`setInterval`](./#val-setInterval) - -``` -type timeoutId -``` -Identify timeout started by [`setTimeout`](./#val-setTimeout) - -``` -val clearInterval : intervalId -> unit -``` -Clear an interval started by [`setInterval`](./#val-setInterval) - -```ocaml -(* API for a somewhat aggressive snoozing alarm clock *) - -let interval = ref Js.Nullable.null - -let remind () = - Js.log "Wake Up!"; - IO.punchSleepyGuy () - -let snooze mins = - interval := Js.Nullable.return (Js.Global.setInterval remind (mins * 60 * 1000)) - -let cancel () = - Js.Nullable.iter !interval (fun[\@u] intervalId -> Js.Global.clearInterval intervalId) -``` -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) MDN -``` -val clearTimeout : timeoutId -> unit -``` -Clear a timeout started by [`setTimeout`](./#val-setTimeout) - -```ocaml -(* A simple model of a code monkey's brain *) - -let timer = ref Js.Nullable.null - -let work () = - IO.closeHackerNewsTab () - -let procrastinate mins = - Js.Nullable.iter !timer (fun[\@u] timer -> Js.Global.clearTimeout timer); - timer := Js.Nullable.return (Js.Global.setTimeout work (mins * 60 * 1000)) -``` -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout) MDN -``` -val setInterval : f:(unit -> unit) -> int -> intervalId -``` -*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls - -**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN -```ocaml -(* Will count up and print the count to the console every second *) - -let count = ref 0 - -let tick () = - count := !count + 1; Js.log (string_of_int !count) - -let _ = - Js.Global.setInterval tick 1000 -``` -``` -val setIntervalFloat : f:(unit -> unit) -> float -> intervalId -``` -*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls - -**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN -```ocaml -(* Will count up and print the count to the console every second *) - -let count = ref 0 - -let tick () = - count := !count + 1; Js.log (string_of_int !count) - -let _ = - Js.Global.setIntervalFloat tick 1000.0 -``` -``` -val setTimeout : f:(unit -> unit) -> int -> timeoutId -``` -Execute a callback after a specified delay (in milliseconds) - -**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN -```ocaml -(* Prints "Timed out!" in the console after one second *) - -let message = "Timed out!" - -let _ = - Js.Global.setTimeout (fun () -> Js.log message) 1000 -``` -``` -val setTimeoutFloat : f:(unit -> unit) -> float -> timeoutId -``` -Execute a callback after a specified delay (in milliseconds) - -**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN -```ocaml -(* Prints "Timed out!" in the console after one second *) - -let message = "Timed out!" - -let _ = - Js.Global.setTimeoutFloat (fun () -> Js.log message) 1000.0 -``` -``` -val encodeURI : string -> string -``` -URL-encodes a string. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) MDN -``` -val decodeURI : string -> string -``` -Decodes a URL-enmcoded string produced by `encodeURI` - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) MDN -``` -val encodeURIComponent : string -> string -``` -URL-encodes a string, including characters with special meaning in a URI. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) MDN -``` -val decodeURIComponent : string -> string -``` -Decodes a URL-enmcoded string produced by `encodeURIComponent` - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) MDN \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Int.md b/docs/api/ml/melange/Js-Int.md deleted file mode 100644 index 08c28ca4a..000000000 --- a/docs/api/ml/melange/Js-Int.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `Js.Int` - -Bindings to functions in JavaScript's `Number` that deal with ints - -Provides functions for inspecting and manipulating `int`s - -``` -type t = int -``` -If we use number, we need coerce to int32 by adding \`\|0\`, otherwise \`+0\` can be wrong. Most JS API is float oriented, it may overflow int32 or comes with `NAN` - -``` -val toExponential : ?digits:t -> t -> string -``` -Formats an `int` using exponential (scientific) notation - -**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). - -**Returns** a `string` representing the given value in exponential notation - -The output will be rounded or padded with zeroes if necessary. - -raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) -```ocaml - Js.Int.toExponential 77 = "7.7e+1" - Js.Int.toExponential ~digits:2 77 = "7.70e+1" - Js.Int.toExponential ~digits:2 5678 = "5.68e+3" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN -``` -val toPrecision : ?digits:t -> t -> string -``` -Formats an `int` using some fairly arbitrary rules - -**digits** specifies how many digits should appear in total. The value must between 1 and some 100. - -**Returns** a `string` representing the given value in fixed-point or scientific notation - -The output will be rounded or padded with zeroes if necessary. - -`toPrecision` differs from [`Js.Float.toFixed`](./Js-Float.md#val-toFixed) in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. - -raises `RangeError` if digits is not between 1 and 100. -```ocaml - Js.Int.toPrecision 123456789 = "123456789" - Js.Int.toPrecision ~digits:2 123456789 = "1.2e+8" - Js.Int.toPrecision ~digits:2 0 = "0.0" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN -``` -val toString : ?radix:t -> t -> string -``` -Formats an `int` as a string - -**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). - -**Returns** a `string` representing the given value in fixed-point (usually) - -raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) -```ocaml - Js.Int.toString 123456789 = "123456789" - Js.Int.toString ~radix:2 6 = "110" - Js.Int.toString ~radix:16 3735928559 = "deadbeef" - Js.Int.toString ~radix:36 123456 = "2n9c" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN -``` -val toFloat : t -> float -``` -``` -val equal : t -> t -> bool -``` -``` -val max : t -``` -``` -val min : t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Iterator.md b/docs/api/ml/melange/Js-Iterator.md deleted file mode 100644 index 3f07302ff..000000000 --- a/docs/api/ml/melange/Js-Iterator.md +++ /dev/null @@ -1,25 +0,0 @@ - -# Module `Js.Iterator` - -Bindings to functions on `Iterator` - -``` -type 'a t = 'a Js.iterator -``` -``` -type 'a value = { -``` -`done_ : bool option;` -`value : 'a option;` -``` -} -``` -``` -val next : 'a t -> 'a value -``` -``` -val toArray : 'a t -> 'a array -``` -``` -val toArrayWithMapper : 'a t -> f:('a -> 'b) -> 'b array -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Json.md b/docs/api/ml/melange/Js-Json.md deleted file mode 100644 index f23f571bf..000000000 --- a/docs/api/ml/melange/Js-Json.md +++ /dev/null @@ -1,285 +0,0 @@ - -# Module `Js.Json` - -Utility functions to manipulate JSON values - -Efficient JSON encoding using JavaScript API @see \ MDN - - -### Types - -``` -type t -``` -The JSON data structure - -``` -type _ kind = -``` -``` -| String : string kind -``` -``` -| Number : float kind -``` -``` -| Object : t Js.dict kind -``` -``` -| Array : t array kind -``` -``` -| Boolean : bool kind -``` -``` -| Null : t Js.null kind -``` -``` - -``` -Underlying type of a JSON value - -``` -type tagged_t = -``` -``` -| JSONFalse -``` -``` -| JSONTrue -``` -``` -| JSONNull -``` -``` -| JSONString of string -``` -``` -| JSONNumber of float -``` -``` -| JSONObject of t Js.dict -``` -``` -| JSONArray of t array -``` -``` - -``` - -### Accessor - -``` -val classify : t -> tagged_t -``` -``` -val test : 'a -> 'b kind -> bool -``` -`test v kind` returns true if `v` is of `kind` - -``` -val decodeString : t -> string option -``` -`decodeString json` returns `Some s` if `json` is a string, `None` otherwise - -``` -val decodeNumber : t -> float option -``` -`decodeNumber json` returns `Some n` if `json` is a number, `None` otherwise - -``` -val decodeObject : t -> t Js.dict option -``` -`decodeObject json` returns `Some o` if `json` is an object, `None` otherwise - -``` -val decodeArray : t -> t array option -``` -`decodeArray json` returns `Some a` if `json` is an array, `None` otherwise - -``` -val decodeBoolean : t -> bool option -``` -`decodeBoolean json` returns `Some b` if `json` is a boolean, `None` otherwise - -``` -val decodeNull : t -> 'a Js.null option -``` -`decodeNull json` returns `Some null` if `json` is a null, `None` otherwise - - -### Construtors - -Those functions allows the construction of an arbitrary complex JSON values. - -``` -val null : t -``` -`null` is the singleton null JSON value - -``` -val string : string -> t -``` -`string s` makes a JSON string of the `string` `s` - -``` -val number : float -> t -``` -`number n` makes a JSON number of the `float` `n` - -``` -val boolean : bool -> t -``` -`boolean b` makes a JSON boolean of the `bool` `b` - -``` -val object_ : t Js.dict -> t -``` -`object_ dict` makes a JSON object of the `Js.dict` `dict` - -``` -val array : t array -> t -``` -`array a` makes a JSON array of the `Js.Json.t array` `a` - -The functions below are specialized for specific array type which happened to be already JSON object in the Melange runtime. Therefore they are more efficient (constant time rather than linear conversion). - -``` -val stringArray : string array -> t -``` -`stringArray a` makes a JSON array of the `string array` `a` - -``` -val numberArray : float array -> t -``` -`numberArray a` makes a JSON array of the `float array` `a` - -``` -val booleanArray : bool array -> t -``` -`booleanArray` makes a JSON array of the `bool array` `a` - -``` -val objectArray : t Js.dict array -> t -``` -`objectArray a` makes a JSON array of the `JsDict.t array` `a` - - -### String conversion - -``` -val parseExn : string -> t -``` -`parseExn s` parses the string `s` into a JSON data structure - -**Returns** a JSON data structure - -raises `SyntaxError` if given string is not a valid JSON. Note SyntaxError is a JavaScript exception. -```ocaml -(* parse a simple JSON string *) - -let json = - try - Js.Json.parseExn {| "foo" |} - with - | _ -> failwith "Error parsing JSON string" -in -match Js.Json.classify json with -| Js.Json.JSONString value -> Js.log value -| _ -> failwith "Expected a string" -``` -```ocaml -(* parse a complex JSON string *) - -let getIds s = - let json = - try - Js.Json.parseExn s - with - | _ -> failwith "Error parsing JSON string" - in - match Js.Json.classify json with - | Js.Json.JSONObject value -> - (* In this branch, compiler infer value : Js.Json.t Js.dict *) - begin match Js.Dict.get value "ids" with - | Some ids -> - begin match Js.Json.classify ids with - | Js.Json.JSONArray ids -> - (* In this branch compiler infer ids : Js.Json.t array *) - ids - | _ -> failwith "Expected an array" - end - | None -> failwith "Expected an `ids` property" - end - | _ -> failwith "Expected an object" - - (* prints `1, 2, 3` *) - let _ = - Js.log (getIds {| { "ids" : [1, 2, 3] } |}) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) MDN -``` -val stringify : t -> string -``` -`stringify json` formats the JSON data structure as a string - -**Returns** the string representation of a given JSON data structure - -```ocaml -(* Creates and stringifies a simple JS object *) - -let dict = Js.Dict.empty () in -Js.Dict.set dict "name" (Js.Json.string "John Doe"); -Js.Dict.set dict "age" (Js.Json.number 30.0); -Js.Dict.set dict "likes" - (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); - -Js.log (Js.Json.stringify (Js.Json.object_ dict)) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN -``` -val stringifyWithSpace : t -> int -> string -``` -`stringify json` formats the JSON data structure as a string - -**Returns** the string representation of a given JSON data structure - -```ocaml -(* Creates and stringifies a simple JS object with spacing *) - -let dict = Js.Dict.empty () in -Js.Dict.set dict "name" (Js.Json.string "John Doe"); -Js.Dict.set dict "age" (Js.Json.number 30.0); -Js.Dict.set dict "likes" - (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); - - Js.log (Js.Json.stringifyWithSpace (Js.Json.object_ dict) 2) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN -``` -val stringifyAny : 'a -> string option -``` -`stringifyAny value` formats any `value` into a JSON string - -```ocaml - (* prints ``"foo", "bar"`` *) - Js.log (Js.Json.stringifyAny [| "foo"; "bar" |]) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN -Best-effort serialization, it tries to seralize as many objects as possible and deserialize it back - -``` -val deserializeUnsafe : string -> 'a -``` -It is unsafe in two aspects - -- It may throw during parsing -- when you cast it to a specific type, it may have a type mismatch -``` -val serializeExn : 'a -> string -``` -It will raise in such situations: - -- The object can not be serlialized to a JSON -- There are cycles -- Some JS engines can not stringify deeply nested json objects \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Map.md b/docs/api/ml/melange/Js-Map.md deleted file mode 100644 index 51c7817bf..000000000 --- a/docs/api/ml/melange/Js-Map.md +++ /dev/null @@ -1,49 +0,0 @@ - -# Module `Js.Map` - -Bindings to functions in `Map` - -ES6 Map API - -``` -type ('k, 'v) t -``` -``` -val make : unit -> ('k, 'v) t -``` -``` -val fromArray : ('k * 'v) array -> ('k, 'v) t -``` -``` -val toArray : ('k, 'v) t -> ('k * 'v) array -``` -``` -val size : ('k, 'v) t -> int -``` -``` -val has : key:'k -> ('k, 'v) t -> bool -``` -``` -val get : key:'k -> ('k, 'v) t -> 'v option -``` -``` -val set : key:'k -> value:'v -> ('k, 'v) t -> ('k, 'v) t -``` -``` -val clear : ('k, 'v) t -> unit -``` -``` -val delete : key:'k -> ('k, 'v) t -> bool -``` -``` -val forEach : f:('v -> 'k -> ('k, 'v) t -> unit) -> ('k, 'v) t -> unit -``` -``` -val keys : ('k, 'v) t -> 'k Js.iterator -``` -``` -val values : ('k, 'v) t -> 'v Js.iterator -``` -``` -val entries : ('k, 'v) t -> ('k * 'v) Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Math.md b/docs/api/ml/melange/Js-Math.md deleted file mode 100644 index 5d799dbda..000000000 --- a/docs/api/ml/melange/Js-Math.md +++ /dev/null @@ -1,299 +0,0 @@ - -# Module `Js.Math` - -Bindings to the functions in the `Math` object - -JavaScript Math API - -``` -val _E : float -``` -Euler's number - -``` -val _LN2 : float -``` -natural logarithm of 2 - -``` -val _LN10 : float -``` -natural logarithm of 10 - -``` -val _LOG2E : float -``` -base 2 logarithm of E - -``` -val _LOG10E : float -``` -base 10 logarithm of E - -``` -val _PI : float -``` -Pi... (ratio of the circumference and diameter of a circle) - -``` -val _SQRT1_2 : float -``` -square root of 1/2 - -``` -val _SQRT2 : float -``` -square root of 2 - -``` -val abs_int : int -> int -``` -absolute value - -``` -val abs_float : float -> float -``` -absolute value - -``` -val acos : float -> float -``` -arccosine in radians, can return NaN - -``` -val acosh : float -> float -``` -hyperbolic arccosine in raidans, can return NaN, ES2015 - -``` -val asin : float -> float -``` -arcsine in radians, can return NaN - -``` -val asinh : float -> float -``` -hyperbolic arcsine in raidans, ES2015 - -``` -val atan : float -> float -``` -arctangent in radians - -``` -val atanh : float -> float -``` -hyperbolic arctangent in radians, can return NaN, ES2015 - -``` -val atan2 : y:float -> x:float -> float -``` -arctangent of the quotient of x and y, mostly... this one's a bit weird - -``` -val cbrt : float -> float -``` -cube root, can return NaN, ES2015 - -``` -val unsafe_ceil_int : float -> int -``` -may return values not representable by `int` - -``` -val ceil_int : float -> int -``` -smallest int greater than or equal to the argument - -``` -val ceil_float : float -> float -``` -smallest float greater than or equal to the argument - -``` -val clz32 : int -> int -``` -number of leading zero bits of the argument's 32 bit int representation, ES2015 - -``` -val cos : float -> float -``` -cosine in radians - -``` -val cosh : float -> float -``` -hyperbolic cosine in radians, ES2015 - -``` -val exp : float -> float -``` -natural exponentional - -``` -val expm1 : float -> float -``` -natural exponential minus 1, ES2015 - -``` -val unsafe_floor_int : float -> int -``` -may return values not representable by `int` - -``` -val floor_int : float -> int -``` -largest int greater than or equal to the arugment - -``` -val floor_float : float -> float -``` -``` -val fround : float -> float -``` -round to nearest single precision float, ES2015 - -``` -val hypot : float -> float -> float -``` -pythagorean equation, ES2015 - -``` -val hypotMany : float array -> float -``` -generalized pythagorean equation, ES2015 - -``` -val imul : int -> int -> int -``` -32-bit integer multiplication, ES2015 - -``` -val log : float -> float -``` -natural logarithm, can return NaN - -``` -val log1p : float -> float -``` -natural logarithm of 1 \+ the argument, can return NaN, ES2015 - -``` -val log10 : float -> float -``` -base 10 logarithm, can return NaN, ES2015 - -``` -val log2 : float -> float -``` -base 2 logarithm, can return NaN, ES2015 - -``` -val max_int : int -> int -> int -``` -max value - -``` -val maxMany_int : int array -> int -``` -max value - -``` -val max_float : float -> float -> float -``` -max value - -``` -val maxMany_float : float array -> float -``` -max value - -``` -val min_int : int -> int -> int -``` -min value - -``` -val minMany_int : int array -> int -``` -min value - -``` -val min_float : float -> float -> float -``` -min value - -``` -val minMany_float : float array -> float -``` -min value - -``` -val pow_float : base:float -> exp:float -> float -``` -base to the power of the exponent - -``` -val random : unit -> float -``` -random number in \[0,1) - -``` -val random_int : int -> int -> int -``` -random number in \[min,max) - -``` -val unsafe_round : float -> int -``` -rounds to nearest integer, returns a value not representable as `int` if NaN - -``` -val round : float -> float -``` -rounds to nearest integer - -``` -val sign_int : int -> int -``` -the sign of the argument, 1, \-1 or 0, ES2015 - -``` -val sign_float : float -> float -``` -the sign of the argument, 1, \-1, 0, \-0 or NaN, ES2015 - -``` -val sin : float -> float -``` -sine in radians - -``` -val sinh : float -> float -``` -hyperbolic sine in radians, ES2015 - -``` -val sqrt : float -> float -``` -square root, can return NaN - -``` -val tan : float -> float -``` -tangent in radians - -``` -val tanh : float -> float -``` -hyperbolic tangent in radians, ES2015 - -``` -val unsafe_trunc : float -> int -``` -truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 - -``` -val trunc : float -> float -``` -truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 diff --git a/docs/api/ml/melange/Js-Null.md b/docs/api/ml/melange/Js-Null.md deleted file mode 100644 index 46aa576d8..000000000 --- a/docs/api/ml/melange/Js-Null.md +++ /dev/null @@ -1,74 +0,0 @@ - -# Module `Js.Null` - -Utility functions on [`null`](./Js.md#type-null) - -Provides functionality for dealing with the `'a Js.null` type - -``` -type +'a t = 'a Js.null -``` -Local alias for `'a Js.null` - -``` -val return : 'a -> 'a t -``` -Constructs a value of `'a Js.null` containing a value of `'a` - -``` -val empty : 'a t -``` -The empty value, `null` - -``` -val getUnsafe : 'a t -> 'a -``` -``` -val getExn : 'a t -> 'a -``` -``` -val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t -``` -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -Maps the contained value using the given function - -If `'a Js.null` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.null` - -```ocaml -let maybeGreetWorld (maybeGreeting: string Js.null) = - Js.Null.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") -``` -``` -val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit -``` -Iterates over the contained value with the given function - -If `'a Js.null` contains a value, that value is unwrapped and applied to the given function. - -```ocaml -let maybeSay (maybeMessage: string Js.null) = - Js.Null.iter maybeMessage ~f:(fun message -> Js.log message) -``` -``` -val fromOption : 'a option -> 'a t -``` -Maps `'a option` to `'a Js.null` - - - -
Some a -> return a -
None -> empty -
- -``` -val toOption : 'a t -> 'a option -``` -Maps `'a Js.null` to `'a option` - - - -
return a -> Some a -
empty -> None -
diff --git a/docs/api/ml/melange/Js-Nullable.md b/docs/api/ml/melange/Js-Nullable.md deleted file mode 100644 index c4f7ffb3c..000000000 --- a/docs/api/ml/melange/Js-Nullable.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `Js.Nullable` - -Utility functions on [`nullable`](./Js.md#type-nullable) - -Contains functionality for dealing with values that can be both `null` and `undefined` - -``` -type +'a t = 'a Js.nullable -``` -Local alias for `'a Js.nullable` - -``` -val return : 'a -> 'a t -``` -Constructs a value of `'a Js.nullable` containing a value of `'a` - -``` -val isNullable : 'a t -> bool -``` -Returns `true` if the given value is `null` or `undefined`, `false` otherwise - -``` -val null : 'a t -``` -The `null` value of type `'a Js.nullable` - -``` -val undefined : 'a t -``` -The `undefined` value of type `'a Js.nullable` - -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -``` -val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t -``` -Binds the contained value using the given function - -If `'a Js.nullable` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.nullable` - -```ocaml -let maybeGreetWorld (maybeGreeting: string Js.nullable) = - Js.Nullable.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") -``` -``` -val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit -``` -Iterates over the contained value with the given function - -If `'a Js.nullable` contains a value, that value is unwrapped and applied to the given function. - -```ocaml -let maybeSay (maybeMessage: string Js.nullable) = - Js.Nullable.iter maybeMessage ~f:(fun message -> Js.log message) -``` -``` -val fromOption : 'a option -> 'a t -``` -Maps `'a option` to `'a Js.nullable` - - - -
Some a -> return a -
None -> undefined -
- -``` -val toOption : 'a t -> 'a option -``` -Maps `'a Js.nullable` to `'a option` - - - -
return a -> Some a -
undefined -> None -
null -> None -
diff --git a/docs/api/ml/melange/Js-Obj.md b/docs/api/ml/melange/Js-Obj.md deleted file mode 100644 index 7ff457710..000000000 --- a/docs/api/ml/melange/Js-Obj.md +++ /dev/null @@ -1,19 +0,0 @@ - -# Module `Js.Obj` - -Utility functions on \`Js.t\` JS objects - -``` -val empty : unit -> < .. > Js.t -``` -``` -val assign : < .. > Js.t -> < .. > Js.t -> < .. > Js.t -``` -``` -val merge : < .. > Js.t -> < .. > Js.t -> < .. > Js.t -``` -`merge obj1 obj2` assigns the properties in `obj2` to a copy of `obj1`. The function returns a new object, and both arguments are not mutated - -``` -val keys : _ Js.t -> string array -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Promise.md b/docs/api/ml/melange/Js-Promise.md deleted file mode 100644 index 2a493825c..000000000 --- a/docs/api/ml/melange/Js-Promise.md +++ /dev/null @@ -1,57 +0,0 @@ - -# Module `Js.Promise` - -Bindings to JS `Promise` functions - -Specialized bindings to Promise. Note: For simplicity, this binding does not track the error type, it treat it as an opaque type - -``` -type +'a t = 'a Js.promise -``` -``` -type error -``` -``` -val make : - (resolve:('a -> unit) Js.Fn.arity1 -> - reject:(exn -> unit) Js.Fn.arity1 -> - unit) -> - 'a t -``` -``` -val resolve : 'a -> 'a t -``` -``` -val reject : exn -> 'a t -``` -``` -val all : 'a t array -> 'a array t -``` -``` -val all2 : ('a0 t * 'a1 t) -> ('a0 * 'a1) t -``` -``` -val all3 : ('a0 t * 'a1 t * 'a2 t) -> ('a0 * 'a1 * 'a2) t -``` -``` -val all4 : ('a0 t * 'a1 t * 'a2 t * 'a3 t) -> ('a0 * 'a1 * 'a2 * 'a3) t -``` -``` -val all5 : - ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t) -> - ('a0 * 'a1 * 'a2 * 'a3 * 'a4) t -``` -``` -val all6 : - ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t * 'a5 t) -> - ('a0 * 'a1 * 'a2 * 'a3 * 'a4 * 'a5) t -``` -``` -val race : 'a t array -> 'a t -``` -``` -val then_ : ('a -> 'b t) -> 'a t -> 'b t -``` -``` -val catch : (error -> 'a t) -> 'a t -> 'a t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Re.md b/docs/api/ml/melange/Js-Re.md deleted file mode 100644 index 36f5547da..000000000 --- a/docs/api/ml/melange/Js-Re.md +++ /dev/null @@ -1,178 +0,0 @@ - -# Module `Js.Re` - -Bindings to the functions in `RegExp.prototype` - -Provides bindings for JavaScript Regular Expressions - - -##### Syntax sugar - -Melange provides a bit of syntax sugar for regex literals: `[%re "/foo/g"]` will evaluate to a [`t`](./#type-t) that can be passed around and used like usual. - -**Note:** This is not an immutable API. A RegExp object with the `global` ("g") flag set will modify the [`lastIndex`](./#val-lastIndex) property when the RegExp object is used, and subsequent uses will continue the search from the previous [`lastIndex`](./#val-lastIndex). - -```ocaml -let maybeMatches = Js.String.exec ~str:"banana" [\[%re "/na+/g"\]] -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) JavaScript API reference on MDN -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular\_Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) JavaScript Regular Expressions Guide on MDN -``` -type t = Js.re -``` -the RegExp object - -``` -type result -``` -the result of a executing a RegExp on a string - -``` -val captures : result -> string Js.nullable array -``` -an array of the match and captures, the first is the full match and the remaining are the substring captures - -``` -val index : result -> int -``` -0-based index of the match in the input string - -``` -val input : result -> string -``` -the original input string - -``` -val fromString : string -> t -``` -Constructs a RegExp object ([`t`](./#type-t)) from a string - -Regex literals (`[%re "/.../"]`) should generally be preferred, but `fromString` is very useful when you need to insert a string into a regex. - -```ocaml -(* A function that extracts the content of the first element with the given tag *) - -let contentOf tag xmlString = - Js.Re.fromString ("<" ^ tag ^ ">(.*?)<\\/" ^ tag ^">") - |> Js.Re.exec ~str:xmlString - |> function - | Some result -> Js.Nullable.toOption (Js.Re.captures result).(1) - | None -> None -``` -``` -val fromStringWithFlags : string -> flags:string -> t -``` -Constructs a RegExp object ([`t`](./#type-t)) from a string with the given `flags` - -See [`fromString`](./#val-fromString) - -Valid flags: - -
g global -
i ignore case -
m multiline -
u unicode (es2015) -
y sticky (es2015) -
- - -``` -val flags : t -> string -``` -returns the enabled flags as a string - -``` -val global : t -> bool -``` -returns a bool indicating whether the `global` flag is set - -``` -val ignoreCase : t -> bool -``` -returns a bool indicating whether the `ignoreCase` flag is set - -``` -val lastIndex : t -> int -``` -returns the index where the next match will start its search - -This property will be modified when the RegExp object is used, if the `global` ("g") flag is set. - -```ocaml -(* Finds and prints successive matches *) - -let re = [%re "/ab*/g"] in -let str = "abbcdefabh" in - -let break = ref false in -while not !break do - match re |> Js.Re.exec ~str with - | None -> break := true - | Some result -> - Js.Nullable.iter (Js.Re.captures result).(0) ((fun match_ -> - let next = string_of_int (Js.Re.lastIndex re) in - Js.log ("Found " ^ match_ ^ ". Next match starts at " ^ next))) -done -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/lastIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) MDN -``` -val setLastIndex : t -> int -> unit -``` -sets the index at which the next match will start its search from - -``` -val multiline : t -> bool -``` -returns a bool indicating whether the `multiline` flag is set - -``` -val source : t -> string -``` -returns the pattern as a string - -``` -val sticky : t -> bool -``` -returns a bool indicating whether the `sticky` flag is set - -``` -val unicode : t -> bool -``` -returns a bool indicating whether the `unicode` flag is set - -``` -val exec : str:string -> t -> result option -``` -executes a search on a given string using the given RegExp object - -**returns** `Some` [`result`](./#type-result) if a match is found, `None` otherwise - -```ocaml -(* Match "quick brown" followed by "jumps", ignoring characters in between - * Remember "brown" and "jumps" - * Ignore case - *) - -let re = [%re "/quick\s(brown).+?(jumps)/ig"] in -let result = re |. Js.Re.exec ~str:"The Quick Brown Fox Jumps Over The Lazy Dog" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/exec](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) MDN -``` -val test : str:string -> t -> bool -``` -tests whether the given RegExp object will match a given string - -**returns** `true` if a match is found, `false` otherwise - -```ocaml -(* A simple implementation of Js.String.startsWith *) - -let str = "hello world!" - -let startsWith target substring = - Js.Re.fromString ("^" ^ substring) - |. Js.Re.test ~str:target - -let () = Js.log (str |. startsWith "hello") (* prints "true" *) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) MDN \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Set.md b/docs/api/ml/melange/Js-Set.md deleted file mode 100644 index bd1087307..000000000 --- a/docs/api/ml/melange/Js-Set.md +++ /dev/null @@ -1,43 +0,0 @@ - -# Module `Js.Set` - -Bindings to functions in `Set` - -ES6 Set API - -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val fromArray : 'a array -> 'a t -``` -``` -val toArray : 'a t -> 'a array -``` -``` -val size : 'a t -> int -``` -``` -val add : value:'a -> 'a t -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val delete : value:'a -> 'a t -> bool -``` -``` -val forEach : f:('a -> unit) -> 'a t -> unit -``` -``` -val has : value:'a -> 'a t -> bool -``` -``` -val values : 'a t -> 'a Js.iterator -``` -``` -val entries : 'a t -> ('a * 'a) Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-String.md b/docs/api/ml/melange/Js-String.md deleted file mode 100644 index ff90c544a..000000000 --- a/docs/api/ml/melange/Js-String.md +++ /dev/null @@ -1,464 +0,0 @@ - -# Module `Js.String` - -Bindings to the functions in `String.prototype` - -JavaScript String API - -``` -type t = string -``` -``` -val make : 'a -> t -``` -`make value` converts the given value to a string - -```ocaml - make 3.5 = "3.5";; - make [|1;2;3|]) = "1,2,3";; -``` -``` -val fromCharCode : int -> t -``` -`fromCharCode n` creates a string containing the character corresponding to that number; *n* ranges from 0 to 65535. If out of range, the lower 16 bits of the value are used. Thus, `fromCharCode 0x1F63A` gives the same result as `fromCharCode 0xF63A`. - -```ocaml - fromCharCode 65 = "A";; - fromCharCode 0x3c8 = {js|ψ|js};; - fromCharCode 0xd55c = {js|한|js};; - fromCharCode -64568 = {js|ψ|js};; -``` -``` -val fromCharCodeMany : int array -> t -``` -`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given numbers, using the same rules as `fromCharCode`. - -```ocaml - fromCharCodeMany([|0xd55c, 0xae00, 33|]) = {js|한글!|js};; -``` -``` -val fromCodePoint : int -> t -``` -`fromCodePoint n` creates a string containing the character corresponding to that numeric code point. If the number is not a valid code point, **raises** `RangeError`. Thus, `fromCodePoint 0x1F63A` will produce a correct value, unlike `fromCharCode 0x1F63A`, and `fromCodePoint -5` will raise a `RangeError`. - -```ocaml - fromCodePoint 65 = "A";; - fromCodePoint 0x3c8 = {js|ψ|js};; - fromCodePoint 0xd55c = {js|한|js};; - fromCodePoint 0x1f63a = {js|😺|js};; -``` -``` -val fromCodePointMany : int array -> t -``` -`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given code point numbers, using the same rules as `fromCodePoint`. - -```ocaml - fromCodePointMany([|0xd55c; 0xae00; 0x1f63a|]) = {js|한글😺|js} -``` -``` -val length : t -> int -``` -`length s` returns the length of the given string. - -```ocaml - length "abcd" = 4;; -``` -``` -val get : t -> int -> t -``` -`get s n` returns as a string the character at the given index number. If `n` is out of range, this function returns `undefined`, so at some point this function may be modified to return `t option`. - -```ocaml - get "Reason" 0 = "R";; - get "Reason" 4 = "o";; - get {js|Rẽasöń|js} 5 = {js|ń|js};; -``` -``` -val charAt : index:int -> t -> t -``` -`charAt ~index s` gets the character at position `index` within string `s`. If `index` is negative or greater than the length of `s`, returns the empty string. If the string contains characters outside the range `\u0000-\uffff`, it will return the first 16-bit value at that position in the string. - -```ocaml - charAt ~index:0 "Reason" = "R" - charAt ~index:12 "Reason" = ""; - charAt ~index:5 {js|Rẽasöń|js} = {js|ń|js} -``` -``` -val charCodeAt : index:int -> t -> float -``` -`charCodeAt s ~index` returns the character code at position `index` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to `0x10000`. The return type is `float` because this function returns `NaN` if `index` is less than zero or greater than the length of the string. - -```ocaml - charCodeAt ~index:0 {js|😺|js} = 0xd83d - codePointAt ~index:0 {js|😺|js} = Some 0x1f63a -``` -``` -val codePointAt : index:int -> t -> int option -``` -`codePointAt s ~index` returns the code point at position `index` within string `s` as a `Some` value. The return value handles code points greater than or equal to `0x10000`. If there is no code point at the given position, the function returns `None`. - -```ocaml - codePointAt ~index:1 {js|¿😺?|js} = Some 0x1f63a - codePointAt ~index:5 "abc" = None -``` -ES2015 - -``` -val concat : other:t -> t -> t -``` -`concat ~other:str2 str1` returns a new string with `str2` added after `str1`. - -```ocaml - concat ~other:"bell" "cow" = "cowbell";; -``` -``` -val concatMany : strings:t array -> t -> t -``` -`concatMany ~strings original` returns a new string consisting of each item of the array of strings `strings` added to the `original` string. - -```ocaml - concatMany ~strings:[|"2nd"; "3rd"; "4th"|] "1st" = "1st2nd3rd4th";; -``` -``` -val endsWith : suffix:t -> ?len:int -> t -> bool -``` -`endsWith ~suffix ?len str` returns `true` if the `str` ends with `suffix`, `false` otherwise. If `len` is specified, \`endsWith\` only takes into account the first `len` characters. - -```ocaml - endsWith ~suffix:"cd" ~len:4 "abcd" = true;; - endsWith ~suffix:"cd" ~len:3 "abcde" = false;; - endsWith ~suffix:"cde" ~len:99 "abcde" = true;; - endsWith ~suffix:"ple" ~len:7 "example.dat" = true;; - endsWith ~suffix:"World!" "Hello, World!" = true;; - endsWith ~suffix:"world!" "Hello, World!" = false;; (* case-sensitive *) - endsWith ~suffix:"World" "Hello, World!" = false;; (* exact match *) -``` -``` -val includes : search:t -> ?start:int -> t -> bool -``` -`includes ~search ?start s` returns `true` if `search` is found anywhere within `s` starting at character number `start` (where 0 is the first character), `false` otherwise. - -```ocaml - includes ~search:"gram" "programmer" = true;; - includes ~search:"er" "programmer" = true;; - includes ~search:"pro" "programmer" = true;; - includes ~search:"xyz" "programmer" = false;; - includes ~search:"gram" ~start:1 "programmer" = true;; - includes ~search:"gram" ~start:4 "programmer" = false;; - includes ~search:{js|한|js} ~start:1 {js|대한민국|js} = true;; -``` -``` -val indexOf : search:t -> ?start:int -> t -> int -``` -`indexOf ~search ?start s` returns the position at which `search` was found within `s` starting at character position `start`, or `-1` if `search` is not found in that portion of `s`. The return value is relative to the beginning of the string, no matter where the search started from. - -```ocaml - indexOf ~search:"ok" "bookseller" = 2;; - indexOf ~search:"sell" "bookseller" = 4;; - indexOf ~search:"ee" "beekeeper" = 1;; - indexOf ~search:"xyz" "bookseller" = -1;; - indexOf ~search:"ok" ~start:1 "bookseller" = 2;; - indexOf ~search:"sell" ~start:2 "bookseller" = 4;; - indexOf ~search:"sell" ~start:5 "bookseller" = -1;; -``` -``` -val lastIndexOf : search:t -> ?start:int -> t -> int -``` -`lastIndexOf ~search ~start s` returns the position of the *last* occurrence of `searchValue` within `s`, searching backwards from the given `start` position. Returns `-1` if `searchValue` is not in `s`. The return value is always relative to the beginning of the string. - -```ocaml - lastIndexOf ~search:"ok" "bookseller" = 2;; - lastIndexOf ~search:"ee" "beekeeper" = 4;; - lastIndexOf ~search:"xyz" "abcdefg" = -1;; - lastIndexOf ~search:"ok" ~start:6 "bookseller" = 2;; - lastIndexOf ~search:"ee" ~start:8 "beekeeper" = 4;; - lastIndexOf ~search:"ee" ~start:3 "beekeeper" = 1;; - lastIndexOf ~search:"xyz" ~start:4 "abcdefg" = -1;; -``` -``` -val localeCompare : other:t -> t -> float -``` -`localeCompare ~other:comparison reference` returns: - -- a negative value if `reference` comes before `comparison` in sort order -- zero if `reference` and `comparison` have the same sort order -- a positive value if `reference` comes after `comparison` in sort order -```ocaml - (localeCompare ~other:"ant" "zebra") > 0.0;; - (localeCompare ~other:"zebra" "ant") < 0.0;; - (localeCompare ~other:"cat" "cat") = 0.0;; - (localeCompare ~other:"cat" "CAT") > 0.0;; -``` -``` -val match_ : regexp:Js.re -> t -> t option array option -``` -`match ~regexp str` matches a string against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the `g` modifier, if there is a match, the return value is `Some array` where the array contains: - -- The entire matched string -- Any capture groups if the `regexp` had parentheses -For regular expressions with the `g` modifier, a matched expression returns `Some array` with all the matched substrings and no capture groups. - -```ocaml - match "The better bats" ~regexp:[%re "/b[aeiou]t/"] = Some [|"bet"|] - match "The better bats" ~regexp:[%re "/b[aeiou]t/g"] = Some [|"bet";"bat"|] - match "Today is 2018-04-05." ~regexp:[%re "/(\\d+)-(\\d+)-(\\d+)/"] = Some [|"2018-04-05"; "2018"; "04"; "05"|] - match "The large container." ~regexp:[%re "/b[aeiou]g/"] = None -``` -``` -val normalize : ?form:[ `NFC | `NFD | `NFKC | `NFKD ] -> t -> t -``` -`normalize ~form str` returns the normalized Unicode string using the specified form of normalization, which may be one of: - -- `` `NFC `` — Normalization Form Canonical Composition. -- `` `NFD `` — Normalization Form Canonical Decomposition. -- `` `NFKC `` — Normalization Form Compatibility Composition. -- `` `NFKD `` — Normalization Form Compatibility Decomposition. -If `form` is omitted, `` `NFC `` is used. - -Consider the character `ã`, which can be represented as the single codepoint `\u00e3` or the combination of a lower case letter A `\u0061` and a combining tilde `\u0303`. Normalization ensures that both can be stored in an equivalent binary representation. - -see [https://www.unicode.org/reports/tr15/tr15-45.html](https://www.unicode.org/reports/tr15/tr15-45.html) Unicode technical report for details -``` -val repeat : count:int -> t -> t -``` -`repeat ~count s` returns a string that consists of `count` repetitions of `s`. Raises `RangeError` if `n` is negative. - -```ocaml - repeat ~count:3 "ha" = "hahaha" - repeat ~count:0 "empty" = "" -``` -``` -val replace : search:t -> replacement:t -> t -> t -``` -`replace ~search ~replacement string` returns a new string which is identical to `string` except with the first matching instance of `search` replaced by `replacement`. - -`search` is treated as a verbatim string to match, not a regular expression. - -```ocaml - replace ~search:"old" ~replacement:"new" "old string" = "new string" - replace ~search:"the" ~replacement:"this" "the cat and the dog" = "this cat and the dog" -``` -``` -val replaceByRe : regexp:Js.re -> replacement:t -> t -> t -``` -`replaceByRe ~regexp ~replacement string` returns a new string where occurrences matching `regexp` have been replaced by `replacement`. - -```ocaml - replaceByRe ~regexp:[%re "/[aeiou]/g"] ~replacement:"x" "vowels be gone" = "vxwxls bx gxnx" - replaceByRe ~regexp:[%re "/(\\w+) (\\w+)/"] ~replacement:"$2, $1" "Juan Fulano" = "Fulano, Juan" -``` -``` -val unsafeReplaceBy0 : regexp:Js.re -> f:(t -> int -> t -> t) -> t -> t -``` -`unsafeReplaceBy0 ~regexp ~f s` returns a new string with some or all matches of a pattern with no capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the offset at which the match begins, and the whole string being matched - -```ocaml -let str = "beautiful vowels" -let re = [%re "/[aeiou]/g"] -let matchFn matchPart offset wholeString = Js.String.toUpperCase matchPart - -let replaced = Js.String.unsafeReplaceBy0 ~regexp:re ~f:matchFn str - -let () = Js.log replaced (* prints "bEAUtifUl vOwEls" *) -``` -@see \ MDN - -``` -val unsafeReplaceBy1 : regexp:Js.re -> f:(t -> t -> int -> t -> t) -> t -> t -``` -`unsafeReplaceBy1 ~regexp ~f s` returns a new string with some or all matches of a pattern with one set of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. - -```ocaml -let str = "increment 23" -let re = [%re "/increment (\\d+)/g"] -let matchFn matchPart p1 offset wholeString = - wholeString ^ " is " ^ (string_of_int ((int_of_string p1) + 1)) - -let replaced = Js.String.unsafeReplaceBy1 ~regexp:re ~f:matchFn str - -let () = Js.log replaced (* prints "increment 23 is 24" *) -``` -@see \ MDN - -``` -val unsafeReplaceBy2 : - regexp:Js.re -> - f:(t -> t -> t -> int -> t -> t) -> - t -> - t -``` -`unsafeReplaceBy2 ~regexp ~f s` returns a new string with some or all matches of a pattern with two sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. - -```ocaml -let str = "7 times 6" -let re = [%re "/(\\d+) times (\\d+)/"] -let matchFn matchPart p1 p2 offset wholeString = - string_of_int ((int_of_string p1) * (int_of_string p2)) - -let replaced = Js.String.unsafeReplaceBy2 ~regexp:re ~f:matchFn str - -let () = Js.log replaced (* prints "42" *) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN -``` -val unsafeReplaceBy3 : - regexp:Js.re -> - f:(t -> t -> t -> t -> int -> t -> t) -> - t -> - t -``` -`unsafeReplaceBy3 ~regexp ~f s` returns a new string with some or all matches of a pattern with three sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN -``` -val search : regexp:Js.re -> t -> int -``` -`search ~regexp str` returns the starting position of the first match of `regexp` in the given `str`, or \-1 if there is no match. - -```ocaml -search ~regexp:[%re "/\\d+/"] "testing 1 2 3" = 8;; -search ~regexp:[%re "/\\d+/"] "no numbers" = -1;; -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`slice ?start ?end str` returns the substring of `str` starting at character `start` up to but not including `end` - -If either `start` or `end` is negative, then it is evaluated as `length str - start` (or `length str - end`). - -If `end` is greater than the length of `str`, then it is treated as `length str`. - -If `start` is greater than `end`, `slice` returns the empty string. - -```ocaml - slice ~start:2 ~end_:5 "abcdefg" = "cde";; - slice ~start:2 ~end_:9 "abcdefg" = "cdefg";; - slice ~start:(-4) ~end_:(-2) "abcdefg" = "de";; - slice ~start:5 ~end_:1 "abcdefg" = "";; -``` -``` -val split : ?sep:t -> ?limit:int -> t -> t array -``` -`split ?sep ?limit str` splits the given `str` at every occurrence of `sep` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. - -```ocaml - split ~sep:"/" ~limit: 3 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"|];; - split ~sep:"/" ~limit: 0 "ant/bee/cat/dog/elk" = [| |];; - split ~sep:"/" ~limit: 9 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"; "dog"; "elk"|];; -``` -``` -val splitByRe : regexp:Js.re -> ?limit:int -> t -> t option array -``` -`splitByRe str ~regexp ?limit ()` splits the given `str` at every occurrence of `regexp` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. - -```ocaml - splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:3 "one: two: three: four" = [|"one"; "two"; "three"|];; - splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:0 "one: two: three: four" = [| |];; - splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:8 "one: two: three: four" = [|"one"; "two"; "three"; "four"|];; -``` -; - -``` -val startsWith : prefix:t -> ?start:int -> t -> bool -``` -`startsWith ~prefix ?start str` returns `true` if the `str` starts with `prefix` starting at position `start`, `false` otherwise. If `start` is negative, the search starts at the beginning of `str`. - -```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;; -``` -``` -val substr : ?start:int -> ?len:int -> t -> t -``` -`substr ?start ?len str` returns the substring of `str` of length `len` starting at position `start`. - -If `start` is less than zero, the starting position is the length of `str` - -- `start`. -If `start` is greater than or equal to the length of `str`, returns the empty string. - -If `len` is less than or equal to zero, returns the empty string. - -```ocaml - substr ~start:3 ~len:4 "abcdefghij" = "defghij" - substr ~start:(-3) ~len:4 "abcdefghij" = "hij" - substr ~start:12 ~len:2 "abcdefghij" = "" -``` -deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/substr\#sect1 -``` -val substring : ?start:int -> ?end_:int -> t -> t -``` -`substring ~start ~end_ str` returns characters `start` up to but not including `end_` from `str`. - -If `start` is less than zero, it is treated as zero. - -If `end_` is zero or negative, the empty string is returned. - -If `start` is greater than `end_`, the start and finish points are swapped. - -```ocaml - substring ~start:3 ~end_:6 "playground" = "ygr";; - substring ~start:6 ~end_:3 "playground" = "ygr";; - substring ~start:4 ~end_:12 "playground" = "ground";; -``` -``` -val toLowerCase : t -> t -``` -`toLowerCase str` converts `str` to lower case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can give different results depending upon context, for example with the Greek letter sigma, which has two different lower case forms when it is the last character in a string or not. - -```ocaml - toLowerCase "ABC" = "abc";; - toLowerCase {js|ΣΠ|js} = {js|σπ|js};; - toLowerCase {js|ΠΣ|js} = {js|πς|js};; -``` -``` -val toLocaleLowerCase : t -> t -``` -`toLocaleLowerCase str` converts `str` to lower case using the current locale - -``` -val toUpperCase : t -> t -``` -`toUpperCase str` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can expand the number of letters in the result; for example the German `ß` capitalizes to two `S`es in a row. - -```ocaml - toUpperCase "abc" = "ABC";; - toUpperCase {js|Straße|js} = {js|STRASSE|js};; - toUpperCase {js|πς|js} = {js|ΠΣ|js};; -``` -``` -val toLocaleUpperCase : t -> t -``` -`toLocaleUpperCase str` converts `str` to upper case using the current locale - -``` -val trim : t -> t -``` -`trim str` returns a string that is `str` with whitespace stripped from both ends. Internal whitespace is not removed. - -```ocaml - trim " abc def " = "abc def" - trim "\n\r\t abc def \n\n\t\r " = "abc def" -``` -``` -val anchor : name:t -> t -> t -``` -`anchor ~name:anchorName anchorText` creates a string with an HTML `` element with `name` attribute of `anchorName` and `anchorText` as its content. - -```ocaml - anchor ~name:"page1" "Page One" = "Page One" -``` -deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/anchor\#sect1 -``` -val link : href:t -> t -> t -``` -`link ~href:urlText linkText` creates a string with an HTML `` element with `href` attribute of `urlText` and `linkText` as its content. - -```ocaml - link ~href:"page2.html" "Go to page two" = "Go to page two" -``` -deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/link\#sect1 -``` -val unsafeToArrayLike : t -> t Js.array_like -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-ArrayBuffer.md b/docs/api/ml/melange/Js-Typed_array-ArrayBuffer.md deleted file mode 100644 index 3331025db..000000000 --- a/docs/api/ml/melange/Js-Typed_array-ArrayBuffer.md +++ /dev/null @@ -1,20 +0,0 @@ - -# Module `Typed_array.ArrayBuffer` - -The underlying buffer that the typed arrays provide views of - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) MDN -``` -type t = Js.arrayBuffer -``` -``` -val make : int -> t -``` -takes length. initializes elements to 0 - -``` -val byteLength : t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> Js.arrayBuffer -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-DataView.md b/docs/api/ml/melange/Js-Typed_array-DataView.md deleted file mode 100644 index 1d1ad1f0f..000000000 --- a/docs/api/ml/melange/Js-Typed_array-DataView.md +++ /dev/null @@ -1,108 +0,0 @@ - -# Module `Typed_array.DataView` - -The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) MDN -``` -type t -``` -``` -val make : Js.arrayBuffer -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val getInt8 : int -> t -> int -``` -``` -val getUint8 : int -> t -> int -``` -``` -val getInt16 : int -> t -> int -``` -``` -val getInt16LittleEndian : int -> t -> int -``` -``` -val getUint16 : int -> t -> int -``` -``` -val getUint16LittleEndian : int -> t -> int -``` -``` -val getInt32 : int -> t -> int -``` -``` -val getInt32LittleEndian : int -> t -> int -``` -``` -val getUint32 : int -> t -> int -``` -``` -val getUint32LittleEndian : int -> t -> int -``` -``` -val getFloat32 : int -> t -> float -``` -``` -val getFloat32LittleEndian : int -> t -> float -``` -``` -val getFloat64 : int -> t -> float -``` -``` -val getFloat64LittleEndian : int -> t -> float -``` -``` -val setInt8 : int -> int -> t -> unit -``` -``` -val setUint8 : int -> int -> t -> unit -``` -``` -val setInt16 : int -> int -> t -> unit -``` -``` -val setInt16LittleEndian : int -> int -> t -> unit -``` -``` -val setUint16 : int -> int -> t -> unit -``` -``` -val setUint16LittleEndian : int -> int -> t -> unit -``` -``` -val setInt32 : int -> int -> t -> unit -``` -``` -val setInt32LittleEndian : int -> int -> t -> unit -``` -``` -val setUint32 : int -> int -> t -> unit -``` -``` -val setUint32LittleEndian : int -> int -> t -> unit -``` -``` -val setFloat32 : int -> float -> t -> unit -``` -``` -val setFloat32LittleEndian : int -> float -> t -> unit -``` -``` -val setFloat64 : int -> float -> t -> unit -``` -``` -val setFloat64LittleEndian : int -> float -> t -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Float32Array.md b/docs/api/ml/melange/Js-Typed_array-Float32Array.md deleted file mode 100644 index 77ea7f873..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Float32Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Float32Array` - -``` -type elt = float -``` -``` -type 'a typed_array = Js.float32Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Float64Array.md b/docs/api/ml/melange/Js-Typed_array-Float64Array.md deleted file mode 100644 index 47a2c9062..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Float64Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Float64Array` - -``` -type elt = float -``` -``` -type 'a typed_array = Js.float64Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Int16Array.md b/docs/api/ml/melange/Js-Typed_array-Int16Array.md deleted file mode 100644 index efd85abba..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Int16Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Int16Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.int16Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Int32Array.md b/docs/api/ml/melange/Js-Typed_array-Int32Array.md deleted file mode 100644 index 459de0957..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Int32Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Int32Array` - -``` -type elt = int32 -``` -``` -type 'a typed_array = Js.int32Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Int8Array.md b/docs/api/ml/melange/Js-Typed_array-Int8Array.md deleted file mode 100644 index fd129f858..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Int8Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Int8Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.int8Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Uint16Array.md b/docs/api/ml/melange/Js-Typed_array-Uint16Array.md deleted file mode 100644 index 44568a6d6..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Uint16Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint16Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint16Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Uint32Array.md b/docs/api/ml/melange/Js-Typed_array-Uint32Array.md deleted file mode 100644 index 2faa8f753..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Uint32Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint32Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint32Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Uint8Array.md b/docs/api/ml/melange/Js-Typed_array-Uint8Array.md deleted file mode 100644 index e3a3890d2..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Uint8Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint8Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint8Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array-Uint8ClampedArray.md b/docs/api/ml/melange/Js-Typed_array-Uint8ClampedArray.md deleted file mode 100644 index 27966ace2..000000000 --- a/docs/api/ml/melange/Js-Typed_array-Uint8ClampedArray.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint8ClampedArray` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint8ClampedArray -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Typed_array.md b/docs/api/ml/melange/Js-Typed_array.md deleted file mode 100644 index 4716bb636..000000000 --- a/docs/api/ml/melange/Js-Typed_array.md +++ /dev/null @@ -1,44 +0,0 @@ - -# Module `Js.Typed_array` - -Bindings to the functions in `TypedArray.prototype` - -JavaScript Typed Array API - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) MDN -``` -module ArrayBuffer : sig ... end -``` -The underlying buffer that the typed arrays provide views of - -``` -module Int8Array : sig ... end -``` -``` -module Uint8Array : sig ... end -``` -``` -module Uint8ClampedArray : sig ... end -``` -``` -module Int16Array : sig ... end -``` -``` -module Uint16Array : sig ... end -``` -``` -module Int32Array : sig ... end -``` -``` -module Uint32Array : sig ... end -``` -``` -module Float32Array : sig ... end -``` -``` -module Float64Array : sig ... end -``` -``` -module DataView : sig ... end -``` -The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. diff --git a/docs/api/ml/melange/Js-Types.md b/docs/api/ml/melange/Js-Types.md deleted file mode 100644 index d9e8e32ab..000000000 --- a/docs/api/ml/melange/Js-Types.md +++ /dev/null @@ -1,109 +0,0 @@ - -# Module `Js.Types` - -Utility functions for runtime reflection on JS types - -``` -type symbol -``` -Js symbol type only available in ES6 - -``` -type bigint_val -``` -Js bigint type only available in ES2020 - -``` -type obj_val -``` -``` -type undefined_val -``` -This type has only one value `undefined` - -``` -type null_val -``` -This type has only one value `null` - -``` -type function_val -``` -``` -type _ t = -``` -``` -| Undefined : undefined_val t -``` -``` -| Null : null_val t -``` -``` -| Boolean : bool t -``` -``` -| Number : float t -``` -``` -| String : string t -``` -``` -| Function : function_val t -``` -``` -| Object : obj_val t -``` -``` -| Symbol : symbol t -``` -``` -| BigInt : bigint_val t -``` -``` - -``` -``` -val test : 'a -> 'b t -> bool -``` -```ocaml -test "x" String = true -``` -``` -type tagged_t = -``` -``` -| JSFalse -``` -``` -| JSTrue -``` -``` -| JSNull -``` -``` -| JSUndefined -``` -``` -| JSNumber of float -``` -``` -| JSString of string -``` -``` -| JSFunction of function_val -``` -``` -| JSObject of obj_val -``` -``` -| JSSymbol of symbol -``` -``` -| JSBigInt of bigint_val -``` -``` - -``` -``` -val classify : 'a -> tagged_t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-Undefined.md b/docs/api/ml/melange/Js-Undefined.md deleted file mode 100644 index 749c64f50..000000000 --- a/docs/api/ml/melange/Js-Undefined.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `Js.Undefined` - -Utility functions on [`undefined`](./Js.md#type-undefined) - -Provides functionality for dealing with the `'a Js.undefined` type - -``` -type +'a t = 'a Js.undefined -``` -Local alias for `'a Js.undefined` - -``` -val return : 'a -> 'a t -``` -Constructs a value of `'a Js.undefined` containing a value of `'a` - -``` -val testAny : 'a -> bool -``` -Returns `true` if the given value is `empty` (`undefined`) - -``` -val empty : 'a t -``` -The empty value, `undefined` - -``` -val getUnsafe : 'a t -> 'a -``` -``` -val getExn : 'a t -> 'a -``` -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -``` -val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t -``` -Bind the contained value using the given function - -If `'a Js.undefined` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.undefined` - -```ocaml -let maybeGreetWorld (maybeGreeting: string Js.undefined) = - Js.Undefined.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") -``` -``` -val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit -``` -Iterates over the contained value with the given function - -If `'a Js.undefined` contains a value, that value is unwrapped and applied to the given function. - -```ocaml -let maybeSay (maybeMessage: string Js.undefined) = - Js.Undefined.iter maybeMessage ~f:(fun message -> Js.log message) -``` -``` -val fromOption : 'a option -> 'a t -``` -Maps `'a option` to `'a Js.undefined` - - - -
Some a -> return a -
None -> empty -
- -``` -val toOption : 'a t -> 'a option -``` -Maps `'a Js.undefined` to `'a option` - - - -
return a -> Some a -
empty -> None -
diff --git a/docs/api/ml/melange/Js-WeakMap.md b/docs/api/ml/melange/Js-WeakMap.md deleted file mode 100644 index a997042d8..000000000 --- a/docs/api/ml/melange/Js-WeakMap.md +++ /dev/null @@ -1,25 +0,0 @@ - -# Module `Js.WeakMap` - -Bindings to functions in `WeakMap` - -ES6 WeakMap API - -``` -type ('k, 'v) t -``` -``` -val make : unit -> ('k, 'v) t -``` -``` -val get : key:'k Js.dict -> ('k, 'v) t -> 'v option -``` -``` -val has : key:'k Js.dict -> ('k, 'v) t -> bool -``` -``` -val set : key:'k Js.dict -> value:'v -> ('k, 'v) t -> ('k, 'v) t -``` -``` -val delete : key:'k Js.dict -> ('k, 'v) t -> bool -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js-WeakSet.md b/docs/api/ml/melange/Js-WeakSet.md deleted file mode 100644 index a7f07d2ea..000000000 --- a/docs/api/ml/melange/Js-WeakSet.md +++ /dev/null @@ -1,22 +0,0 @@ - -# Module `Js.WeakSet` - -Bindings to functions in `WeakSet` - -ES6 WeakSet API - -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val add : value:'a Js.dict -> 'a t -> 'a t -``` -``` -val delete : value:'a Js.dict -> 'a t -> bool -``` -``` -val has : value:'a Js.dict -> 'a t -> bool -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Js.md b/docs/api/ml/melange/Js.md deleted file mode 100644 index 06b1fd244..000000000 --- a/docs/api/ml/melange/Js.md +++ /dev/null @@ -1,320 +0,0 @@ - -# Module `Js` - -``` -type +'a null -``` -A value of this type can be either `null` or `'a`. This type is the same as type `t` in [`Null`](./Js-Null.md) - -``` -type +'a undefined -``` -A value of this type can be either `undefined` or `'a`. This type is the same as type `t` in [`Undefined`](./Js-Undefined.md) - -``` -type +'a nullable -``` -A value of this type can be `undefined`, `null` or `'a`. This type is the same as type `t` n [`Nullable`](./Js-Nullable.md) - -``` -type re -``` -The type for JavaScript `RegExp` - -``` -type 'a dict -``` -The type for a simple key-value dictionary abstraction over native JavaScript objects - -``` -type 'a iterator -``` -The type for JavaScript iterators - -``` -type 'a array_like -``` -The type for array-like objects in JavaScript - -``` -type bigint -``` -The type for JavaScript BigInt - -``` -type +'a promise -``` -The type for JavaScript Promise - -``` -type blob -``` -The type for JavaScript [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - -``` -type file -``` -The type for JavaScript [File](https://developer.mozilla.org/en-US/docs/Web/API/File) - -``` -type arrayBuffer -``` -``` -type int8Array -``` -``` -type uint8Array -``` -``` -type uint8ClampedArray -``` -``` -type int16Array -``` -``` -type uint16Array -``` -``` -type int32Array -``` -``` -type uint32Array -``` -``` -type float32Array -``` -``` -type float64Array -``` -``` -val toOption : 'a nullable -> 'a option -``` -``` -val undefinedToOption : 'a undefined -> 'a option -``` -``` -val nullToOption : 'a null -> 'a option -``` -``` -val isNullable : 'a nullable -> bool -``` -``` -val import : 'a -> 'a promise -``` -TODO(anmonteiro): document - -``` -val testAny : 'a -> bool -``` -The same as [`isNullable`](./#val-isNullable) except that it is more permissive on the types of input - -``` -val null : 'a null -``` -The same as `empty` in [`Js.Null`](./Js-Null.md) will be compiled as `null` - -``` -val undefined : 'a undefined -``` -The same as `empty` [`Js.Undefined`](./Js-Undefined.md) will be compiled as `undefined` - -``` -val typeof : 'a -> string -``` -`typeof x` will be compiled as `typeof x` in JS Please consider functions in [`Types`](./Js-Types.md) for a type safe way of reflection - -``` -val log : 'a -> unit -``` -A convenience function to log everything - -``` -val log2 : 'a -> 'b -> unit -``` -``` -val log3 : 'a -> 'b -> 'c -> unit -``` -``` -val log4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val logMany : 'a array -> unit -``` -A convenience function to log more than 4 arguments - -``` -val eqNull : 'a -> 'a null -> bool -``` -``` -val eqUndefined : 'a -> 'a undefined -> bool -``` -``` -val eqNullable : 'a -> 'a nullable -> bool -``` - -##### Operators - -``` -val unsafe_lt : 'a -> 'a -> bool -``` -`unsafe_lt a b` will be compiled as `a < b`. It is marked as unsafe, since it is impossible to give a proper semantics for comparision which applies to any type - -``` -val unsafe_le : 'a -> 'a -> bool -``` -`unsafe_le a b` will be compiled as `a <= b`. See also [`unsafe_lt`](./#val-unsafe_lt) - -``` -val unsafe_gt : 'a -> 'a -> bool -``` -`unsafe_gt a b` will be compiled as `a > b`. See also [`unsafe_lt`](./#val-unsafe_lt) - -``` -val unsafe_ge : 'a -> 'a -> bool -``` -`unsafe_ge a b` will be compiled as `a >= b`. See also [`unsafe_lt`](./#val-unsafe_lt) - -Types for JS objects - -``` -type 'a t -``` -This used to be mark a Js object type. - -``` -module Exn : sig ... end -``` -Utilities for dealing with Js exceptions - -``` -module String : sig ... end -``` -Bindings to the functions in `String.prototype` - -``` -module Null : sig ... end -``` -Utility functions on [`null`](./#type-null) - -``` -module Undefined : sig ... end -``` -Utility functions on [`undefined`](./#type-undefined) - -``` -module Nullable : sig ... end -``` -Utility functions on [`nullable`](./#type-nullable) - -``` -module Array : sig ... end -``` -Bindings to the functions in `Array.prototype` - -``` -module Re : sig ... end -``` -Bindings to the functions in `RegExp.prototype` - -``` -module Promise : sig ... end -``` -Bindings to JS `Promise` functions - -``` -module Date : sig ... end -``` -Bindings to the functions in JS's `Date.prototype` - -``` -module Dict : sig ... end -``` -Utility functions to treat a JS object as a dictionary - -``` -module Global : sig ... end -``` -Bindings to functions in the JS global namespace - -``` -module Json : sig ... end -``` -Utility functions to manipulate JSON values - -``` -module Math : sig ... end -``` -Bindings to the functions in the `Math` object - -``` -module Obj : sig ... end -``` -Utility functions on \`Js.t\` JS objects - -``` -module Typed_array : sig ... end -``` -Bindings to the functions in `TypedArray.prototype` - -``` -module Types : sig ... end -``` -Utility functions for runtime reflection on JS types - -``` -module Float : sig ... end -``` -Bindings to functions in JavaScript's `Number` that deal with floats - -``` -module Int : sig ... end -``` -Bindings to functions in JavaScript's `Number` that deal with ints - -``` -module Bigint : sig ... end -``` -Bindings to functions in JavaScript's `BigInt` - -``` -module Console : sig ... end -``` -``` -module Set : sig ... end -``` -Bindings to functions in `Set` - -``` -module WeakSet : sig ... end -``` -Bindings to functions in `WeakSet` - -``` -module Map : sig ... end -``` -Bindings to functions in `Map` - -``` -module WeakMap : sig ... end -``` -Bindings to functions in `WeakMap` - -``` -module Iterator : sig ... end -``` -Bindings to functions on `Iterator` - -``` -module Blob : sig ... end -``` -Bindings to Blob - -``` -module File : sig ... end -``` -Bindings to File - -``` -module FormData : sig ... end -``` -Bindings to FormData diff --git a/docs/api/ml/melange/Node-Buffer.md b/docs/api/ml/melange/Node-Buffer.md deleted file mode 100644 index 3488b30f6..000000000 --- a/docs/api/ml/melange/Node-Buffer.md +++ /dev/null @@ -1,56 +0,0 @@ - -# Module `Node.Buffer` - -Node Buffer API - -``` -type t = Node.buffer -``` -``` -type encoding = [ -``` -``` -| `ascii -``` -``` -| `utf8 -``` -``` -| `utf16le -``` -``` -| `ucs2 -``` -``` -| `base64 -``` -``` -| `base64url -``` -``` -| `latin1 -``` -``` -| `binary -``` -``` -| `hex -``` -``` - ] -``` -``` -val isBuffer : 'a -> bool -``` -``` -val fromString : string -> t -``` -``` -val fromStringWithEncoding : string -> encoding:encoding -> t -``` -``` -val toString : ?encoding:encoding -> t -> string -``` -``` -val concat : t array -> t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Node-Child_process.md b/docs/api/ml/melange/Node-Child_process.md deleted file mode 100644 index 5a3630c8c..000000000 --- a/docs/api/ml/melange/Node-Child_process.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Module `Node.Child_process` - -Node Child Process API - -``` -type option -``` -``` -val option : ?cwd:string -> ?encoding:string -> unit -> option -``` -``` -val execSync : string -> option -> string -``` -``` -type spawnResult -``` -``` -val spawnSync : string -> spawnResult -``` -``` -val readAs : - spawnResult -> - < pid : int - ; status : int Js.null - ; signal : string Js.null - ; stdout : Node.string_buffer Js.null - ; stderr : Node.string_buffer Js.null > - Js.t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Node-Fs-Watch.md b/docs/api/ml/melange/Node-Fs-Watch.md deleted file mode 100644 index 581d242fa..000000000 --- a/docs/api/ml/melange/Node-Fs-Watch.md +++ /dev/null @@ -1,33 +0,0 @@ - -# Module `Fs.Watch` - -``` -type t -``` -``` -type config -``` -``` -val config : - ?persistent:bool -> - ?recursive:bool -> - ?encoding:Js.String.t -> - unit -> - config -``` -``` -val watch : string -> ?config:config -> unit -> t -``` -there is no need to accept listener, since we return a `watcher` back it can register event listener there. Currently we introduce a type `string_buffer`, for the `filename`, it will be `Buffer` when the encoding is `` `utf8 ``. This is dependent type which can be tracked by GADT in some way, but to make things simple, let's just introduce an or type - -``` -val on : - t -> - f: - [ `change of (string -> Node.string_buffer -> unit) Js.Fn.arity2 - | `error of unit Js.Fn.arity0 ] -> - t -``` -``` -val close : t -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Node-Fs.md b/docs/api/ml/melange/Node-Fs.md deleted file mode 100644 index b437a848f..000000000 --- a/docs/api/ml/melange/Node-Fs.md +++ /dev/null @@ -1,110 +0,0 @@ - -# Module `Node.Fs` - -Node FS API - -see [https://blogs.janestreet.com/a-and-a/](https://blogs.janestreet.com/a-and-a/) refernce documentation -``` -val readdirSync : string -> string array -``` -Most fs functions let you omit the callback argument. If you do, a default callback is used that rethrows errors. To get a trace to the original call site, set the \`NODE\_DEBUG\` environment variable. - -``` -val renameSync : string -> string -> unit -``` -``` -type fd = private int -``` -``` -type path = string -``` -The relative path to a filename can be used. Remember, however, that this path will be relative to `process.cwd()`. - -``` -module Watch : sig ... end -``` -``` -val ftruncateSync : fd -> int -> unit -``` -``` -val truncateSync : string -> int -> unit -``` -``` -val chownSync : string -> uid:int -> gid:int -> unit -``` -``` -val fchownSync : fd -> uid:int -> gid:int -> unit -``` -``` -val readlinkSync : string -> string -``` -``` -val unlinkSync : string -> unit -``` -``` -val rmdirSync : string -> unit -``` -``` -val openSync : - path -> - [ `Read - | `Read_write - | `Read_write_sync - | `Write - | `Write_fail_if_exists - | `Write_read - | `Write_read_fail_if_exists - | `Append - | `Append_fail_if_exists - | `Append_read - | `Append_read_fail_if_exists ] -> - unit -``` -``` -type encoding = [ -``` -``` -| `hex -``` -``` -| `utf8 -``` -``` -| `ascii -``` -``` -| `latin1 -``` -``` -| `base64 -``` -``` -| `ucs2 -``` -``` -| `base64 -``` -``` -| `binary -``` -``` -| `utf16le -``` -``` - ] -``` -``` -val readFileSync : string -> encoding -> string -``` -``` -val readFileAsUtf8Sync : string -> string -``` -``` -val existsSync : string -> bool -``` -``` -val writeFileSync : string -> string -> encoding -> unit -``` -``` -val writeFileAsUtf8Sync : string -> string -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Node-Module.md b/docs/api/ml/melange/Node-Module.md deleted file mode 100644 index 26dbe1439..000000000 --- a/docs/api/ml/melange/Node-Module.md +++ /dev/null @@ -1,8 +0,0 @@ - -# Module `Node.Module` - -Node Module API - -``` -val module_ : < __cache : Node.node_module Js.Dict.t > Js.t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Node-Path.md b/docs/api/ml/melange/Node-Path.md deleted file mode 100644 index 0d7ebfd71..000000000 --- a/docs/api/ml/melange/Node-Path.md +++ /dev/null @@ -1,56 +0,0 @@ - -# Module `Node.Path` - -Node Path API - -``` -val basename : string -> string -``` -``` -val basename_ext : string -> string -> string -``` -``` -val delimiter : string -``` -``` -val dirname : string -> string -``` -``` -val dirname_ext : string -> string -> string -``` -``` -type pathObject = - < dir : string - ; root : string - ; base : string - ; name : string - ; ext : string > - Js.t -``` -``` -val format : pathObject -> string -``` -``` -val isAbsolute : string -> bool -``` -``` -val join2 : string -> string -> string -``` -``` -val join : string array -> string -``` -``` -val normalize : string -> string -``` -``` -val parse : string -> pathObject -``` -``` -val relative : from:string -> to_:string -> unit -> string -``` -``` -val resolve : string -> string -> string -``` -``` -val sep : string -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Node-Process.md b/docs/api/ml/melange/Node-Process.md deleted file mode 100644 index f2714be7b..000000000 --- a/docs/api/ml/melange/Node-Process.md +++ /dev/null @@ -1,38 +0,0 @@ - -# Module `Node.Process` - -``` -type t = - < argv : string array - ; arch : string - ; abort : unit Js.OO.Meth.arity0 - ; chdir : (string -> unit) Js.OO.Meth.arity1 - ; cwd : string Js.OO.Meth.arity0 - ; disconnect : unit Js.OO.Meth.arity0 - ; platform : string - ; env : string Js.Dict.t > - Js.t -``` -``` -val process : t -``` -``` -val argv : string array -``` -``` -val exit : int -> 'a -``` -``` -val cwd : unit -> string -``` -``` -val uptime : t -> unit -> float -``` -The process.uptime() method returns the number of seconds the current Node.js process has been running.) - -``` -val putEnvVar : string -> string -> unit -``` -``` -val deleteEnvVar : string -> unit -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Node.md b/docs/api/ml/melange/Node.md deleted file mode 100644 index 2730c44a9..000000000 --- a/docs/api/ml/melange/Node.md +++ /dev/null @@ -1,73 +0,0 @@ - -# Module `Node` - -``` -type node_exports -``` -``` -type node_module = - < id : string - ; exports : node_exports - ; parent : node_module Js.nullable - ; filename : string - ; loaded : bool - ; children : node_module array - ; paths : string array > - Js.t -``` -``` -type node_require = - < main : node_module Js.undefined - ; resolve : (string -> string) Js.Fn.arity1 > - Js.t -``` -``` -type string_buffer -``` -``` -type buffer -``` -``` -type _ string_buffer_kind = -``` -``` -| String : string string_buffer_kind -``` -``` -| Buffer : buffer string_buffer_kind -``` -``` - -``` -``` -val test : string_buffer -> 't string_buffer_kind * 't -``` -We expect a good inliner will eliminate such boxing in the future - -``` -module Path : sig ... end -``` -Node Path API - -``` -module Fs : sig ... end -``` -Node FS API - -``` -module Process : sig ... end -``` -``` -module Module : sig ... end -``` -Node Module API - -``` -module Buffer : sig ... end -``` -Node Buffer API - -``` -module Child_process : sig ... end -``` -Node Child Process API diff --git a/docs/api/ml/melange/Stdlib-Arg.md b/docs/api/ml/melange/Stdlib-Arg.md deleted file mode 100644 index 9688b86ce..000000000 --- a/docs/api/ml/melange/Stdlib-Arg.md +++ /dev/null @@ -1,261 +0,0 @@ - -# Module `Stdlib.Arg` - -Parsing of command line arguments. - -This module provides a general mechanism for extracting options and arguments from the command line to the program. For example: - -```ocaml - let usage_msg = "append [-verbose] [] ... -o " - let verbose = ref false - let input_files = ref [] - let output_file = ref "" - - let anon_fun filename = - input_files := filename::!input_files - - let speclist = - [("-verbose", Arg.Set verbose, "Output debug information"); - ("-o", Arg.Set_string output_file, "Set output file name")] - - let () = - Arg.parse speclist anon_fun usage_msg; - (* Main functionality here *) -``` -Syntax of command lines: A keyword is a character string starting with a `-`. An option is a keyword alone or followed by an argument. The types of keywords are: `Unit`, `Bool`, `Set`, `Clear`, `String`, `Set_string`, `Int`, `Set_int`, `Float`, `Set_float`, `Tuple`, `Symbol`, `Rest`, `Rest_all` and `Expand`. - -`Unit`, `Set` and `Clear` keywords take no argument. - -A `Rest` or `Rest_all` keyword takes the remainder of the command line as arguments. (More explanations below.) - -Every other keyword takes the following word on the command line as argument. For compatibility with GNU getopt\_long, `keyword=arg` is also allowed. Arguments not preceded by a keyword are called anonymous arguments. - -Examples (`cmd` is assumed to be the command name): - -- `cmd -flag `(a unit option) -- `cmd -int 1 `(an int option with argument `1`) -- `cmd -string foobar `(a string option with argument `"foobar"`) -- `cmd -float 12.34 `(a float option with argument `12.34`) -- `cmd a b c `(three anonymous arguments: `"a"`, `"b"`, and `"c"`) -- `cmd a b -- c d `(two anonymous arguments and a rest option with two arguments) -`Rest` takes a function that is called repeatedly for each remaining command line argument. `Rest_all` takes a function that is called once, with the list of all remaining arguments. - -Note that if no arguments follow a `Rest` keyword then the function is not called at all whereas the function for a `Rest_all` keyword is called with an empty list. - -alert unsynchronized\_access The Arg module relies on a mutable global state, parsing functions should only be called from a single domain. -``` -type spec = -``` -``` -| Unit of unit -> unit -``` -Call the function with unit argument - -``` -| Bool of bool -> unit -``` -Call the function with a bool argument - -``` -| Set of bool ref -``` -Set the reference to true - -``` -| Clear of bool ref -``` -Set the reference to false - -``` -| String of string -> unit -``` -Call the function with a string argument - -``` -| Set_string of string ref -``` -Set the reference to the string argument - -``` -| Int of int -> unit -``` -Call the function with an int argument - -``` -| Set_int of int ref -``` -Set the reference to the int argument - -``` -| Float of float -> unit -``` -Call the function with a float argument - -``` -| Set_float of float ref -``` -Set the reference to the float argument - -``` -| Tuple of spec list -``` -Take several arguments according to the spec list - -``` -| Symbol of string list * string -> unit -``` -Take one of the symbols as argument and call the function with the symbol - -``` -| Rest of string -> unit -``` -Stop interpreting keywords and call the function with each remaining argument - -``` -| Rest_all of string list -> unit -``` -Stop interpreting keywords and call the function with all remaining arguments - -``` -| Expand of string -> string array -``` -If the remaining arguments to process are of the form `["-foo"; "arg"] @ rest` where "foo" is registered as `Expand f`, then the arguments `f "arg" @ rest` are processed. Only allowed in `parse_and_expand_argv_dynamic`. - -``` - -``` -The concrete type describing the behavior associated with a keyword. - -``` -type key = string -``` -``` -type doc = string -``` -``` -type usage_msg = string -``` -``` -type anon_fun = string -> unit -``` -``` -val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit -``` -`Arg.parse speclist anon_fun usage_msg` parses the command line. `speclist` is a list of triples `(key, spec, doc)`. `key` is the option keyword, it must start with a `'-'` character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon_fun` is called on anonymous arguments. The functions in `spec` and `anon_fun` are called in the same order as their arguments appear on the command line. - -If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows: - -- The reason for the error: unknown option, invalid or missing argument, etc. -- `usage_msg` -- The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list. -For the user to be able to specify anonymous arguments starting with a `-`, include for example `("-", String anon_fun, doc)` in `speclist`. - -By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage_msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`. - -``` -val parse_dynamic : - (key * spec * doc) list ref -> - anon_fun -> - usage_msg -> - unit -``` -Same as [`Arg.parse`](./#val-parse), except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form: - -- command subcommand `options` where the list of options depends on the value of the subcommand argument. -since 4.01 -``` -val parse_argv : - ?current:int ref -> - string array -> - (key * spec * doc) list -> - anon_fun -> - usage_msg -> - unit -``` -`Arg.parse_argv ~current args speclist anon_fun usage_msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or [`Arg.current`](./#val-current). You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises [`Arg.Bad`](./#exception-Bad) with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises [`Arg.Help`](./#exception-Help) with the help message as argument. - -``` -val parse_argv_dynamic : - ?current:int ref -> - string array -> - (key * spec * doc) list ref -> - anon_fun -> - string -> - unit -``` -Same as [`Arg.parse_argv`](./#val-parse_argv), except that the `speclist` argument is a reference and may be updated during the parsing. See [`Arg.parse_dynamic`](./#val-parse_dynamic). - -since 4.01 -``` -val parse_and_expand_argv_dynamic : - int ref -> - string array ref -> - (key * spec * doc) list ref -> - anon_fun -> - string -> - unit -``` -Same as [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic), except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic). - -since 4.05 -``` -val parse_expand : (key * spec * doc) list -> anon_fun -> usage_msg -> unit -``` -Same as [`Arg.parse`](./#val-parse), except that the `Expand` arguments are allowed and the [`current`](./#val-current) reference is not updated. - -since 4.05 -``` -exception Help of string -``` -Raised by `Arg.parse_argv` when the user asks for help. - -``` -exception Bad of string -``` -Functions in `spec` or `anon_fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by [`Arg.parse_argv`](./#val-parse_argv) in case of an error. - -``` -val usage : (key * spec * doc) list -> usage_msg -> unit -``` -`Arg.usage speclist usage_msg` prints to standard error an error message that includes the list of valid options. This is the same message that [`Arg.parse`](./#val-parse) prints in case of error. `speclist` and `usage_msg` are the same as for [`Arg.parse`](./#val-parse). - -``` -val usage_string : (key * spec * doc) list -> usage_msg -> string -``` -Returns the message that would have been printed by [`Arg.usage`](./#val-usage), if provided with the same parameters. - -``` -val align : ?limit:int -> (key * spec * doc) list -> (key * spec * doc) list -``` -Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line. - -parameter limit options with keyword and message longer than limit will not be used to compute the alignment. -``` -val current : int ref -``` -Position (in [`Sys.argv`](./Stdlib-Sys.md#val-argv)) of the argument being processed. You can change this value, e.g. to force [`Arg.parse`](./#val-parse) to skip some arguments. [`Arg.parse`](./#val-parse) uses the initial value of [`Arg.current`](./#val-current) as the index of argument 0 (the program name) and starts parsing arguments at the next element. - -``` -val read_arg : string -> string array -``` -`Arg.read_arg file` reads newline-terminated command line arguments from file `file`. - -since 4.05 -``` -val read_arg0 : string -> string array -``` -Identical to [`Arg.read_arg`](./#val-read_arg) but assumes null character terminated command line arguments. - -since 4.05 -``` -val write_arg : string -> string array -> unit -``` -`Arg.write_arg file args` writes the arguments `args` newline-terminated into the file `file`. If any of the arguments in `args` contains a newline, use [`Arg.write_arg0`](./#val-write_arg0) instead. - -since 4.05 -``` -val write_arg0 : string -> string array -> unit -``` -Identical to [`Arg.write_arg`](./#val-write_arg) but uses the null character for terminator instead of newline. - -since 4.05 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Array.md b/docs/api/ml/melange/Stdlib-Array.md deleted file mode 100644 index 9653f6b3d..000000000 --- a/docs/api/ml/melange/Stdlib-Array.md +++ /dev/null @@ -1,373 +0,0 @@ - -# Module `Stdlib.Array` - -Array operations. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a array -``` -An alias for the type of arrays. - -``` -val length : 'a array -> int -``` -Return the length (number of elements) of the given array. - -``` -val get : 'a array -> int -> 'a -``` -`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val set : 'a array -> int -> 'a -> unit -``` -`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. -``` -val make : int -> 'a -> 'a array -``` -`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val create_float : int -> float array -``` -`create_float n` returns a fresh float array of length `n`, with uninitialized data. - -since 4.03 -``` -val init : int -> (int -> 'a) -> 'a array -``` -`init n f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -``` -val make_matrix : int -> int -> 'a -> 'a array array -``` -`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val init_matrix : int -> int -> (int -> int -> 'a) -> 'a array array -``` -`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -since 5.2 -``` -val append : 'a array -> 'a array -> 'a array -``` -`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. -``` -val concat : 'a array list -> 'a array -``` -Same as [`append`](./#val-append), but concatenates a list of arrays. - -``` -val sub : 'a array -> int -> int -> 'a array -``` -`sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. -``` -val copy : 'a array -> 'a array -``` -`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. - -``` -val fill : 'a array -> int -> int -> 'a -> unit -``` -`fill a pos len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. -``` -val blit : 'a array -> int -> 'a array -> int -> int -> unit -``` -`blit src src_pos dst dst_pos len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. -``` -val to_list : 'a array -> 'a list -``` -`to_list a` returns the list of all the elements of `a`. - -``` -val of_list : 'a list -> 'a array -``` -`of_list l` returns a fresh array containing the elements of `l`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. - -## Iterators - -``` -val iter : ('a -> unit) -> 'a array -> unit -``` -`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. - -``` -val iteri : (int -> 'a -> unit) -> 'a array -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val map : ('a -> 'b) -> 'a array -> 'b array -``` -`map f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. - -``` -val map_inplace : ('a -> 'a) -> 'a array -> unit -``` -`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. - -since 5.1 -``` -val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val mapi_inplace : (int -> 'a -> 'a) -> 'a array -> unit -``` -Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -since 5.1 -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a array -> 'acc -``` -`fold_left f init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. - -``` -val fold_left_map : - ('acc -> 'a -> 'acc * 'b) -> - 'acc -> - 'a array -> - 'acc * 'b array -``` -`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. - -since 4.13 -``` -val fold_right : ('a -> 'acc -> 'acc) -> 'a array -> 'acc -> 'acc -``` -`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. - - -## Iterators on two arrays - -``` -val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit -``` -`iter2 f a b` applies function `f` to all the elements of `a` and `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) -``` -val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array -``` -`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) - -## Array scanning - -``` -val for_all : ('a -> bool) -> 'a array -> bool -``` -`for_all f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. - -since 4.03 -``` -val exists : ('a -> bool) -> 'a array -> bool -``` -`exists f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. - -since 4.03 -``` -val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val mem : 'a -> 'a array -> bool -``` -`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). - -since 4.03 -``` -val memq : 'a -> 'a array -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. - -since 4.03 -``` -val find_opt : ('a -> bool) -> 'a array -> 'a option -``` -`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. - -since 4.13 -``` -val find_index : ('a -> bool) -> 'a array -> int option -``` -`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : ('a -> 'b option) -> 'a array -> 'b option -``` -`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.13 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a array -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 - -## Arrays of pairs - -``` -val split : ('a * 'b) array -> 'a array * 'b array -``` -`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. - -since 4.13 -``` -val combine : 'a array -> 'b array -> ('a * 'b) array -``` -`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. - -since 4.13 - -## Sorting and shuffling - -``` -val sort : ('a -> 'a -> int) -> 'a array -> unit -``` -Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. - -The current implementation uses Heap Sort. It runs in constant stack space. - -Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : - -- `cmp x y` \> 0 if and only if `cmp y x` \< 0 -- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 -When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : - -- `cmp a.(i) a.(j)` \>= 0 if i \>= j -``` -val stable_sort : ('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. - -The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). - -``` -val fast_sort : ('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val shuffle : rand:(int -> int) -> 'a array -> unit -``` -`shuffle rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. - -`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). - -since 5.2 - -## Arrays and Sequences - -``` -val to_seq : 'a array -> 'a Seq.t -``` -Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : 'a array -> (int * 'a) Seq.t -``` -Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a array -``` -Create an array from the generator - -since 4.07 - -## Arrays and concurrency safety - -Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let a = Array.make size 1 -let d1 = Domain.spawn (fun () -> - Array.iteri (fun i x -> a.(i) <- x + 1) a -) -let d2 = Domain.spawn (fun () -> - Array.iteri (fun i x -> a.(i) <- 2 * x + 1) a -) -let () = Domain.join d1; Domain.join d2 -``` -After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). - - -### Float arrays - -Float arrays have two supplementary caveats in the presence of data races. - -First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. - -For instance, at the end of - -```ocaml - let zeros = Array.make size 0. -let max_floats = Array.make size Float.max_float -let res = Array.copy zeros -let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) -let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) -let () = Domain.join d1; Domain.join d2 -``` -the `res` array might contain values that are neither `0.` nor `max_float`. - -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/ml/melange/Stdlib-ArrayLabels.md b/docs/api/ml/melange/Stdlib-ArrayLabels.md deleted file mode 100644 index 22c66dcff..000000000 --- a/docs/api/ml/melange/Stdlib-ArrayLabels.md +++ /dev/null @@ -1,383 +0,0 @@ - -# Module `Stdlib.ArrayLabels` - -Array operations. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a array -``` -An alias for the type of arrays. - -``` -val length : 'a array -> int -``` -Return the length (number of elements) of the given array. - -``` -val get : 'a array -> int -> 'a -``` -`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val set : 'a array -> int -> 'a -> unit -``` -`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. -``` -val make : int -> 'a -> 'a array -``` -`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val create_float : int -> float array -``` -`create_float n` returns a fresh float array of length `n`, with uninitialized data. - -since 4.03 -``` -val init : int -> f:(int -> 'a) -> 'a array -``` -`init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -``` -val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array -``` -`make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val init_matrix : - dimx:int -> - dimy:int -> - f:(int -> int -> 'a) -> - 'a array array -``` -`init_matrix ~dimx ~dimy ~f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -since 5.2 -``` -val append : 'a array -> 'a array -> 'a array -``` -`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. -``` -val concat : 'a array list -> 'a array -``` -Same as [`append`](./#val-append), but concatenates a list of arrays. - -``` -val sub : 'a array -> pos:int -> len:int -> 'a array -``` -`sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. -``` -val copy : 'a array -> 'a array -``` -`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. - -``` -val fill : 'a array -> pos:int -> len:int -> 'a -> unit -``` -`fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. -``` -val blit : - src:'a array -> - src_pos:int -> - dst:'a array -> - dst_pos:int -> - len:int -> - unit -``` -`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. -``` -val to_list : 'a array -> 'a list -``` -`to_list a` returns the list of all the elements of `a`. - -``` -val of_list : 'a list -> 'a array -``` -`of_list l` returns a fresh array containing the elements of `l`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. - -## Iterators - -``` -val iter : f:('a -> unit) -> 'a array -> unit -``` -`iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. - -``` -val iteri : f:(int -> 'a -> unit) -> 'a array -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val map : f:('a -> 'b) -> 'a array -> 'b array -``` -`map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. - -``` -val map_inplace : f:('a -> 'a) -> 'a array -> unit -``` -`map_inplace ~f a` applies function `f` to all elements of `a`, and updates their values in place. - -since 5.1 -``` -val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val mapi_inplace : f:(int -> 'a -> 'a) -> 'a array -> unit -``` -Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -since 5.1 -``` -val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'acc -``` -`fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. - -``` -val fold_left_map : - f:('acc -> 'a -> 'acc * 'b) -> - init:'acc -> - 'a array -> - 'acc * 'b array -``` -`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. - -since 4.13 -``` -val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> init:'acc -> 'acc -``` -`fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. - - -## Iterators on two arrays - -``` -val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit -``` -`iter2 ~f a b` applies function `f` to all the elements of `a` and `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) -``` -val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array -``` -`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) - -## Array scanning - -``` -val for_all : f:('a -> bool) -> 'a array -> bool -``` -`for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. - -since 4.03 -``` -val exists : f:('a -> bool) -> 'a array -> bool -``` -`exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. - -since 4.03 -``` -val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val mem : 'a -> set:'a array -> bool -``` -`mem a ~set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). - -since 4.03 -``` -val memq : 'a -> set:'a array -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. - -since 4.03 -``` -val find_opt : f:('a -> bool) -> 'a array -> 'a option -``` -`find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. - -since 4.13 -``` -val find_index : f:('a -> bool) -> 'a array -> int option -``` -`find_index ~f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : f:('a -> 'b option) -> 'a array -> 'b option -``` -`find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.13 -``` -val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 - -## Arrays of pairs - -``` -val split : ('a * 'b) array -> 'a array * 'b array -``` -`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. - -since 4.13 -``` -val combine : 'a array -> 'b array -> ('a * 'b) array -``` -`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. - -since 4.13 - -## Sorting and shuffling - -``` -val sort : cmp:('a -> 'a -> int) -> 'a array -> unit -``` -Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. - -The current implementation uses Heap Sort. It runs in constant stack space. - -Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : - -- `cmp x y` \> 0 if and only if `cmp y x` \< 0 -- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 -When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : - -- `cmp a.(i) a.(j)` \>= 0 if i \>= j -``` -val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. - -The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). - -``` -val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val shuffle : rand:(int -> int) -> 'a array -> unit -``` -`shuffle ~rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. - -`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). - -since 5.2 - -## Arrays and Sequences - -``` -val to_seq : 'a array -> 'a Seq.t -``` -Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : 'a array -> (int * 'a) Seq.t -``` -Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a array -``` -Create an array from the generator - -since 4.07 - -## Arrays and concurrency safety - -Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let a = ArrayLabels.make size 1 -let d1 = Domain.spawn (fun () -> - ArrayLabels.iteri ~f:(fun i x -> a.(i) <- x + 1) a -) -let d2 = Domain.spawn (fun () -> - ArrayLabels.iteri ~f:(fun i x -> a.(i) <- 2 * x + 1) a -) -let () = Domain.join d1; Domain.join d2 -``` -After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). - - -### Float arrays - -Float arrays have two supplementary caveats in the presence of data races. - -First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. - -For instance, at the end of - -```ocaml - let zeros = Array.make size 0. -let max_floats = Array.make size Float.max_float -let res = Array.copy zeros -let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) -let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) -let () = Domain.join d1; Domain.join d2 -``` -the `res` array might contain values that are neither `0.` nor `max_float`. - -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/ml/melange/Stdlib-Atomic.md b/docs/api/ml/melange/Stdlib-Atomic.md deleted file mode 100644 index 1fc036d20..000000000 --- a/docs/api/ml/melange/Stdlib-Atomic.md +++ /dev/null @@ -1,144 +0,0 @@ - -# Module `Stdlib.Atomic` - -Atomic references. - -See [the examples](./#examples) below. See 'Memory model: The hard bits' chapter in the manual. - -since 4.12 -``` -type !'a t -``` -An atomic (mutable) reference to a value of type `'a`. - -``` -val make : 'a -> 'a t -``` -Create an atomic reference. - -Create an atomic reference that is alone on a cache line. It occupies 4-16x the memory of one allocated with `make v`. - -The primary purpose is to prevent false-sharing and the resulting performance degradation. When a CPU performs an atomic operation, it temporarily takes ownership of an entire cache line that contains the atomic reference. If multiple atomic references share the same cache line, modifying these disjoint memory regions simultaneously becomes impossible, which can create a bottleneck. Hence, as a general guideline, if an atomic reference is experiencing contention, assigning it its own cache line may enhance performance. - -``` -val get : 'a t -> 'a -``` -Get the current value of the atomic reference. - -``` -val set : 'a t -> 'a -> unit -``` -Set a new value for the atomic reference. - -``` -val exchange : 'a t -> 'a -> 'a -``` -Set a new value for the atomic reference, and return the current value. - -``` -val compare_and_set : 'a t -> 'a -> 'a -> bool -``` -`compare_and_set r seen v` sets the new value of `r` to `v` only if its current value is physically equal to `seen` \-- the comparison and the set occur atomically. Returns `true` if the comparison succeeded (so the set happened) and `false` otherwise. - -``` -val fetch_and_add : int t -> int -> int -``` -`fetch_and_add r n` atomically increments the value of `r` by `n`, and returns the current value (before the increment). - -``` -val incr : int t -> unit -``` -`incr r` atomically increments the value of `r` by `1`. - -``` -val decr : int t -> unit -``` -`decr r` atomically decrements the value of `r` by `1`. - - -## Examples - - -### Basic Thread Coordination - -A basic use case is to have global counters that are updated in a thread-safe way, for example to keep some sorts of metrics over IOs performed by the program. Another basic use case is to coordinate the termination of threads in a given program, for example when one thread finds an answer, or when the program is shut down by the user. - -Here, for example, we're going to try to find a number whose hash satisfies a basic property. To do that, we'll run multiple threads which will try random numbers until they find one that works. - -Of course the output below is a sample run and will change every time the program is run. - -```ocaml -(* use for termination *) -let stop_all_threads = Atomic.make false - -(* total number of individual attempts to find a number *) -let num_attempts = Atomic.make 0 - -(* find a number that satisfies [p], by... trying random numbers - until one fits. *) -let find_number_where (p:int -> bool) = - let rand = Random.State.make_self_init() in - while not (Atomic.get stop_all_threads) do - - let n = Random.State.full_int rand max_int in - ignore (Atomic.fetch_and_add num_attempts 1 : int); - - if p (Hashtbl.hash n) then ( - Printf.printf "found %d (hash=%d)\n%!" n (Hashtbl.hash n); - Atomic.set stop_all_threads true; (* signal all threads to stop *) - ) - done;; - - -(* run multiple domains to search for a [n] where [hash n <= 100] *) -let () = - let criterion n = n <= 100 in - let threads = - Array.init 8 - (fun _ -> Domain.spawn (fun () -> find_number_where criterion)) - in - Array.iter Domain.join threads; - Printf.printf "total number of attempts: %d\n%!" - (Atomic.get num_attempts) ;; - -- : unit = () -found 1651745641680046833 (hash=33) -total number of attempts: 30230350 -``` - -### Treiber Stack - -Another example is a basic [Treiber stack](https://en.wikipedia.org/wiki/Treiber_stack) (a thread-safe stack) that can be safely shared between threads. - -Note how both `push` and `pop` are recursive, because they attempt to swap the new stack (with one more, or one fewer, element) with the old stack. This is optimistic concurrency: each iteration of, say, `push stack x` gets the old stack `l`, and hopes that by the time it tries to replace `l` with `x::l`, nobody else has had time to modify the list. If the `compare_and_set` fails it means we were too optimistic, and must try again. - -```ocaml -type 'a stack = 'a list Atomic.t - -let rec push (stack: _ stack) elt : unit = - let cur = Atomic.get stack in - let success = Atomic.compare_and_set stack cur (elt :: cur) in - if not success then - push stack elt - -let rec pop (stack: _ stack) : _ option = - let cur = Atomic.get stack in - match cur with - | [] -> None - | x :: tail -> - let success = Atomic.compare_and_set stack cur tail in - if success then Some x - else pop stack - -# let st = Atomic.make [] -# push st 1 -- : unit = () -# push st 2 -- : unit = () -# pop st -- : int option = Some 2 -# pop st -- : int option = Some 1 -# pop st -- : int option = None -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Bool.md b/docs/api/ml/melange/Stdlib-Bool.md deleted file mode 100644 index d6f379425..000000000 --- a/docs/api/ml/melange/Stdlib-Bool.md +++ /dev/null @@ -1,83 +0,0 @@ - -# Module `Stdlib.Bool` - -Boolean values. - -since 4.08 - -## Booleans - -``` -type t = bool = -``` -``` -| false -``` -``` -| true -``` -``` - -``` -The type of booleans (truth values). - -The constructors `false` and `true` are included here so that they have paths, but they are not intended to be used in user-defined data types. - -``` -val not : bool -> bool -``` -`not b` is the boolean negation of `b`. - -``` -val (&&) : bool -> bool -> bool -``` -`e0 && e1` is the lazy boolean conjunction of expressions `e0` and `e1`. If `e0` evaluates to `false`, `e1` is not evaluated. Right-associative operator at precedence level 3/11. - -``` -val (||) : bool -> bool -> bool -``` -`e0 || e1` is the lazy boolean disjunction of expressions `e0` and `e1`. If `e0` evaluates to `true`, `e1` is not evaluated. Right-associative operator at precedence level 2/11. - - -## Predicates and comparisons - -``` -val equal : bool -> bool -> bool -``` -`equal b0 b1` is `true` if and only if `b0` and `b1` are both `true` or both `false`. - -``` -val compare : bool -> bool -> int -``` -`compare b0 b1` is a total order on boolean values. `false` is smaller than `true`. - - -## Converting - -``` -val to_int : bool -> int -``` -`to_int b` is `0` if `b` is `false` and `1` if `b` is `true`. - -``` -val to_float : bool -> float -``` -`to_float b` is `0.` if `b` is `false` and `1.` if `b` is `true`. - -``` -val to_string : bool -> string -``` -`to_string b` is `"true"` if `b` is `true` and `"false"` if `b` is `false`. - -``` -val seeded_hash : int -> bool -> int -``` -A seeded hash function for booleans, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : bool -> int -``` -An unseeded hash function for booleans, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Buffer.md b/docs/api/ml/melange/Stdlib-Buffer.md deleted file mode 100644 index 9af9a8328..000000000 --- a/docs/api/ml/melange/Stdlib-Buffer.md +++ /dev/null @@ -1,282 +0,0 @@ - -# Module `Stdlib.Buffer` - -Extensible buffers. - -This module implements buffers that automatically expand as necessary. It provides accumulative concatenation of strings in linear time (instead of quadratic time when strings are concatenated pairwise). For example: - -```ocaml - let concat_strings ss = - let b = Buffer.create 16 in - List.iter (Buffer.add_string b) ss; - Buffer.contents b - -``` -**Unsynchronized accesses** - -Unsynchronized accesses to a buffer may lead to an invalid buffer state. Thus, concurrent accesses to a buffer must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -type t -``` -The abstract type of buffers. - -``` -val create : int -> t -``` -`create n` returns a fresh buffer, initially empty. The `n` parameter is the initial size of the internal byte sequence that holds the buffer contents. That byte sequence is automatically reallocated when more than `n` characters are stored in the buffer, but shrinks back to `n` characters when `reset` is called. For best performance, `n` should be of the same order of magnitude as the number of characters that are expected to be stored in the buffer (for instance, 80 for a buffer that holds one output line). Nothing bad will happen if the buffer grows beyond that limit, however. In doubt, take `n = 16` for instance. If `n` is not between 1 and [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length), it will be clipped to that interval. - -``` -val contents : t -> string -``` -Return a copy of the current contents of the buffer. The buffer itself is unchanged. - -``` -val to_bytes : t -> bytes -``` -Return a copy of the current contents of the buffer. The buffer itself is unchanged. - -since 4.02 -``` -val sub : t -> int -> int -> string -``` -`Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off and len do not designate a valid range of b. -``` -val blit : t -> int -> bytes -> int -> int -> unit -``` -`Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if srcoff and len do not designate a valid range of src, or if dstoff and len do not designate a valid range of dst. -since 3.11.2 -``` -val nth : t -> int -> char -``` -Get the n-th character of the buffer. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if index out of bounds -``` -val length : t -> int -``` -Return the number of characters currently contained in the buffer. - -``` -val clear : t -> unit -``` -Empty the buffer. - -``` -val reset : t -> unit -``` -Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by [`Buffer.create`](./#val-create) `n`. For long-lived buffers that may have grown a lot, `reset` allows faster reclamation of the space used by the buffer. - -``` -val output_buffer : out_channel -> t -> unit -``` -`output_buffer oc b` writes the current contents of buffer `b` on the output channel `oc`. - -``` -val truncate : t -> int -> unit -``` -`truncate b len` truncates the length of `b` to `len` Note: the internal byte sequence is not shortened. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> length b. -since 4.05 - -## Appending - -Note: all `add_*` operations can raise `Failure` if the internal byte sequence of the buffer would need to grow beyond [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length). - -``` -val add_char : t -> char -> unit -``` -`add_char b c` appends the character `c` at the end of buffer `b`. - -``` -val add_utf_8_uchar : t -> Uchar.t -> unit -``` -`add_utf_8_uchar b u` appends the [UTF-8](https://tools.ietf.org/html/rfc3629) encoding of `u` at the end of buffer `b`. - -since 4.06 -``` -val add_utf_16le_uchar : t -> Uchar.t -> unit -``` -`add_utf_16le_uchar b u` appends the [UTF-16LE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. - -since 4.06 -``` -val add_utf_16be_uchar : t -> Uchar.t -> unit -``` -`add_utf_16be_uchar b u` appends the [UTF-16BE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. - -since 4.06 -``` -val add_string : t -> string -> unit -``` -`add_string b s` appends the string `s` at the end of buffer `b`. - -``` -val add_bytes : t -> bytes -> unit -``` -`add_bytes b s` appends the byte sequence `s` at the end of buffer `b`. - -since 4.02 -``` -val add_substring : t -> string -> int -> int -> unit -``` -`add_substring b s ofs len` takes `len` characters from offset `ofs` in string `s` and appends them at the end of buffer `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. -``` -val add_subbytes : t -> bytes -> int -> int -> unit -``` -`add_subbytes b s ofs len` takes `len` characters from offset `ofs` in byte sequence `s` and appends them at the end of buffer `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. -since 4.02 -``` -val add_substitute : t -> (string -> string) -> string -> unit -``` -`add_substitute b f s` appends the string pattern `s` at the end of buffer `b` with substitution. The substitution process looks for variable references in the pattern and substitutes each variable reference with its value, as obtained by applying the mapping `f` to the variable name. Inside the string pattern, a variable reference is a non-escaped `$` immediately followed by a variable name, which is one of the following: - -- a non empty sequence of alphanumeric or `_` characters, -- an arbitrary sequence of characters enclosed by a pair of matching parentheses or curly brackets. An escaped `$` character is a `$` that immediately follows a backslash character; the two characters together stand for a plain `$`. -``` -val add_buffer : t -> t -> unit -``` -`add_buffer b1 b2` appends the current contents of buffer `b2` at the end of buffer `b1`. `b2` is not modified. - -``` -val add_channel : t -> in_channel -> int -> unit -``` -`add_channel b ic n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`. - -raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if the channel contains fewer than n characters. In this case, the characters are still added to the buffer, so as to avoid loss of data. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> Sys.max\_string\_length. - -## Buffers and Sequences - -``` -val to_seq : t -> char Seq.t -``` -Iterate on the buffer, in increasing order. - -The behavior is not specified if the buffer is modified during iteration. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -Iterate on the buffer, in increasing order, yielding indices along chars. - -The behavior is not specified if the buffer is modified during iteration. - -since 4.07 -``` -val add_seq : t -> char Seq.t -> unit -``` -Add chars to the buffer - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -Create a buffer from the generator - -since 4.07 - -## Binary encoding of integers - -The functions in this section append binary encodings of integers to buffers. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. Functions that encode these values truncate their inputs to their least significant bytes. - -``` -val add_uint8 : t -> int -> unit -``` -`add_uint8 b i` appends a binary unsigned 8-bit integer `i` to `b`. - -since 4.08 -``` -val add_int8 : t -> int -> unit -``` -`add_int8 b i` appends a binary signed 8-bit integer `i` to `b`. - -since 4.08 -``` -val add_uint16_ne : t -> int -> unit -``` -`add_uint16_ne b i` appends a binary native-endian unsigned 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_uint16_be : t -> int -> unit -``` -`add_uint16_be b i` appends a binary big-endian unsigned 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_uint16_le : t -> int -> unit -``` -`add_uint16_le b i` appends a binary little-endian unsigned 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int16_ne : t -> int -> unit -``` -`add_int16_ne b i` appends a binary native-endian signed 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int16_be : t -> int -> unit -``` -`add_int16_be b i` appends a binary big-endian signed 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int16_le : t -> int -> unit -``` -`add_int16_le b i` appends a binary little-endian signed 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int32_ne : t -> int32 -> unit -``` -`add_int32_ne b i` appends a binary native-endian 32-bit integer `i` to `b`. - -since 4.08 -``` -val add_int32_be : t -> int32 -> unit -``` -`add_int32_be b i` appends a binary big-endian 32-bit integer `i` to `b`. - -since 4.08 -``` -val add_int32_le : t -> int32 -> unit -``` -`add_int32_le b i` appends a binary little-endian 32-bit integer `i` to `b`. - -since 4.08 -``` -val add_int64_ne : t -> int64 -> unit -``` -`add_int64_ne b i` appends a binary native-endian 64-bit integer `i` to `b`. - -since 4.08 -``` -val add_int64_be : t -> int64 -> unit -``` -`add_int64_be b i` appends a binary big-endian 64-bit integer `i` to `b`. - -since 4.08 -``` -val add_int64_le : t -> int64 -> unit -``` -`add_int64_ne b i` appends a binary little-endian 64-bit integer `i` to `b`. - -since 4.08 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Bytes.md b/docs/api/ml/melange/Stdlib-Bytes.md deleted file mode 100644 index 28c026643..000000000 --- a/docs/api/ml/melange/Stdlib-Bytes.md +++ /dev/null @@ -1,683 +0,0 @@ - -# Module `Stdlib.Bytes` - -Byte sequence operations. - -A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. - -Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. - -Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. - -Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. - -Bytes are represented by the OCaml type `char`. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -since 4.02 -``` -val length : bytes -> int -``` -Return the length (number of bytes) of the argument. - -``` -val get : bytes -> int -> char -``` -`get s n` returns the byte at index `n` in argument `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val set : bytes -> int -> char -> unit -``` -`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val create : int -> bytes -``` -`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val make : int -> char -> bytes -``` -`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> (int -> char) -> bytes -``` -`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val empty : bytes -``` -A byte sequence of size 0. - -``` -val copy : bytes -> bytes -``` -Return a new byte sequence that contains the same bytes as the argument. - -``` -val of_string : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -``` -val to_string : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -``` -val sub : bytes -> int -> int -> bytes -``` -`sub s pos len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val sub_string : bytes -> int -> int -> string -``` -Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. - -``` -val extend : bytes -> int -> int -> bytes -``` -`extend s left right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val fill : bytes -> int -> int -> char -> unit -``` -`fill s pos len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val blit : bytes -> int -> bytes -> int -> int -> unit -``` -`blit src src_pos dst dst_pos len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -``` -val blit_string : string -> int -> bytes -> int -> int -> unit -``` -`blit_string src src_pos dst dst_pos len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -since 4.05 in BytesLabels -``` -val concat : bytes -> bytes list -> bytes -``` -`concat sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : bytes -> bytes -> bytes -``` -`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val iter : (char -> unit) -> bytes -> unit -``` -`iter f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. - -``` -val iteri : (int -> char -> unit) -> bytes -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. - -``` -val map : (char -> char) -> bytes -> bytes -``` -`map f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val mapi : (int -> char -> char) -> bytes -> bytes -``` -`mapi f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val fold_left : ('acc -> char -> 'acc) -> 'acc -> bytes -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. - -since 4.13 -``` -val fold_right : (char -> 'acc -> 'acc) -> bytes -> 'acc -> 'acc -``` -`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. - -since 4.13 -``` -val for_all : (char -> bool) -> bytes -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : (char -> bool) -> bytes -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : bytes -> bytes -``` -Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. - -``` -val escaped : bytes -> bytes -``` -Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val index : bytes -> char -> int -``` -`index s c` returns the index of the first occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val index_opt : bytes -> char -> int option -``` -`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val rindex : bytes -> char -> int -``` -`rindex s c` returns the index of the last occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val rindex_opt : bytes -> char -> int option -``` -`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val index_from : bytes -> int -> char -> int -``` -`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -``` -val index_from_opt : bytes -> int -> char -> int option -``` -`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : bytes -> int -> char -> int -``` -`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -``` -val rindex_from_opt : bytes -> int -> char -> int option -``` -`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val contains : bytes -> char -> bool -``` -`contains s c` tests if byte `c` appears in `s`. - -``` -val contains_from : bytes -> int -> char -> bool -``` -`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : bytes -> int -> char -> bool -``` -`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val uppercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val lowercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val capitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val uncapitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -type t = bytes -``` -An alias for the type of byte sequences. - -``` -val compare : t -> t -> int -``` -The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val equal : t -> t -> bool -``` -The equality function for byte sequences. - -since 4.03 (4.05 in BytesLabels) -``` -val starts_with : prefix:bytes -> bytes -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:bytes -> bytes -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 - -## Unsafe conversions (for advanced users) - -This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. - -``` -val unsafe_to_string : bytes -> string -``` -Unsafely convert a byte sequence into a string. - -To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: - -- Unique ownership: the data may be accessed and mutated -- Shared ownership: the data has several owners, that may only access it, not mutate it. -Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. - -`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. - -There are two valid use-cases that respect this ownership discipline: - -1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. - -```ocaml -let string_init len f : string = - let s = Bytes.create len in - for i = 0 to len - 1 do Bytes.set s i (f i) done; - Bytes.unsafe_to_string s -``` -This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. - -Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. - -We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. - -2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. - -```ocaml -let bytes_length (s : bytes) = - String.length (Bytes.unsafe_to_string s) -``` -In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. - -The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. - -``` -val unsafe_of_string : string -> bytes -``` -Unsafely convert a shared string to a byte sequence that should not be mutated. - -The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. - -In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. - -For example, string literals are implicitly shared by the compiler, so you never uniquely own them. - -```ocaml -let incorrect = Bytes.unsafe_of_string "hello" -let s = Bytes.of_string "hello" -``` -The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. - -Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. - -The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. - -``` -val split_on_char : char -> bytes -> bytes list -``` -`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. - -The function's output is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). -- No byte sequence in the result contains the `sep` character. -since 4.13 - -## Iterators - -``` -val to_seq : t -> char Seq.t -``` -Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -Iterate on the string, in increasing order, yielding indices along chars - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -Create a string from the generator - -since 4.07 - -## UTF codecs and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val set_utf_8_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val set_utf_16be_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val set_utf_16le_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary encoding/decoding of integers - -The functions in this section binary encode and decode integers to and from byte sequences. - -All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: - -- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. -- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. -``` -val get_uint8 : bytes -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int8 : bytes -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_ne : bytes -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_be : bytes -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_le : bytes -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_ne : bytes -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_be : bytes -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_le : bytes -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_ne : bytes -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_be : bytes -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_le : bytes -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_ne : bytes -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_be : bytes -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_le : bytes -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val set_uint8 : bytes -> int -> int -> unit -``` -`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int8 : bytes -> int -> int -> unit -``` -`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_ne : bytes -> int -> int -> unit -``` -`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_be : bytes -> int -> int -> unit -``` -`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_le : bytes -> int -> int -> unit -``` -`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_ne : bytes -> int -> int -> unit -``` -`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_be : bytes -> int -> int -> unit -``` -`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_le : bytes -> int -> int -> unit -``` -`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_ne : bytes -> int -> int32 -> unit -``` -`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_be : bytes -> int -> int32 -> unit -``` -`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_le : bytes -> int -> int32 -> unit -``` -`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_ne : bytes -> int -> int64 -> unit -``` -`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_be : bytes -> int -> int64 -> unit -``` -`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_le : bytes -> int -> int64 -> unit -``` -`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 - -## Byte sequences and concurrency safety - -Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let b = Bytes.make size ' ' -let update b f () = - Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b -let d1 = Domain.spawn (update b (fun x -> x + 1)) -let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) -let () = Domain.join d1; Domain.join d2 -``` -the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. - -After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. - - -### Mixed-size accesses - -Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index - -```ocaml -let b = Bytes.make 10 '\000' -let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) -``` -In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/ml/melange/Stdlib-BytesLabels.md b/docs/api/ml/melange/Stdlib-BytesLabels.md deleted file mode 100644 index ece55c1e0..000000000 --- a/docs/api/ml/melange/Stdlib-BytesLabels.md +++ /dev/null @@ -1,695 +0,0 @@ - -# Module `Stdlib.BytesLabels` - -Byte sequence operations. - -A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. - -Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. - -Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. - -Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. - -Bytes are represented by the OCaml type `char`. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -since 4.02 -``` -val length : bytes -> int -``` -Return the length (number of bytes) of the argument. - -``` -val get : bytes -> int -> char -``` -`get s n` returns the byte at index `n` in argument `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val set : bytes -> int -> char -> unit -``` -`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val create : int -> bytes -``` -`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val make : int -> char -> bytes -``` -`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> f:(int -> char) -> bytes -``` -`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val empty : bytes -``` -A byte sequence of size 0. - -``` -val copy : bytes -> bytes -``` -Return a new byte sequence that contains the same bytes as the argument. - -``` -val of_string : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -``` -val to_string : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -``` -val sub : bytes -> pos:int -> len:int -> bytes -``` -`sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val sub_string : bytes -> pos:int -> len:int -> string -``` -Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. - -``` -val extend : bytes -> left:int -> right:int -> bytes -``` -`extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val fill : bytes -> pos:int -> len:int -> char -> unit -``` -`fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val blit : - src:bytes -> - src_pos:int -> - dst:bytes -> - dst_pos:int -> - len:int -> - unit -``` -`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -``` -val blit_string : - src:string -> - src_pos:int -> - dst:bytes -> - dst_pos:int -> - len:int -> - unit -``` -`blit_string ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -since 4.05 in BytesLabels -``` -val concat : sep:bytes -> bytes list -> bytes -``` -`concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : bytes -> bytes -> bytes -``` -`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val iter : f:(char -> unit) -> bytes -> unit -``` -`iter ~f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. - -``` -val iteri : f:(int -> char -> unit) -> bytes -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. - -``` -val map : f:(char -> char) -> bytes -> bytes -``` -`map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val mapi : f:(int -> char -> char) -> bytes -> bytes -``` -`mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> bytes -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. - -since 4.13 -``` -val fold_right : f:(char -> 'acc -> 'acc) -> bytes -> init:'acc -> 'acc -``` -`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. - -since 4.13 -``` -val for_all : f:(char -> bool) -> bytes -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : f:(char -> bool) -> bytes -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : bytes -> bytes -``` -Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. - -``` -val escaped : bytes -> bytes -``` -Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val index : bytes -> char -> int -``` -`index s c` returns the index of the first occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val index_opt : bytes -> char -> int option -``` -`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val rindex : bytes -> char -> int -``` -`rindex s c` returns the index of the last occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val rindex_opt : bytes -> char -> int option -``` -`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val index_from : bytes -> int -> char -> int -``` -`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -``` -val index_from_opt : bytes -> int -> char -> int option -``` -`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : bytes -> int -> char -> int -``` -`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -``` -val rindex_from_opt : bytes -> int -> char -> int option -``` -`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val contains : bytes -> char -> bool -``` -`contains s c` tests if byte `c` appears in `s`. - -``` -val contains_from : bytes -> int -> char -> bool -``` -`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : bytes -> int -> char -> bool -``` -`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val uppercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val lowercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val capitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val uncapitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -type t = bytes -``` -An alias for the type of byte sequences. - -``` -val compare : t -> t -> int -``` -The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val equal : t -> t -> bool -``` -The equality function for byte sequences. - -since 4.03 (4.05 in BytesLabels) -``` -val starts_with : prefix:bytes -> bytes -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:bytes -> bytes -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 - -## Unsafe conversions (for advanced users) - -This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. - -``` -val unsafe_to_string : bytes -> string -``` -Unsafely convert a byte sequence into a string. - -To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: - -- Unique ownership: the data may be accessed and mutated -- Shared ownership: the data has several owners, that may only access it, not mutate it. -Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. - -`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. - -There are two valid use-cases that respect this ownership discipline: - -1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. - -```ocaml -let string_init len f : string = - let s = Bytes.create len in - for i = 0 to len - 1 do Bytes.set s i (f i) done; - Bytes.unsafe_to_string s -``` -This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. - -Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. - -We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. - -2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. - -```ocaml -let bytes_length (s : bytes) = - String.length (Bytes.unsafe_to_string s) -``` -In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. - -The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. - -``` -val unsafe_of_string : string -> bytes -``` -Unsafely convert a shared string to a byte sequence that should not be mutated. - -The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. - -In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. - -For example, string literals are implicitly shared by the compiler, so you never uniquely own them. - -```ocaml -let incorrect = Bytes.unsafe_of_string "hello" -let s = Bytes.of_string "hello" -``` -The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. - -Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. - -The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. - -``` -val split_on_char : sep:char -> bytes -> bytes list -``` -`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. - -The function's output is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). -- No byte sequence in the result contains the `sep` character. -since 4.13 - -## Iterators - -``` -val to_seq : t -> char Seq.t -``` -Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -Iterate on the string, in increasing order, yielding indices along chars - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -Create a string from the generator - -since 4.07 - -## UTF codecs and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val set_utf_8_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val set_utf_16be_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val set_utf_16le_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary encoding/decoding of integers - -The functions in this section binary encode and decode integers to and from byte sequences. - -All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: - -- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. -- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. -``` -val get_uint8 : bytes -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int8 : bytes -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_ne : bytes -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_be : bytes -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_le : bytes -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_ne : bytes -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_be : bytes -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_le : bytes -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_ne : bytes -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_be : bytes -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_le : bytes -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_ne : bytes -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_be : bytes -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_le : bytes -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val set_uint8 : bytes -> int -> int -> unit -``` -`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int8 : bytes -> int -> int -> unit -``` -`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_ne : bytes -> int -> int -> unit -``` -`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_be : bytes -> int -> int -> unit -``` -`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_le : bytes -> int -> int -> unit -``` -`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_ne : bytes -> int -> int -> unit -``` -`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_be : bytes -> int -> int -> unit -``` -`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_le : bytes -> int -> int -> unit -``` -`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_ne : bytes -> int -> int32 -> unit -``` -`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_be : bytes -> int -> int32 -> unit -``` -`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_le : bytes -> int -> int32 -> unit -``` -`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_ne : bytes -> int -> int64 -> unit -``` -`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_be : bytes -> int -> int64 -> unit -``` -`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_le : bytes -> int -> int64 -> unit -``` -`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 - -## Byte sequences and concurrency safety - -Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let b = Bytes.make size ' ' -let update b f () = - Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b -let d1 = Domain.spawn (update b (fun x -> x + 1)) -let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) -let () = Domain.join d1; Domain.join d2 -``` -the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. - -After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. - - -### Mixed-size accesses - -Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index - -```ocaml -let b = Bytes.make 10 '\000' -let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) -``` -In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/ml/melange/Stdlib-Char.md b/docs/api/ml/melange/Stdlib-Char.md deleted file mode 100644 index 31c382bda..000000000 --- a/docs/api/ml/melange/Stdlib-Char.md +++ /dev/null @@ -1,61 +0,0 @@ - -# Module `Stdlib.Char` - -Character operations. - -``` -val code : char -> int -``` -Return the ASCII code of the argument. - -``` -val chr : int -> char -``` -Return the character with the given ASCII code. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is outside the range 0--255. -``` -val escaped : char -> string -``` -Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote. - -``` -val lowercase_ascii : char -> char -``` -Convert the given character to its equivalent lowercase character, using the US-ASCII character set. - -since 4.03 -``` -val uppercase_ascii : char -> char -``` -Convert the given character to its equivalent uppercase character, using the US-ASCII character set. - -since 4.03 -``` -type t = char -``` -An alias for the type of characters. - -``` -val compare : t -> t -> int -``` -The comparison function for characters, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Char` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val equal : t -> t -> bool -``` -The equal function for chars. - -since 4.03 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for characters, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for characters, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Complex.md b/docs/api/ml/melange/Stdlib-Complex.md deleted file mode 100644 index e751d99b7..000000000 --- a/docs/api/ml/melange/Stdlib-Complex.md +++ /dev/null @@ -1,106 +0,0 @@ - -# Module `Stdlib.Complex` - -Complex numbers. - -This module provides arithmetic operations on complex numbers. Complex numbers are represented by their real and imaginary parts (cartesian representation). Each part is represented by a double-precision floating-point number (type `float`). - -``` -type t = { -``` -`re : float;` -`im : float;` -``` -} -``` -The type of complex numbers. `re` is the real part and `im` the imaginary part. - -``` -val zero : t -``` -The complex number `0`. - -``` -val one : t -``` -The complex number `1`. - -``` -val i : t -``` -The complex number `i`. - -``` -val neg : t -> t -``` -Unary negation. - -``` -val conj : t -> t -``` -Conjugate: given the complex `x + i.y`, returns `x - i.y`. - -``` -val add : t -> t -> t -``` -Addition - -``` -val sub : t -> t -> t -``` -Subtraction - -``` -val mul : t -> t -> t -``` -Multiplication - -``` -val inv : t -> t -``` -Multiplicative inverse (`1/z`). - -``` -val div : t -> t -> t -``` -Division - -``` -val sqrt : t -> t -``` -Square root. The result `x + i.y` is such that `x > 0` or `x = 0` and `y >= 0`. This function has a discontinuity along the negative real axis. - -``` -val norm2 : t -> float -``` -Norm squared: given `x + i.y`, returns `x^2 + y^2`. - -``` -val norm : t -> float -``` -Norm: given `x + i.y`, returns `sqrt(x^2 + y^2)`. - -``` -val arg : t -> float -``` -Argument. The argument of a complex number is the angle in the complex plane between the positive real axis and a line passing through zero and the number. This angle ranges from `-pi` to `pi`. This function has a discontinuity along the negative real axis. - -``` -val polar : float -> float -> t -``` -`polar norm arg` returns the complex having norm `norm` and argument `arg`. - -``` -val exp : t -> t -``` -Exponentiation. `exp z` returns `e` to the `z` power. - -``` -val log : t -> t -``` -Natural logarithm (in base `e`). - -``` -val pow : t -> t -> t -``` -Power function. `pow z1 z2` returns `z1` to the `z2` power. diff --git a/docs/api/ml/melange/Stdlib-Digest-BLAKE128.md b/docs/api/ml/melange/Stdlib-Digest-BLAKE128.md deleted file mode 100644 index d066e1e33..000000000 --- a/docs/api/ml/melange/Stdlib-Digest-BLAKE128.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.BLAKE128` - -`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Digest-BLAKE256.md b/docs/api/ml/melange/Stdlib-Digest-BLAKE256.md deleted file mode 100644 index ee9952c96..000000000 --- a/docs/api/ml/melange/Stdlib-Digest-BLAKE256.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.BLAKE256` - -`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Digest-BLAKE512.md b/docs/api/ml/melange/Stdlib-Digest-BLAKE512.md deleted file mode 100644 index a22b0bc72..000000000 --- a/docs/api/ml/melange/Stdlib-Digest-BLAKE512.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.BLAKE512` - -`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Digest-MD5.md b/docs/api/ml/melange/Stdlib-Digest-MD5.md deleted file mode 100644 index 9909a727e..000000000 --- a/docs/api/ml/melange/Stdlib-Digest-MD5.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.MD5` - -`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Digest-module-type-S.md b/docs/api/ml/melange/Stdlib-Digest-module-type-S.md deleted file mode 100644 index 8e6095b8a..000000000 --- a/docs/api/ml/melange/Stdlib-Digest-module-type-S.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module type `Digest.S` - -The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Digest.md b/docs/api/ml/melange/Stdlib-Digest.md deleted file mode 100644 index 6ef661f6d..000000000 --- a/docs/api/ml/melange/Stdlib-Digest.md +++ /dev/null @@ -1,120 +0,0 @@ - -# Module `Stdlib.Digest` - -Message digest. - -This module provides functions to compute 'digests', also known as 'hashes', of arbitrary-length strings or files. The supported hashing algorithms are BLAKE2 and MD5. - - -## Basic functions - -The functions in this section use the MD5 hash function to produce 128-bit digests (16 bytes). MD5 is not cryptographically secure. Hence, these functions should not be used for security-sensitive applications. The BLAKE2 functions below are cryptographically secure. - -``` -type t = string -``` -The type of digests: 16-byte strings. - -``` -val compare : t -> t -> int -``` -The comparison function for 16-byte digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare) and the implementation shared with [`String.compare`](./Stdlib-String.md#val-compare). Along with the type `t`, this function `compare` allows the module `Digest` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -since 4.00 -``` -val equal : t -> t -> bool -``` -The equal function for 16-byte digests. - -since 4.03 -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -since 4.02 -``` -val substring : string -> int -> int -> t -``` -`Digest.substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`Digest.subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -since 4.02 -``` -val channel : in_channel -> int -> t -``` -If `len` is nonnegative, `Digest.channel ic len` reads `len` characters from channel `ic` and returns their digest, or raises `End_of_file` if end-of-file is reached before `len` characters are read. If `len` is negative, `Digest.channel ic len` reads all characters from `ic` until end-of-file is reached and return their digest. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 16 bytes. -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 32 hexadecimal characters. -since 5.2 -``` -val from_hex : string -> t -``` -Same function as [`Digest.of_hex`](./#val-of_hex). - -since 4.00 - -## Generic interface - -``` -module type S = sig ... end -``` -The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. - - -## Specific hash functions - -``` -module BLAKE128 : S -``` -`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. - -``` -module BLAKE256 : S -``` -`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -``` -module BLAKE512 : S -``` -`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -``` -module MD5 : S -``` -`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. diff --git a/docs/api/ml/melange/Stdlib-Domain-DLS.md b/docs/api/ml/melange/Stdlib-Domain-DLS.md deleted file mode 100644 index 5c29e70ee..000000000 --- a/docs/api/ml/melange/Stdlib-Domain-DLS.md +++ /dev/null @@ -1,45 +0,0 @@ - -# Module `Domain.DLS` - -Domain-local Storage - -``` -type 'a key -``` -Type of a DLS key - -``` -val new_key : ?split_from_parent:('a -> 'a) -> (unit -> 'a) -> 'a key -``` -`new_key f` returns a new key bound to initialiser `f` for accessing domain-local variables. - -If `split_from_parent` is not provided, the value for a new domain will be computed on-demand by the new domain: the first `get` call will call the initializer `f` and store that value. - -**Warning.** `f` may be called several times if another call to `get` occurs during initialization on the same domain. Only the 'first' value computed will be used, the other now-useless values will be discarded. Your initialization function should support this situation, or contain logic to detect this case and fail. - -If `split_from_parent` is provided, spawning a domain will derive the child value (for this key) from the parent value. This computation happens in the parent domain and it always happens, regardless of whether the child domain will use it. If the splitting function is expensive or requires child-side computation, consider using `'a Lazy.t key`: - -```ocaml -let init () = ... - -let split_from_parent parent_value = - ... parent-side computation ...; - lazy ( - ... child-side computation ... - ) - -let key = Domain.DLS.new_key ~split_from_parent init - -let get () = Lazy.force (Domain.DLS.get key) -``` -In this case a part of the computation happens on the child domain; in particular, it can access `parent_value` concurrently with the parent domain, which may require explicit synchronization to avoid data races. - -``` -val get : 'a key -> 'a -``` -`get k` returns `v` if a value `v` is associated to the key `k` on the calling domain's domain-local state. Sets `k`'s value with its initialiser and returns it otherwise. - -``` -val set : 'a key -> 'a -> unit -``` -`set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. It overwrites any previous values associated to `k`, which cannot be restored later. diff --git a/docs/api/ml/melange/Stdlib-Domain.md b/docs/api/ml/melange/Stdlib-Domain.md deleted file mode 100644 index 5a038a823..000000000 --- a/docs/api/ml/melange/Stdlib-Domain.md +++ /dev/null @@ -1,89 +0,0 @@ - -# Module `Stdlib.Domain` - -alert unstable The Domain interface may change in incompatible ways in the future. -Domains. - -See 'Parallel programming' chapter in the manual. - -since 5.0 -alert unstable The Domain interface may change in incompatible ways in the future. -``` -type !'a t -``` -A domain of type `'a t` runs independently, eventually producing a result of type 'a, or an exception - -``` -val spawn : (unit -> 'a) -> 'a t -``` -`spawn f` creates a new domain that runs in parallel with the current domain. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the program has insufficient resources to create another domain. -``` -val join : 'a t -> 'a Js.Promise.t -``` -`join d` blocks until domain `d` runs to completion. If `d` results in a value, then that is returned by `join d`. If `d` raises an uncaught exception, then that is re-raised by `join d`. - -``` -type id = private int -``` -Domains have unique integer identifiers - -``` -val get_id : 'a t -> id -``` -`get_id d` returns the identifier of the domain `d` - -``` -val self : unit -> id -``` -`self ()` is the identifier of the currently running domain - -``` -val before_first_spawn : (unit -> unit) -> unit -``` -`before_first_spawn f` registers `f` to be called before the first domain is spawned by the program. The functions registered with `before_first_spawn` are called on the main (initial) domain. The functions registered with `before_first_spawn` are called in 'first in, first out' order: the oldest function added with `before_first_spawn` is called first. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the program has already spawned a domain. -``` -val at_exit : (unit -> unit) -> unit -``` -`at_exit f` registers `f` to be called when the current domain exits. Note that `at_exit` callbacks are domain-local and only apply to the calling domain. The registered functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. An example: - -```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) -``` -The snippet above creates a key that when retrieved for the first time will open a temporary file and register an `at_exit` callback to close it, thus guaranteeing the descriptor is not leaked in case the current domain exits. - -``` -val cpu_relax : unit -> unit -``` -If busy-waiting, calling cpu\_relax () between iterations will improve performance on some CPU architectures - -``` -val is_main_domain : unit -> bool -``` -`is_main_domain ()` returns true if called from the initial domain. - -``` -val recommended_domain_count : unit -> int -``` -The recommended maximum number of domains which should be running simultaneously (including domains already running). - -The value returned is at least `1`. - -``` -val self_index : unit -> int -``` -The index of the current domain. It is an integer unique among currently-running domains, in the interval `0; N-1` where N is the peak number of domains running simultaneously so far. - -The index of a terminated domain may be reused for a new domain. Use `(Domain.self () :> int)` instead for an identifier unique among all domains ever created by the program. - -since 5.3 -``` -module DLS : sig ... end -``` -Domain-local Storage diff --git a/docs/api/ml/melange/Stdlib-Dynarray.md b/docs/api/ml/melange/Stdlib-Dynarray.md deleted file mode 100644 index c278e16be..000000000 --- a/docs/api/ml/melange/Stdlib-Dynarray.md +++ /dev/null @@ -1,582 +0,0 @@ - -# Module `Stdlib.Dynarray` - -Dynamic arrays. - -The [`Array`](./Stdlib-Array.md) module provide arrays of fixed length. [`Dynarray`](#) provides arrays whose length can change over time, by adding or removing elements at the end of the array. - -This is typically used to accumulate elements whose number is not known in advance or changes during computation, while also providing fast access to elements at arbitrary indices. - -```ocaml - let dynarray_of_list li = - let arr = Dynarray.create () in - List.iter (fun v -> Dynarray.add_last arr v) li; - arr -``` -The [`Buffer`](./Stdlib-Buffer.md) module provides similar features, but it is specialized for accumulating characters into a dynamically-resized string. - -The [`Stack`](./Stdlib-Stack.md) module provides a last-in first-out data structure that can be easily implemented on top of dynamic arrays. - -since 5.2 -**Unsynchronized accesses** - -Concurrent accesses to dynamic arrays must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). Unsynchronized accesses to a dynamic array are a programming error that may lead to an invalid dynamic array state, on which some operations would fail with an `Invalid_argument` exception. - - -## Dynamic arrays - -``` -type !'a t -``` -A dynamic array containing values of type `'a`. - -A dynamic array `a` provides constant-time `get` and `set` operations on indices between `0` and `Dynarray.length a - 1` included. Its [`length`](./#val-length) may change over time by adding or removing elements to the end of the array. - -We say that an index into a dynarray `a` is valid if it is in `0 .. length a - 1` and invalid otherwise. - -``` -val create : unit -> 'a t -``` -`create ()` is a new, empty array. - -``` -val make : int -> 'a -> 'a t -``` -`make n x` is a new array of length `n`, filled with `x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. -``` -val init : int -> (int -> 'a) -> 'a t -``` -`init n f` is a new array `a` of length `n`, such that `get a i` is `f i`. In other words, the elements of `a` are `f 0`, then `f 1`, then `f 2`... and `f (n - 1)` last, evaluated in that order. - -This is similar to [`Array.init`](./Stdlib-Array.md#val-init). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. -``` -val get : 'a t -> int -> 'a -``` -`get a i` is the `i`\-th element of `a`, starting with index `0`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid -``` -val set : 'a t -> int -> 'a -> unit -``` -`set a i x` sets the `i`\-th element of `a` to be `x`. - -`i` must be a valid index. `set` does not add new elements to the array \-- see [`add_last`](./#val-add_last) to add an element. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid. -``` -val length : 'a t -> int -``` -`length a` is the number of elements in the array. - -``` -val is_empty : 'a t -> bool -``` -`is_empty a` is `true` if `a` is empty, that is, if `length a = 0`. - -``` -val get_last : 'a t -> 'a -``` -`get_last a` is the element of `a` at index `length a - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if a is empty. -``` -val find_last : 'a t -> 'a option -``` -`find_last a` is `None` if `a` is empty and `Some (get_last a)` otherwise. - -``` -val copy : 'a t -> 'a t -``` -`copy a` is a shallow copy of `a`, a new array containing the same elements as `a`. - - -## Adding elements - -Note: all operations adding elements raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). - -``` -val add_last : 'a t -> 'a -> unit -``` -`add_last a x` adds the element `x` at the end of the array `a`. - -``` -val append_array : 'a t -> 'a array -> unit -``` -`append_array a b` adds all elements of `b` at the end of `a`, in the order they appear in `b`. - -For example: - -```ocaml - let a = Dynarray.of_list [1;2] in - Dynarray.append_array a [|3; 4|]; - assert (Dynarray.to_list a = [1; 2; 3; 4]) -``` -``` -val append_list : 'a t -> 'a list -> unit -``` -Like [`append_array`](./#val-append_array) but with a list. - -``` -val append : 'a t -> 'a t -> unit -``` -`append a b` is like `append_array a b`, but `b` is itself a dynamic array instead of a fixed-size array. - -Warning: `append a a` is a programming error because it iterates on `a` and adds elements to it at the same time \-- see the [Iteration](./#iteration) section below. It fails with `Invalid_argument`. If you really want to append a copy of `a` to itself, you can use `Dynarray.append_array a (Dynarray.to_array a)` which copies `a` into a temporary array. - -``` -val append_seq : 'a t -> 'a Seq.t -> unit -``` -Like [`append_array`](./#val-append_array) but with a sequence. - -Warning: `append_seq a (to_seq_reentrant a)` simultaneously traverses `a` and adds element to it; the ordering of those operations is unspecified, and may result in an infinite loop \-- the new elements may in turn be produced by `to_seq_reentrant a` and get added again and again. - -``` -val append_iter : 'a t -> (('a -> unit) -> 'x -> unit) -> 'x -> unit -``` -`append_iter a iter x` adds each element of `x` to the end of `a`. This is `iter (add_last a) x`. - -For example, `append_iter a List.iter [1;2;3]` would add elements `1`, `2`, and then `3` at the end of `a`. `append_iter a Queue.iter q` adds elements from the queue `q`. - -``` -val blit : - src:'a t -> - src_pos:int -> - dst:'a t -> - dst_pos:int -> - len:int -> - unit -``` -`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from a source dynarray `src`, starting at index `src_pos`, to a destination dynarray `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. - -Unlike [`Array.blit`](./Stdlib-Array.md#val-blit), [`Dynarray.blit`](./#val-blit) can extend the destination array with new elements: it is valid to call `blit` even when `dst_pos + len` is larger than `length dst`. The only requirement is that `dst_pos` must be at most `length dst` (included), so that there is no gap between the current elements and the blit region. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos is strictly below 0 or strictly above length dst. - -## Removing elements - -``` -val pop_last_opt : 'a t -> 'a option -``` -`pop_last_opt a` removes and returns the last element of `a`, or `None` if the array is empty. - -``` -val pop_last : 'a t -> 'a -``` -`pop_last a` removes and returns the last element of `a`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) on an empty array. -``` -val remove_last : 'a t -> unit -``` -`remove_last a` removes the last element of `a`, if any. It does nothing if `a` is empty. - -``` -val truncate : 'a t -> int -> unit -``` -`truncate a n` truncates `a` to have at most `n` elements. - -It removes elements whose index is greater or equal to `n`. It does nothing if `n >= length a`. - -`truncate a n` is equivalent to: - -```ocaml - if n < 0 then invalid_argument "..."; - while length a > n do - remove_last a - done -``` -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. -``` -val clear : 'a t -> unit -``` -`clear a` is `truncate a 0`, it removes all the elements of `a`. - - -## Iteration - -The iteration functions traverse the elements of a dynamic array. Traversals of `a` are computed in increasing index order: from the element of index `0` to the element of index `length a - 1`. - -It is a programming error to change the length of an array (by adding or removing elements) during an iteration on the array. Any iteration function will fail with `Invalid_argument` if it detects such a length change. - -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f a` calls `f` on each element of `a`. - -``` -val iteri : (int -> 'a -> unit) -> 'a t -> unit -``` -`iteri f a` calls `f i x` for each `x` at index `i` in `a`. - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f a` is a new array of elements of the form `f x` for each element `x` of `a`. - -For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f x0`, `f x1`, `f x2`. - -``` -val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t -``` -`mapi f a` is a new array of elements of the form `f i x` for each element `x` of `a` at index `i`. - -For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f 0 x0`, `f 1 x1`, `f 2 x2`. - -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold_left f acc a` folds `f` over `a` in order, starting with accumulator `acc`. - -For example, if the elements of `a` are `x0`, `x1`, then `fold f acc a` is - -```ocaml - let acc = f acc x0 in - let acc = f acc x1 in - acc -``` -``` -val fold_right : ('a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -`fold_right f a acc` computes `f x0 (f x1 (... (f xn acc) ...))` where `x0`, `x1`, ..., `xn` are the elements of `a`. - -``` -val filter : ('a -> bool) -> 'a t -> 'a t -``` -`filter f a` is a new array of all the elements of `a` that satisfy `f`. In other words, it is an array `b` such that, for each element `x` in `a` in order, `x` is added to `b` if `f x` is `true`. - -For example, `filter (fun x -> x >= 0) a` is a new array of all non-negative elements of `a`, in order. - -``` -val filter_map : ('a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f a` is a new array of elements `y` such that `f x` is `Some y` for an element `x` of `a`. In others words, it is an array `b` such that, for each element `x` of `a` in order: - -- if `f x = Some y`, then `y` is added to `b`, -- if `f x = None`, then no element is added to `b`. -For example, `filter_map int_of_string_opt inputs` returns a new array of integers read from the strings in `inputs`, ignoring strings that cannot be converted to integers. - - -## Dynarray scanning - -``` -val exists : ('a -> bool) -> 'a t -> bool -``` -`exists f a` is `true` if some element of `a` satisfies `f`. - -For example, if the elements of `a` are `x0`, `x1`, `x2`, then `exists f a` is `f x0 || f x1 || f x2`. - -``` -val for_all : ('a -> bool) -> 'a t -> bool -``` -`for_all f a` is `true` if all elements of `a` satisfy `f`. This includes the case where `a` is empty. - -For example, if the elements of `a` are `x0`, `x1`, then `exists f a` is `f x0 && f x1 && f x2`. - -``` -val mem : 'a -> 'a t -> bool -``` -`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). - -since 5.3 -``` -val memq : 'a -> 'a t -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. - -since 5.3 -``` -val find_opt : ('a -> bool) -> 'a t -> 'a option -``` -`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. - -since 5.3 -``` -val find_index : ('a -> bool) -> 'a t -> int option -``` -`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.3 -``` -val find_map : ('a -> 'b option) -> 'a t -> 'b option -``` -`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 5.3 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.3 - -## Comparison functions - -Comparison functions iterate over their arguments; it is a programming error to change their length during the iteration, see the [Iteration](./#iteration) section above. - -``` -val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal eq a b` holds when `a` and `b` have the same length, and for all indices `i` we have `eq (get a i) (get b i)`. - -since 5.3 -``` -val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Provided the function `cmp` defines a preorder on elements, `compare cmp a b` compares first `a` and `b` by their length, and then, if equal, by their elements according to the lexicographic preorder. - -For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). - -since 5.3 - -## Conversions to other data structures - -Note: the `of_*` functions raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). - -The `to_*` functions, except those specifically marked "reentrant", iterate on their dynarray argument. In particular it is a programming error if the length of the dynarray changes during their execution, and the conversion functions raise `Invalid_argument` if they observe such a change. - -``` -val of_array : 'a array -> 'a t -``` -`of_array arr` returns a dynamic array corresponding to the fixed-sized array `a`. Operates in `O(n)` time by making a copy. - -``` -val to_array : 'a t -> 'a array -``` -`to_array a` returns a fixed-sized array corresponding to the dynamic array `a`. This always allocate a new array and copies elements into it. - -``` -val of_list : 'a list -> 'a t -``` -`of_list l` is the array containing the elements of `l` in the same order. - -``` -val to_list : 'a t -> 'a list -``` -`to_list a` is a list with the elements contained in the array `a`. - -``` -val of_seq : 'a Seq.t -> 'a t -``` -`of_seq seq` is an array containing the same elements as `seq`. - -It traverses `seq` once and will terminate only if `seq` is finite. - -``` -val to_seq : 'a t -> 'a Seq.t -``` -`to_seq a` is the sequence of elements `get a 0`, `get a 1`... `get a (length a - 1)`. - -``` -val to_seq_reentrant : 'a t -> 'a Seq.t -``` -`to_seq_reentrant a` is a reentrant variant of [`to_seq`](./#val-to_seq), in the sense that one may still access its elements after the length of `a` has changed. - -Demanding the `i`\-th element of the resulting sequence (which can happen zero, one or several times) will access the `i`\-th element of `a` at the time of the demand. The sequence stops if `a` has less than `i` elements at this point. - -``` -val to_seq_rev : 'a t -> 'a Seq.t -``` -`to_seq_rev a` is the sequence of elements `get a (l - 1)`, `get a (l - 2)`... `get a 0`, where `l` is `length a` at the time `to_seq_rev` is invoked. - -``` -val to_seq_rev_reentrant : 'a t -> 'a Seq.t -``` -`to_seq_rev_reentrant a` is a reentrant variant of [`to_seq_rev`](./#val-to_seq_rev), in the sense that one may still access its elements after the length of `a` has changed. - -Elements that have been removed from the array by the time they are demanded in the sequence are skipped. - - -## Advanced topics for performance - - -### Backing array, capacity - -Internally, a dynamic array uses a **backing array** (a fixed-size array as provided by the [`Array`](./Stdlib-Array.md) module) whose length is greater or equal to the length of the dynamic array. We define the **capacity** of a dynamic array as the length of its backing array. - -The capacity of a dynamic array is relevant in advanced scenarios, when reasoning about the performance of dynamic array programs: - -- The memory usage of a dynamic array is proportional to its capacity, rather than its length. -- When there is no empty space left at the end of the backing array, adding elements requires allocating a new, larger backing array. -The implementation uses a standard exponential reallocation strategy which guarantees amortized constant-time operation; in particular, the total capacity of all backing arrays allocated over the lifetime of a dynamic array is at worst proportional to the total number of elements added. - -In other words, users need not care about capacity and reallocations, and they will get reasonable behavior by default. However, in some performance-sensitive scenarios the functions below can help control memory usage or guarantee an optimal number of reallocations. - -``` -val capacity : 'a t -> int -``` -`capacity a` is the length of `a`'s backing array. - -``` -val ensure_capacity : 'a t -> int -> unit -``` -`ensure_capacity a n` makes sure that the capacity of `a` is at least `n`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the requested capacity is outside the range 0 .. Sys.max\_array\_length. -An example would be to reimplement [`of_array`](./#val-of_array) without using [`init`](./#val-init): - -```ocaml -let of_array arr = - let a = Dynarray.create () in - Dynarray.ensure_capacity a (Array.length arr); - Array.iter (fun v -> add_last a v) arr -``` -Using `ensure_capacity` guarantees that at most one reallocation will take place, instead of possibly several. - -Without this `ensure_capacity` hint, the number of resizes would be logarithmic in the length of `arr`, creating a constant-factor slowdown noticeable when `arr` is large. - -``` -val ensure_extra_capacity : 'a t -> int -> unit -``` -`ensure_extra_capacity a n` is `ensure_capacity a (length a + n)`, it makes sure that `a` has room for `n` extra items. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the total requested capacity is outside the range 0 .. Sys.max\_array\_length. -A use case would be to implement [`append_array`](./#val-append_array): - -```ocaml -let append_array a arr = - ensure_extra_capacity a (Array.length arr); - Array.iter (fun v -> add_last a v) arr -``` -``` -val fit_capacity : 'a t -> unit -``` -`fit_capacity a` reallocates a backing array if necessary, so that the resulting capacity is exactly `length a`, with no additional empty space at the end. This can be useful to make sure there is no memory wasted on a long-lived array. - -Note that calling `fit_capacity` breaks the amortized complexity guarantees provided by the default reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. - -If you know that a dynamic array has reached its final length, which will remain fixed in the future, it is sufficient to call `to_array` and only keep the resulting fixed-size array. `fit_capacity` is useful when you need to keep a dynamic array for eventual future resizes. - -``` -val set_capacity : 'a t -> int -> unit -``` -`set_capacity a n` reallocates a backing array if necessary, so that the resulting capacity is exactly `n`. In particular, all elements of index `n` or greater are removed. - -Like [`fit_capacity`](./#val-fit_capacity), this function breaks the amortized complexity guarantees provided by the reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. - -This is an advanced function; in particular, [`ensure_capacity`](./#val-ensure_capacity) should be preferred to increase the capacity, as it preserves those amortized guarantees. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. -``` -val reset : 'a t -> unit -``` -`reset a` clears `a` and replaces its backing array by an empty array. - -It is equivalent to `set_capacity a 0` or `clear a; fit_capacity a`. - - -### No leaks: preservation of memory liveness - -The user-provided values reachable from a dynamic array `a` are exactly the elements in the indices `0` to `length a - 1`. In particular, no user-provided values are "leaked" by being present in the backing array at index `length a` or later. - - -## Code examples - - -### Min-heaps for mutable priority queues - -We can use dynamic arrays to implement a mutable priority queue. A priority queue provides a function to add elements, and a function to extract the minimum element \-- according to some comparison function. - -```ocaml -(* We present our priority queues as a functor - parametrized on the comparison function. *) -module Heap (Elem : Map.OrderedType) : sig - type t - val create : unit -> t - val add : t -> Elem.t -> unit - val pop_min : t -> Elem.t option -end = struct - - (* Our priority queues are implemented using the standard "min heap" - data structure, a dynamic array representing a binary tree. *) - type t = Elem.t Dynarray.t - let create = Dynarray.create - - (* The node of index [i] has as children the nodes of index [2 * i + 1] - and [2 * i + 2] -- if they are valid indices in the dynarray. *) - let left_child i = 2 * i + 1 - let right_child i = 2 * i + 2 - let parent_node i = (i - 1) / 2 - - (* We use indexing operators for convenient notations. *) - let ( .!() ) = Dynarray.get - let ( .!()<- ) = Dynarray.set - - (* Auxiliary functions to compare and swap two elements - in the dynamic array. *) - let order h i j = - Elem.compare h.!(i) h.!(j) - - let swap h i j = - let v = h.!(i) in - h.!(i) <- h.!(j); - h.!(j) <- v - - (* We say that a heap respects the "heap ordering" if the value of - each node is smaller than the value of its children. The - algorithm manipulates arrays that respect the heap algorithm, - except for one node whose value may be too small or too large. - - The auxiliary functions [heap_up] and [heap_down] take - such a misplaced value, and move it "up" (respectively: "down") - the tree by permuting it with its parent value (respectively: - a child value) until the heap ordering is restored. *) - - let rec heap_up h i = - if i = 0 then () else - let parent = parent_node i in - if order h i parent < 0 then - (swap h i parent; heap_up h parent) - - and heap_down h ~len i = - let left, right = left_child i, right_child i in - if left >= len then () (* no child, stop *) else - let smallest = - if right >= len then left (* no right child *) else - if order h left right < 0 then left else right - in - if order h i smallest > 0 then - (swap h i smallest; heap_down h ~len smallest) - - let add h s = - let i = Dynarray.length h in - Dynarray.add_last h s; - heap_up h i - - let pop_min h = - if Dynarray.is_empty h then None - else begin - (* Standard trick: swap the 'best' value at index 0 - with the last value of the array. *) - let last = Dynarray.length h - 1 in - swap h 0 last; - (* At this point [pop_last] returns the 'best' value, - and leaves a heap with one misplaced element at index [0]. *) - let best = Dynarray.pop_last h in - (* Restore the heap ordering -- does nothing if the heap is empty. *) - heap_down h ~len:last 0; - Some best - end -end -``` -The production code from which this example was inspired includes logic to free the backing array when the heap becomes empty, only in the case where the capacity is above a certain threshold. This can be done by calling the following function from `pop`: - -```ocaml -let shrink h = - if Dynarray.length h = 0 && Dynarray.capacity h > 1 lsl 18 then - Dynarray.reset h -``` -The `Heap` functor can be used to implement a sorting function, by adding all elements into a priority queue and then extracting them in order. - -```ocaml -let heap_sort (type a) cmp li = - let module Heap = Heap(struct type t = a let compare = cmp end) in - let heap = Heap.create () in - List.iter (Heap.add heap) li; - List.map (fun _ -> Heap.pop_min heap |> Option.get) li -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Either.md b/docs/api/ml/melange/Stdlib-Either.md deleted file mode 100644 index 444260295..000000000 --- a/docs/api/ml/melange/Stdlib-Either.md +++ /dev/null @@ -1,115 +0,0 @@ - -# Module `Stdlib.Either` - -Either type. - -Either is the simplest and most generic sum/variant type: a value of `('a, 'b) Either.t` is either a `Left (v : 'a)` or a `Right (v : 'b)`. - -It is a natural choice in the API of generic functions where values could fall in two different cases, possibly at different types, without assigning a specific meaning to what each case should be. - -For example: - -```ocaml -List.partition_map: - ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list -``` -If you are looking for a parametrized type where one alternative means success and the other means failure, you should use the more specific type [`Result.t`](./Stdlib-Result.md#type-t). - -since 4.12 -``` -type ('a, 'b) t = -``` -``` -| Left of 'a -``` -``` -| Right of 'b -``` -``` - -``` -A value of `('a, 'b) Either.t` contains either a value of `'a` or a value of `'b` - -``` -val left : 'a -> ('a, 'b) t -``` -`left v` is `Left v`. - -``` -val right : 'b -> ('a, 'b) t -``` -`right v` is `Right v`. - -``` -val is_left : ('a, 'b) t -> bool -``` -`is_left (Left v)` is `true`, `is_left (Right v)` is `false`. - -``` -val is_right : ('a, 'b) t -> bool -``` -`is_right (Left v)` is `false`, `is_right (Right v)` is `true`. - -``` -val find_left : ('a, 'b) t -> 'a option -``` -`find_left (Left v)` is `Some v`, `find_left (Right _)` is `None` - -``` -val find_right : ('a, 'b) t -> 'b option -``` -`find_right (Right v)` is `Some v`, `find_right (Left _)` is `None` - -``` -val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t -``` -`map_left f e` is `Left (f v)` if `e` is `Left v` and `e` if `e` is `Right _`. - -``` -val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t -``` -`map_right f e` is `Right (f v)` if `e` is `Right v` and `e` if `e` is `Left _`. - -``` -val map : - left:('a1 -> 'a2) -> - right:('b1 -> 'b2) -> - ('a1, 'b1) t -> - ('a2, 'b2) t -``` -`map ~left ~right (Left v)` is `Left (left v)`, `map ~left ~right (Right v)` is `Right (right v)`. - -``` -val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c -``` -`fold ~left ~right (Left v)` is `left v`, and `fold ~left ~right (Right v)` is `right v`. - -``` -val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit -``` -`iter ~left ~right (Left v)` is `left v`, and `iter ~left ~right (Right v)` is `right v`. - -``` -val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool -``` -`for_all ~left ~right (Left v)` is `left v`, and `for_all ~left ~right (Right v)` is `right v`. - -``` -val equal : - left:('a -> 'a -> bool) -> - right:('b -> 'b -> bool) -> - ('a, 'b) t -> - ('a, 'b) t -> - bool -``` -`equal ~left ~right e0 e1` tests equality of `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. - -``` -val compare : - left:('a -> 'a -> int) -> - right:('b -> 'b -> int) -> - ('a, 'b) t -> - ('a, 'b) t -> - int -``` -`compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _ ` and `Right _`. `Left _` values are smaller than `Right _` values. diff --git a/docs/api/ml/melange/Stdlib-Filename.md b/docs/api/ml/melange/Stdlib-Filename.md deleted file mode 100644 index f56fdfaec..000000000 --- a/docs/api/ml/melange/Stdlib-Filename.md +++ /dev/null @@ -1,167 +0,0 @@ - -# Module `Stdlib.Filename` - -Operations on file names. - -``` -val current_dir_name : string -``` -The conventional name for the current directory (e.g. `.` in Unix). - -``` -val parent_dir_name : string -``` -The conventional name for the parent of the current directory (e.g. `..` in Unix). - -``` -val dir_sep : string -``` -The directory separator (e.g. `/` in Unix). - -since 3.11.2 -``` -val concat : string -> string -> string -``` -`concat dir file` returns a file name that designates file `file` in directory `dir`. - -``` -val is_relative : string -> bool -``` -Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. in Unix, starts with `/`). - -``` -val is_implicit : string -> bool -``` -Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory. - -``` -val check_suffix : string -> string -> bool -``` -`check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`. - -Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. - -``` -val chop_suffix : string -> string -> string -``` -`chop_suffix name suff` removes the suffix `suff` from the filename `name`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if name does not end with the suffix suff. -``` -val chop_suffix_opt : suffix:string -> string -> string option -``` -`chop_suffix_opt ~suffix filename` removes the suffix from the `filename` if possible, or returns `None` if the filename does not end with the suffix. - -Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. - -since 4.08 -``` -val extension : string -> string -``` -`extension name` is the shortest suffix `ext` of `name0` where: - -- `name0` is the longest suffix of `name` that does not contain a directory separator; -- `ext` starts with a period; -- `ext` is preceded by at least one non-period character in `name0`. -If such a suffix does not exist, `extension name` is the empty string. - -since 4.04 -``` -val remove_extension : string -> string -``` -Return the given file name without its extension, as defined in [`Filename.extension`](./#val-extension). If the extension is empty, the function returns the given file name. - -The following invariant holds for any file name `s`: - -`remove_extension s ^ extension s = s` - -since 4.04 -``` -val chop_extension : string -> string -``` -Same as [`Filename.remove_extension`](./#val-remove_extension), but raise `Invalid_argument` if the given name has an empty extension. - -``` -val basename : string -> string -``` -Split a file name into directory name / base file name. If `name` is a valid file name, then `concat (dirname name) (basename name)` returns a file name which is equivalent to `name`. Moreover, after setting the current directory to `dirname name` (with [`Sys.chdir`](./Stdlib-Sys.md#val-chdir)), references to `basename name` (which is a relative file name) designate the same file as `name` before the call to [`Sys.chdir`](./Stdlib-Sys.md#val-chdir). - -This function conforms to the specification of POSIX.1-2008 for the `basename` utility. - -``` -val dirname : string -> string -``` -See [`Filename.basename`](./#val-basename). This function conforms to the specification of POSIX.1-2008 for the `dirname` utility. - -``` -val null : string -``` -`null` is `"/dev/null"` on POSIX and `"NUL"` on Windows. It represents a file on the OS that discards all writes and returns end of file on reads. - -since 4.10 -``` -val temp_file : ?temp_dir:string -> string -> string -> string -``` -`temp_file prefix suffix` returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary file is created empty, with permissions `0o600` (readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when `temp_file` was called. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be created. -before 3.11.2 no ?temp\_dir optional argument -``` -val open_temp_file : - ?mode:open_flag list -> - ?perms:int -> - ?temp_dir:string -> - string -> - string -> - string * out_channel -``` -Same as [`Filename.temp_file`](./#val-temp_file), but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than `temp_file`: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument `mode` is a list of additional flags to control the opening of the file. It can contain one or several of `Open_append`, `Open_binary`, and `Open_text`. The default is `[Open_text]` (open in text mode). The file is created with permissions `perms` (defaults to readable and writable only by the file owner, `0o600`). - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be opened. -before 4.03 no ?perms optional argument -before 3.11.2 no ?temp\_dir optional argument -``` -val temp_dir : ?temp_dir:string -> ?perms:int -> string -> string -> string -``` -`temp_dir prefix suffix` creates and returns the name of a fresh temporary directory with permissions `perms` (defaults to 0o700) inside `temp_dir`. The base name of the temporary directory is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary directory is created empty, with permissions `0o700` (readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when `temp_dir` was called. - -If temp\_dir does not exist, this function does not create it. Instead, it raises Sys\_error. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the directory could not be created. -since 5.1 -``` -val get_temp_dir_name : unit -> string -``` -The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the `TEMP` environment variable, or "." if the variable is not set. The temporary directory can be changed with [`Filename.set_temp_dir_name`](./#val-set_temp_dir_name). - -since 4.00 -``` -val set_temp_dir_name : string -> unit -``` -Change the temporary directory returned by [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name) and used by [`Filename.temp_file`](./#val-temp_file) and [`Filename.open_temp_file`](./#val-open_temp_file). The temporary directory is a domain-local value which is inherited by child domains. - -since 4.00 -``` -val quote : string -> string -``` -Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions. - -``` -val quote_command : - string -> - ?stdin:string -> - ?stdout:string -> - ?stderr:string -> - string list -> - string -``` -`quote_command cmd args` returns a quoted command line, suitable for use as an argument to [`Sys.command`](./Stdlib-Sys.md#val-command), `Unix.system`, and the `Unix.open_process` functions. - -The string `cmd` is the command to call. The list `args` is the list of arguments to pass to this command. It can be empty. - -The optional arguments `?stdin` and `?stdout` and `?stderr` are file names used to redirect the standard input, the standard output, or the standard error of the command. If `~stdin:f` is given, a redirection `< f` is performed and the standard input of the command reads from file `f`. If `~stdout:f` is given, a redirection `> f` is performed and the standard output of the command is written to file `f`. If `~stderr:f` is given, a redirection `2> f` is performed and the standard error of the command is written to file `f`. If both `~stdout:f` and `~stderr:f` are given, with the exact same file name `f`, a `2>&1` redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file `f`. - -Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using [`Filename.quote`](./#val-quote), then concatenated. Under Win32, additional quoting is performed as required by the `cmd.exe` shell that is called by [`Sys.command`](./Stdlib-Sys.md#val-command). - -raises [`Failure`](./Stdlib.md#exception-Failure) if the command cannot be escaped on the current platform. -since 4.10 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Float-Array.md b/docs/api/ml/melange/Stdlib-Float-Array.md deleted file mode 100644 index 99c3234de..000000000 --- a/docs/api/ml/melange/Stdlib-Float-Array.md +++ /dev/null @@ -1,330 +0,0 @@ - -# Module `Float.Array` - -Float arrays with packed representation. - -``` -type t = floatarray -``` -The type of float arrays with packed representation. - -since 4.08 -``` -val length : t -> int -``` -Return the length (number of elements) of the given floatarray. - -``` -val get : t -> int -> float -``` -`get a n` returns the element number `n` of floatarray `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val set : t -> int -> float -> unit -``` -`set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val make : int -> float -> t -``` -`make n x` returns a fresh floatarray of length `n`, initialized with `x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. -``` -val create : int -> t -``` -`create n` returns a fresh floatarray of length `n`, with uninitialized data. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. -``` -val init : int -> (int -> float) -> t -``` -`init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers `0` to `n-1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. -``` -val make_matrix : int -> int -> float -> t array -``` -`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where all elements are initialized with `e`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. -since 5.2 -``` -val init_matrix : int -> int -> (int -> int -> float) -> t array -``` -`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. -since 5.2 -``` -val append : t -> t -> t -``` -`append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_floatarray\_length. -``` -val concat : t list -> t -``` -Same as [`append`](./#val-append), but concatenates a list of floatarrays. - -``` -val sub : t -> int -> int -> t -``` -`sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. -``` -val copy : t -> t -``` -`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`. - -``` -val fill : t -> int -> int -> float -> unit -``` -`fill a pos len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. -``` -val blit : t -> int -> t -> int -> int -> unit -``` -`blit src src_pos dst dst_pos len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. -``` -val to_list : t -> float list -``` -`to_list a` returns the list of all the elements of `a`. - -``` -val of_list : float list -> t -``` -`of_list l` returns a fresh floatarray containing the elements of `l`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_floatarray\_length. - -## Iterators - -``` -val iter : (float -> unit) -> t -> unit -``` -`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. - -``` -val iteri : (int -> float -> unit) -> t -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied with the index of the element as first argument, and the element itself as second argument. - -``` -val map : (float -> float) -> t -> t -``` -`map f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. - -``` -val map_inplace : (float -> float) -> t -> unit -``` -`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. - -since 5.1 -``` -val mapi : (int -> float -> float) -> t -> t -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val mapi_inplace : (int -> float -> float) -> t -> unit -``` -Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -since 5.1 -``` -val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc -``` -`fold_left f x init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`. - -``` -val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`. - - -## Iterators on two arrays - -``` -val iter2 : (float -> float -> unit) -> t -> t -> unit -``` -`Array.iter2 f a b` applies function `f` to all the elements of `a` and `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. -``` -val map2 : (float -> float -> float) -> t -> t -> t -``` -`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. - -## Array scanning - -``` -val for_all : (float -> bool) -> t -> bool -``` -`for_all f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. - -``` -val exists : (float -> bool) -> t -> bool -``` -`exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. - -``` -val mem : float -> t -> bool -``` -`mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`. - -``` -val mem_ieee : float -> t -> bool -``` -Same as [`mem`](./#val-mem), but uses IEEE equality instead of structural equality. - - -## Array searching - -``` -val find_opt : (float -> bool) -> t -> float option -``` -``` -val find_index : (float -> bool) -> t -> int option -``` -`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : (float -> 'a option) -> t -> 'a option -``` -``` -val find_mapi : (int -> float -> 'a option) -> t -> 'a option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 - -## Sorting and shuffling - -``` -val sort : (float -> float -> int) -> t -> unit -``` -Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. - -The current implementation uses Heap Sort. It runs in constant stack space. - -Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : - -- `cmp x y` \> 0 if and only if `cmp y x` \< 0 -- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 -When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : - -- `cmp a.(i) a.(j)` \>= 0 if i \>= j -``` -val stable_sort : (float -> float -> int) -> t -> unit -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. - -The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of [`sort`](./#val-sort). - -``` -val fast_sort : (float -> float -> int) -> t -> unit -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val shuffle : rand:(int -> int) -> t -> unit -``` -`shuffle rand a` randomly permutes `a`'s elements using `rand` for randomness. The distribution of permutations is uniform. - -`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). - -since 5.2 - -## Float arrays and Sequences - -``` -val to_seq : t -> float Seq.t -``` -Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence. - -``` -val to_seqi : t -> (int * float) Seq.t -``` -Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence. - -``` -val of_seq : float Seq.t -> t -``` -Create an array from the generator. - -``` -val map_to_array : (float -> 'a) -> t -> 'a array -``` -`map_to_array f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. - -``` -val map_from_array : ('a -> float) -> 'a array -> t -``` -`map_from_array f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. - - -## Arrays and concurrency safety - -Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let a = Float.Array.make size 1. -let update a f () = - Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a -let d1 = Domain.spawn (update a (fun x -> x +. 1.)) -let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.)) -let () = Domain.join d1; Domain.join d2 -``` -After executing this code, each field of the float array `a` is either `2.`, `3.`, `4.` or `5.`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions. - - -### Tearing - -Float arrays have two supplementary caveats in the presence of data races. - -First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. - -For instance, at the end of - -```ocaml -let zeros = Float.Array.make size 0. -let max_floats = Float.Array.make size Float.max_float -let res = Float.Array.copy zeros -let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size) -let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size) -let () = Domain.join d1; Domain.join d2 -``` -the `res` float array might contain values that are neither `0.` nor `max_float`. - -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/ml/melange/Stdlib-Float.md b/docs/api/ml/melange/Stdlib-Float.md deleted file mode 100644 index 29ecfd718..000000000 --- a/docs/api/ml/melange/Stdlib-Float.md +++ /dev/null @@ -1,482 +0,0 @@ - -# Module `Stdlib.Float` - -Floating-point arithmetic. - -OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... - -since 4.07 -``` -val zero : float -``` -The floating point 0. - -since 4.08 -``` -val one : float -``` -The floating-point 1\. - -since 4.08 -``` -val minus_one : float -``` -The floating-point \-1. - -since 4.08 -``` -val neg : float -> float -``` -Unary negation. - -``` -val add : float -> float -> float -``` -Floating-point addition. - -``` -val sub : float -> float -> float -``` -Floating-point subtraction. - -``` -val mul : float -> float -> float -``` -Floating-point multiplication. - -``` -val div : float -> float -> float -``` -Floating-point division. - -``` -val fma : float -> float -> float -> float -``` -`fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation. - -On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters. - -since 4.08 -``` -val rem : float -> float -> float -``` -`rem a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. - -``` -val succ : float -> float -``` -`succ x` returns the floating point number right after `x` i.e., the smallest floating-point number greater than `x`. See also [`next_after`](./#val-next_after). - -since 4.08 -``` -val pred : float -> float -``` -`pred x` returns the floating-point number right before `x` i.e., the greatest floating-point number smaller than `x`. See also [`next_after`](./#val-next_after). - -since 4.08 -``` -val abs : float -> float -``` -`abs f` returns the absolute value of `f`. - -``` -val infinity : float -``` -Positive infinity. - -``` -val neg_infinity : float -``` -Negative infinity. - -``` -val nan : float -``` -A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. Stands for 'not a number'. Any floating-point operation with `nan` as argument returns `nan` as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, `=`, `<`, `<=`, `>` and `>=` return `false` and `<>` returns `true` if one or both of their arguments is `nan`. - -`nan` is `quiet_nan` since 5.1; it was a signaling NaN before. - -``` -val signaling_nan : float -``` -Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries. - -since 5.1 -``` -val quiet_nan : float -``` -Quiet NaN. - -since 5.1 -``` -val pi : float -``` -The constant pi. - -``` -val max_float : float -``` -The largest positive finite value of type `float`. - -``` -val min_float : float -``` -The smallest positive, non-zero, non-denormalized value of type `float`. - -``` -val epsilon : float -``` -The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. - -``` -val is_finite : float -> bool -``` -`is_finite x` is `true` if and only if `x` is finite i.e., not infinite and not [`nan`](./#val-nan). - -since 4.08 -``` -val is_infinite : float -> bool -``` -`is_infinite x` is `true` if and only if `x` is [`infinity`](./#val-infinity) or [`neg_infinity`](./#val-neg_infinity). - -since 4.08 -``` -val is_nan : float -> bool -``` -`is_nan x` is `true` if and only if `x` is not a number (see [`nan`](./#val-nan)). - -since 4.08 -``` -val is_integer : float -> bool -``` -`is_integer x` is `true` if and only if `x` is an integer. - -since 4.08 -``` -val of_int : int -> float -``` -Convert an integer to floating-point. - -``` -val to_int : float -> int -``` -Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. - -``` -val of_string : string -> float -``` -Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The `_` (underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of a float. -``` -val of_string_opt : string -> float option -``` -Same as `of_string`, but returns `None` instead of raising. - -``` -val to_string : float -> string -``` -Return a string representation of a floating-point number. - -This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). - -This function is an alias for [`Stdlib.string_of_float`](./Stdlib.md#val-string_of_float). - -``` -type fpclass = fpclass = -``` -``` -| FP_normal -``` -Normal number, none of the below - -``` -| FP_subnormal -``` -Number very close to 0.0, has reduced precision - -``` -| FP_zero -``` -Number is 0.0 or \-0.0 - -``` -| FP_infinite -``` -Number is positive or negative infinity - -``` -| FP_nan -``` -Not a number: result of an undefined operation - -``` - -``` -The five classes of floating-point numbers, as determined by the [`classify_float`](./#val-classify_float) function. - -``` -val classify_float : float -> fpclass -``` -Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number. - -``` -val pow : float -> float -> float -``` -Exponentiation. - -``` -val sqrt : float -> float -``` -Square root. - -``` -val cbrt : float -> float -``` -Cube root. - -since 4.13 -``` -val exp : float -> float -``` -Exponential. - -``` -val exp2 : float -> float -``` -Base 2 exponential function. - -since 4.13 -``` -val log : float -> float -``` -Natural logarithm. - -``` -val log10 : float -> float -``` -Base 10 logarithm. - -``` -val log2 : float -> float -``` -Base 2 logarithm. - -since 4.13 -``` -val expm1 : float -> float -``` -`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. - -``` -val log1p : float -> float -``` -`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. - -``` -val cos : float -> float -``` -Cosine. Argument is in radians. - -``` -val sin : float -> float -``` -Sine. Argument is in radians. - -``` -val tan : float -> float -``` -Tangent. Argument is in radians. - -``` -val acos : float -> float -``` -Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. - -``` -val asin : float -> float -``` -Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan : float -> float -``` -Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan2 : float -> float -> float -``` -`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. - -``` -val hypot : float -> float -> float -``` -`hypot x y` returns `sqrt(x *. x +. y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. If one of `x` or `y` is infinite, returns `infinity` even if the other is `nan`. - -``` -val cosh : float -> float -``` -Hyperbolic cosine. Argument is in radians. - -``` -val sinh : float -> float -``` -Hyperbolic sine. Argument is in radians. - -``` -val tanh : float -> float -``` -Hyperbolic tangent. Argument is in radians. - -``` -val acosh : float -> float -``` -Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. - -since 4.13 -``` -val asinh : float -> float -``` -Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. - -since 4.13 -``` -val atanh : float -> float -``` -Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. - -since 4.13 -``` -val erf : float -> float -``` -Error function. The argument ranges over the entire real line. The result is always within `[-1.0, 1.0]`. - -since 4.13 -``` -val erfc : float -> float -``` -Complementary error function (`erfc x = 1 - erf x`). The argument ranges over the entire real line. The result is always within `[0.0, 2.0]`. - -since 4.13 -``` -val trunc : float -> float -``` -`trunc x` rounds `x` to the nearest integer whose absolute value is less than or equal to `x`. - -since 4.08 -``` -val round : float -> float -``` -`round x` rounds `x` to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If `x` is an integer, `+0.`, `-0.`, `nan`, or infinite, `x` itself is returned. - -On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform. - -since 4.08 -``` -val ceil : float -> float -``` -Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. - -``` -val floor : float -> float -``` -Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. - -``` -val next_after : float -> float -> float -``` -`next_after x y` returns the next representable floating-point value following `x` in the direction of `y`. More precisely, if `y` is greater (resp. less) than `x`, it returns the smallest (resp. largest) representable number greater (resp. less) than `x`. If `x` equals `y`, the function returns `y`. If `x` or `y` is `nan`, a `nan` is returned. Note that `next_after max_float infinity = infinity` and that `next_after 0. infinity` is the smallest denormalized positive number. If `x` is the smallest denormalized positive number, `next_after x 0. = 0.` - -since 4.08 -``` -val copy_sign : float -> float -> float -``` -`copy_sign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. - -``` -val sign_bit : float -> bool -``` -`sign_bit x` is `true` if and only if the sign bit of `x` is set. For example `sign_bit 1.` and `signbit 0.` are `false` while `sign_bit (-1.)` and `sign_bit (-0.)` are `true`. - -since 4.08 -``` -val frexp : float -> float * int -``` -`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. - -``` -val ldexp : float -> int -> float -``` -`ldexp x n` returns `x *. 2 ** n`. - -``` -val modf : float -> float * float -``` -`modf f` returns the pair of the fractional and integral part of `f`. - -``` -type t = float -``` -An alias for the type of floating-point numbers. - -``` -val compare : t -> t -> int -``` -`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. - -``` -val equal : t -> t -> bool -``` -The equal function for floating-point numbers, compared using [`compare`](./#val-compare). - -``` -val min : t -> t -> t -``` -`min x y` returns the minimum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `min (-0.) (+0.) = -0.` - -since 4.08 -``` -val max : float -> float -> float -``` -`max x y` returns the maximum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `max (-0.) (+0.) = +0.` - -since 4.08 -``` -val min_max : float -> float -> float * float -``` -`min_max x y` is `(min x y, max x y)`, just more efficient. - -since 4.08 -``` -val min_num : t -> t -> t -``` -`min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `min_num (-0.) (+0.) = -0.` - -since 4.08 -``` -val max_num : t -> t -> t -``` -`max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan` `nan` is returned. Moreover `max_num (-0.) (+0.) = +0.` - -since 4.08 -``` -val min_max_num : float -> float -> float * float -``` -`min_max_num x y` is `(min_num x y, max_num x y)`, just more efficient. Note that in particular `min_max_num x nan = (x, x)` and `min_max_num nan y = (y, y)`. - -since 4.08 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for floats, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for floats, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -``` -module Array : sig ... end -``` -Float arrays with packed representation. diff --git a/docs/api/ml/melange/Stdlib-Format.md b/docs/api/ml/melange/Stdlib-Format.md deleted file mode 100644 index 92440e239..000000000 --- a/docs/api/ml/melange/Stdlib-Format.md +++ /dev/null @@ -1,1401 +0,0 @@ - -# Module `Stdlib.Format` - -Pretty-printing. - -If you are new to this module, see the [examples](./#examples) below. - -This module implements a pretty-printing facility to format values within ['pretty-printing boxes'](./#boxes) and ['semantic tags'](./#tags) combined with a set of [printf-like functions](./#fpp). The pretty-printer splits lines at specified [break hints](./#breaks), and indents lines according to the box structure. Similarly, [semantic tags](./#tags) can be used to decouple text presentation from its contents. - -This pretty-printing facility is implemented as an overlay on top of abstract [formatters](./#formatter) which provide basic output functions. Some formatters are predefined, notably: - -- [`std_formatter`](./#val-std_formatter) outputs to [stdout](./Stdlib.md#val-stdout) -- [`err_formatter`](./#val-err_formatter) outputs to [stderr](./Stdlib.md#val-stderr) -Most functions in the [`Format`](#) module come in two variants: a short version that operates on the current domain's standard formatter as obtained using [`get_std_formatter`](./#val-get_std_formatter) and the generic version prefixed by `pp_` that takes a formatter as its first argument. For the version that operates on the current domain's standard formatter, the call to [`get_std_formatter`](./#val-get_std_formatter) is delayed until the last argument is received. - -More formatters can be created with [`formatter_of_out_channel`](./#val-formatter_of_out_channel), [`formatter_of_buffer`](./#val-formatter_of_buffer), [`formatter_of_symbolic_output_buffer`](./#val-formatter_of_symbolic_output_buffer) or using [custom formatters](./#formatter). - -**Warning**: Since [formatters](./#formatter) contain mutable state, it is not thread-safe to use the same formatter on multiple domains in parallel without synchronization. - -If multiple domains write to the same output channel using the predefined formatters (as obtained by [`get_std_formatter`](./#val-get_std_formatter) or [`get_err_formatter`](./#val-get_err_formatter)), the output from the domains will be interleaved with each other at points where the formatters are flushed, such as with [`print_flush`](./#val-print_flush). This synchronization is not performed by formatters obtained from [`formatter_of_out_channel`](./#val-formatter_of_out_channel) (on the standard out channels or others). - - -## Introduction - -You may consider this module as providing an extension to the `printf` facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular `printf` format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function [`Format.fprintf`](./#val-fprintf). - -You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise `fprintf` format strings. - -For instance, the sequence `open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()` that prints `x = 1` within a pretty-printing box, can be abbreviated as `printf "@[%s@ %i@]@." "x =" 1`, or even shorter `printf "@[x =@ %i@]@." 1`. - -Rule of thumb for casual users of this library: - -- use simple pretty-printing boxes (as obtained by `open_box 0`); -- use simple break hints as obtained by `print_cut ()` that outputs a simple break hint, or by `print_space ()` that outputs a space indicating a break hint; -- once a pretty-printing box is open, display its material with basic printing functions (e. g. `print_int` and `print_string`); -- when the material for a pretty-printing box has been printed, call `close_box ()` to close the box; -- at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate `print_newline ()`. -The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the `open_` functions below must be closed using `close_box` for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. - -In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer. - -Warning: mixing calls to pretty-printing functions of this module with calls to [`Stdlib`](./Stdlib.md) low level output functions is error prone. - -The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, ` Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT"; ` leads to output `<>PRETTYTEXT`. - - -## Formatters - -``` -type formatter -``` -Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also [Defining formatters](./#formatter). - - -## Pretty-printing boxes - -The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer. - -Each different pretty-printing box kind introduces a specific line splitting policy: - -- within an *horizontal* box, break hints never split the line (but the line may be split in a box nested deeper), -- within a *vertical* box, break hints always split the line, -- within an *horizontal/vertical* box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line, -- within a *compacting* box, a break hint never splits the line, unless there is no more room on the current line. -Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line. - -Moreover, opening a box after the [maximum indentation limit](./#maxindent) splits the line whether or not the box would end up fitting on the line. - -``` -val pp_open_box : formatter -> int -> unit -``` -``` -val open_box : int -> unit -``` -`pp_open_box ppf d` opens a new compacting pretty-printing box with offset `d` in the formatter `ppf`. - -Within this box, the pretty-printer prints as much as possible material on every line. - -A break hint splits the line if there is no more room on the line to print the remainder of the box. - -Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting \``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line). - -This box is the general purpose pretty-printing box. - -If the pretty-printer splits the line in the box, offset `d` is added to the current indentation. - -``` -val pp_close_box : formatter -> unit -> unit -``` -``` -val close_box : unit -> unit -``` -Closes the most recently open pretty-printing box. - -``` -val pp_open_hbox : formatter -> unit -> unit -``` -``` -val open_hbox : unit -> unit -``` -`pp_open_hbox ppf ()` opens a new 'horizontal' pretty-printing box. - -This box prints material on a single line. - -Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper). - -``` -val pp_open_vbox : formatter -> int -> unit -``` -``` -val open_vbox : int -> unit -``` -`pp_open_vbox ppf d` opens a new 'vertical' pretty-printing box with offset `d`. - -This box prints material on as many lines as break hints in the box. - -Every break hint in a vertical box splits the line. - -If the pretty-printer splits the line in the box, `d` is added to the current indentation. - -``` -val pp_open_hvbox : formatter -> int -> unit -``` -``` -val open_hvbox : int -> unit -``` -`pp_open_hvbox ppf d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`. - -This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box. - -If the pretty-printer splits the line in the box, `d` is added to the current indentation. - -``` -val pp_open_hovbox : formatter -> int -> unit -``` -``` -val open_hovbox : int -> unit -``` -`pp_open_hovbox ppf d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`. - -This box prints material as much as possible on every line. - -A break hint splits the line if there is no more room on the line to print the remainder of the box. - -If the pretty-printer splits the line in the box, `d` is added to the current indentation. - - -## Formatting functions - -``` -val pp_print_string : formatter -> string -> unit -``` -``` -val print_string : string -> unit -``` -`pp_print_string ppf s` prints `s` in the current pretty-printing box. - -``` -val pp_print_substring : pos:int -> len:int -> formatter -> string -> unit -``` -``` -val print_substring : pos:int -> len:int -> string -> unit -``` -`pp_print_substring ~pos ~len ppf s` prints the substring of `s` that starts at position `pos` and stops at position `pos+len` in the current pretty-printing box. - -since 5.3 -``` -val pp_print_bytes : formatter -> bytes -> unit -``` -``` -val print_bytes : bytes -> unit -``` -`pp_print_bytes ppf b` prints `b` in the current pretty-printing box. - -since 4.13 -``` -val pp_print_as : formatter -> int -> string -> unit -``` -``` -val print_as : int -> string -> unit -``` -`pp_print_as ppf len s` prints `s` in the current pretty-printing box. The pretty-printer formats `s` as if it were of length `len`. - -``` -val pp_print_substring_as : - pos:int -> - len:int -> - formatter -> - int -> - string -> - unit -``` -``` -val print_substring_as : pos:int -> len:int -> int -> string -> unit -``` -`pp_print_substring_as ~first ~len ppf len_as s` prints the substring of `s` that starts at position `pos` and stop at position `pos+len` in the current pretty-printing box as if it were of length `len_as`. - -since 5.1 -``` -val pp_print_int : formatter -> int -> unit -``` -``` -val print_int : int -> unit -``` -Print an integer in the current pretty-printing box. - -``` -val pp_print_float : formatter -> float -> unit -``` -``` -val print_float : float -> unit -``` -Print a floating point number in the current pretty-printing box. - -``` -val pp_print_char : formatter -> char -> unit -``` -``` -val print_char : char -> unit -``` -Print a character in the current pretty-printing box. - -``` -val pp_print_bool : formatter -> bool -> unit -``` -``` -val print_bool : bool -> unit -``` -Print a boolean in the current pretty-printing box. - -``` -val pp_print_nothing : formatter -> unit -> unit -``` -Print nothing. - -since 5.2 - -## Break hints - -A 'break hint' tells the pretty-printer to output some space or split the line whichever way is more appropriate to the current pretty-printing box splitting rules. - -Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items. - -Simple break hints are: - -- the 'space': output a space or split the line if appropriate, -- the 'cut': split the line if appropriate. -Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, \``output a space'' simply means printing a space character (ASCII code 32) and \``split the line'' means printing a newline character (ASCII code 10). - -``` -val pp_print_space : formatter -> unit -> unit -``` -``` -val print_space : unit -> unit -``` -`pp_print_space ppf ()` emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space. - -`pp_print_space ppf ()` is equivalent to `pp_print_break ppf 1 0`. - -``` -val pp_print_cut : formatter -> unit -> unit -``` -``` -val print_cut : unit -> unit -``` -`pp_print_cut ppf ()` emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing. - -`pp_print_cut ppf ()` is equivalent to `pp_print_break ppf 0 0`. - -``` -val pp_print_break : formatter -> int -> int -> unit -``` -``` -val print_break : int -> int -> unit -``` -`pp_print_break ppf nspaces offset` emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints `nspaces` spaces. - -If the pretty-printer splits the line, `offset` is added to the current indentation. - -``` -val pp_print_custom_break : - formatter -> - fits:(string * int * string) -> - breaks:(string * int * string) -> - unit -``` -`pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4)` emits a custom break hint: the pretty-printer may split the line at this point. - -If it does not split the line, then the `s1` is emitted, then `n` spaces, then `s2`. - -If it splits the line, then it emits the `s3` string, then an indent (according to the box rules), then an offset of `m` spaces, then the `s4` string. - -While `n` and `m` are handled by `formatter_out_functions.out_indent`, the strings will be handled by `formatter_out_functions.out_string`. This allows for a custom formatter that handles indentation distinctly, for example, outputs `
` tags or ` ` entities. - -The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list ` [a; b; c] `, you might want to add a trailing semicolon when it is printed vertically: - -```ocaml -[ - a; - b; - c; -] -``` -You can do this as follows: - -```ocaml -printf "@[[@;<0 2>@[a;@,b;@,c@]%t]@]@\n" - (pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, "")) -``` -since 4.08 -``` -val pp_force_newline : formatter -> unit -> unit -``` -``` -val force_newline : unit -> unit -``` -Force a new line in the current pretty-printing box. - -The pretty-printer must split the line at this point, - -Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative. - -``` -val pp_print_if_newline : formatter -> unit -> unit -``` -``` -val print_if_newline : unit -> unit -``` -Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. - - -## Pretty-printing termination - -``` -val pp_print_flush : formatter -> unit -> unit -``` -``` -val print_flush : unit -> unit -``` -End of pretty-printing: resets the pretty-printer to initial state. - -All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed. - -Note: never use `print_flush` in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering. - -Only consider using `print_flush` when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing. - -Warning: If the output device of the pretty-printer is an output channel, repeated calls to `print_flush` means repeated calls to [`Stdlib.flush`](./Stdlib.md#val-flush) to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency. - -``` -val pp_print_newline : formatter -> unit -> unit -``` -``` -val print_newline : unit -> unit -``` -End of pretty-printing: resets the pretty-printer to initial state. - -All open pretty-printing boxes are closed, all pending text is printed. - -Equivalent to [`print_flush`](./#val-print_flush) with a new line emitted on the pretty-printer low-level output device immediately before the device is flushed. See corresponding words of caution for [`print_flush`](./#val-print_flush). - -Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box. - - -## Margin - -``` -val pp_infinity : int -``` -`pp_infinity` is the maximal size of the margin. Its exact value is implementation dependent but is guaranteed to be greater than 109. - -since 5.2 -``` -val pp_set_margin : formatter -> int -> unit -``` -``` -val set_margin : int -> unit -``` -`pp_set_margin ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to `d` means that the formatting engine aims at printing at most `d-1` characters per line. Nothing happens if `d` is smaller than 2. If `d >= `[`pp_infinity`](./#val-pp_infinity), the right margin is set to [`pp_infinity`](./#val-pp_infinity)` - 1`. If `d` is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio `max_indent/margin>=50%` and if possible the current difference `margin - max_indent`. - -See also [`pp_set_geometry`](./#val-pp_set_geometry). - -``` -val pp_get_margin : formatter -> unit -> int -``` -``` -val get_margin : unit -> int -``` -Returns the position of the right margin. - - -## Maximum indentation limit - -``` -val pp_set_max_indent : formatter -> int -> unit -``` -``` -val set_max_indent : int -> unit -``` -`pp_set_max_indent ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration, - -```ocaml - set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." -``` -yields - -```ocaml - 123456 - 789A -``` -because the nested box `"@[7@]"` is opened after the maximum indentation limit (`7>5`) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line: - -```ocaml - printf "@[123456@[7@]89@]@." -``` -or opening an intermediary box before the maximum indentation limit which fits on the current line - -```ocaml - printf "@[123@[456@[7@]89@]A@]@." -``` -avoids the rejection to the left of the inner boxes and print respectively `"123456789"` and `"123456789A"` . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to `margin - 1`. Note that setting the maximum indentation limit to `margin` is invalid. - -Nothing happens if `d` is smaller than 2. - -If `d` is greater than the current margin, it is ignored, and the current maximum indentation limit is kept. - -See also [`pp_set_geometry`](./#val-pp_set_geometry). - -``` -val pp_get_max_indent : formatter -> unit -> int -``` -``` -val get_max_indent : unit -> int -``` -Return the maximum indentation limit (in characters). - - -## Geometry - -Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maximum indentation limit. - -``` -type geometry = { -``` -`max_indent : int;` -`margin : int;` -``` -} -``` -since 4.08 -``` -val check_geometry : geometry -> bool -``` -Check if the formatter geometry is valid: `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity) - -since 4.08 -``` -val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit -``` -``` -val set_geometry : max_indent:int -> margin:int -> unit -``` -``` -val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit -``` -``` -val safe_set_geometry : max_indent:int -> margin:int -> unit -``` -`pp_set_geometry ppf ~max_indent ~margin` sets both the margin and maximum indentation limit for `ppf`. - -When `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity), `pp_set_geometry ppf ~max_indent ~margin` is equivalent to `pp_set_margin ppf margin; pp_set_max_indent ppf max_indent`; and avoids the subtly incorrect `pp_set_max_indent ppf max_indent; pp_set_margin ppf margin`; - -Outside of this domain, `pp_set_geometry` raises an invalid argument exception whereas `pp_safe_set_geometry` does nothing. - -since 4.08 -``` -val pp_update_geometry : formatter -> (geometry -> geometry) -> unit -``` -`pp_update_geometry ppf (fun geo -> { geo with ... })` lets you update a formatter's geometry in a way that is robust to extension of the `geometry` record with new fields. - -Raises an invalid argument exception if the returned geometry does not satisfy [`check_geometry`](./#val-check_geometry). - -since 4.11 -``` -val update_geometry : (geometry -> geometry) -> unit -``` -``` -val pp_get_geometry : formatter -> unit -> geometry -``` -``` -val get_geometry : unit -> geometry -``` -Return the current geometry of the formatter - -since 4.08 - -## Maximum formatting depth - -The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open. - -Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). - -``` -val pp_set_max_boxes : formatter -> int -> unit -``` -``` -val set_max_boxes : int -> unit -``` -`pp_set_max_boxes ppf max` sets the maximum number of pretty-printing boxes simultaneously open. - -Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). - -Nothing happens if `max` is smaller than 2. - -``` -val pp_get_max_boxes : formatter -> unit -> int -``` -``` -val get_max_boxes : unit -> int -``` -Returns the maximum number of pretty-printing boxes allowed before ellipsis. - -``` -val pp_over_max_boxes : formatter -> unit -> bool -``` -``` -val over_max_boxes : unit -> bool -``` -Tests if the maximum number of pretty-printing boxes allowed have already been opened. - - -## Tabulation boxes - -A *tabulation box* prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text. - -This box features command `set_tab` to define cell boundaries, and command `print_tab` to move from cell to cell and split the line when there is no more cells to print on the line. - -Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module [`Format`](#). - -``` -val pp_open_tbox : formatter -> unit -> unit -``` -``` -val open_tbox : unit -> unit -``` -`open_tbox ()` opens a new tabulation box. - -This box prints lines separated into cells of fixed width. - -Inside a tabulation box, special *tabulation markers* defines points of interest on the line (for instance to delimit cell boundaries). Function [`Format.set_tab`](./#val-set_tab) sets a tabulation marker at insertion point. - -A tabulation box features specific *tabulation breaks* to move to next tabulation marker or split the line. Function [`Format.print_tbreak`](./#val-print_tbreak) prints a tabulation break. - -``` -val pp_close_tbox : formatter -> unit -> unit -``` -``` -val close_tbox : unit -> unit -``` -Closes the most recently opened tabulation box. - -``` -val pp_set_tab : formatter -> unit -> unit -``` -``` -val set_tab : unit -> unit -``` -Sets a tabulation marker at current insertion point. - -``` -val pp_print_tab : formatter -> unit -> unit -``` -``` -val print_tab : unit -> unit -``` -`print_tab ()` emits a 'next' tabulation break hint: if not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. - -It is equivalent to `print_tbreak 0 0`. - -``` -val pp_print_tbreak : formatter -> int -> int -> unit -``` -``` -val print_tbreak : int -> int -> unit -``` -`print_tbreak nspaces offset` emits a 'full' tabulation break hint. - -If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints `nspaces` spaces. - -If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box. - -If the pretty-printer splits the line, `offset` is added to the current indentation. - - -## Ellipsis - -``` -val pp_set_ellipsis_text : formatter -> string -> unit -``` -``` -val set_ellipsis_text : string -> unit -``` -Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, `.`, by default). - -``` -val pp_get_ellipsis_text : formatter -> unit -> string -``` -``` -val get_ellipsis_text : unit -> string -``` -Return the text of the ellipsis. - - -## Semantic tags - -``` -type stag = .. -``` -*Semantic tags* (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities. - -Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so: - -```ocaml -type stag += RGB of {r:int;g:int;b:int} -``` -In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using [`pp_open_stag`](./#val-pp_open_stag) and [`pp_close_stag`](./#val-pp_close_stag). - -Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed *tag-marking* and *tag-printing*: - -- The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation. -- The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations. -Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output). - -More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur: - -- Tag-printing a semantic tag means calling the formatter specific function `print_open_stag` (resp. `print_close_stag`) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation). -- Tag-marking a semantic tag means calling the formatter specific function `mark_open_stag` (resp. `mark_close_stag`) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. \`tag-closing marker') for direct output into the output device of the formatter. -Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting). - -Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once `set_tags` is set to `true`, the pretty-printer engine honors tags and decorates the output accordingly. - -Default tag-marking functions behave the HTML way: [string tags](./#type-tag) are enclosed in "\<" and "\>" while other tags are ignored; hence, opening marker for tag string `"t"` is `""` and closing marker is `""`. - -Default tag-printing functions just do nothing. - -Tag-marking and tag-printing functions are user definable and can be set by calling [`set_formatter_stag_functions`](./#val-set_formatter_stag_functions). - -Semantic tag operations may be set on or off with [`set_tags`](./#val-set_tags). Tag-marking operations may be set on or off with [`set_mark_tags`](./#val-set_mark_tags). Tag-printing operations may be set on or off with [`set_print_tags`](./#val-set_print_tags). - -since 4.08 -``` -type tag = string -``` -``` -type stag += -``` -``` -| String_tag of tag -``` -`String_tag s` is a string tag `s`. String tags can be inserted either by explicitly using the constructor `String_tag` or by using the dedicated format syntax `"@{ ... @}"`. - -since 4.08 -``` - -``` -``` -val pp_open_stag : formatter -> stag -> unit -``` -``` -val open_stag : stag -> unit -``` -`pp_open_stag ppf t` opens the semantic tag named `t`. - -The `print_open_stag` tag-printing function of the formatter is called with `t` as argument; then the opening tag marker for `t`, as given by `mark_open_stag t`, is written into the output device of the formatter. - -since 4.08 -``` -val pp_close_stag : formatter -> unit -> unit -``` -``` -val close_stag : unit -> unit -``` -`pp_close_stag ppf ()` closes the most recently opened semantic tag `t`. - -The closing tag marker, as given by `mark_close_stag t`, is written into the output device of the formatter; then the `print_close_stag` tag-printing function of the formatter is called with `t` as argument. - -since 4.08 -``` -val pp_set_tags : formatter -> bool -> unit -``` -``` -val set_tags : bool -> unit -``` -`pp_set_tags ppf b` turns on or off the treatment of semantic tags (default is off). - -``` -val pp_set_print_tags : formatter -> bool -> unit -``` -``` -val set_print_tags : bool -> unit -``` -`pp_set_print_tags ppf b` turns on or off the tag-printing operations. - -``` -val pp_set_mark_tags : formatter -> bool -> unit -``` -``` -val set_mark_tags : bool -> unit -``` -`pp_set_mark_tags ppf b` turns on or off the tag-marking operations. - -``` -val pp_get_print_tags : formatter -> unit -> bool -``` -``` -val get_print_tags : unit -> bool -``` -Return the current status of tag-printing operations. - -``` -val pp_get_mark_tags : formatter -> unit -> bool -``` -``` -val get_mark_tags : unit -> bool -``` -Return the current status of tag-marking operations. - -``` -val pp_set_formatter_out_channel : formatter -> out_channel -> unit -``` -Redirecting the standard formatter output - -``` -val set_formatter_out_channel : out_channel -> unit -``` -Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.) - -`set_formatter_out_channel` is equivalent to [`pp_set_formatter_out_channel`](./#val-pp_set_formatter_out_channel) `std_formatter`. - -``` -val pp_set_formatter_output_functions : - formatter -> - (string -> int -> int -> unit) -> - (unit -> unit) -> - unit -``` -``` -val set_formatter_output_functions : - (string -> int -> int -> unit) -> - (unit -> unit) -> - unit -``` -`pp_set_formatter_output_functions ppf out flush` redirects the standard pretty-printer output functions to the functions `out` and `flush`. - -The `out` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. - -The `flush` function is called whenever the pretty-printer is flushed (via conversion `%!`, or pretty-printing indications `@?` or `@.`, or using low level functions `print_flush` or `print_newline`). - -``` -val pp_get_formatter_output_functions : - formatter -> - unit -> - (string -> int -> int -> unit) * (unit -> unit) -``` -``` -val get_formatter_output_functions : - unit -> - (string -> int -> int -> unit) * (unit -> unit) -``` -Return the current output functions of the standard pretty-printer. - - -## Redefining formatter output - -The `Format` module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed\! - - -### Redefining output functions - -``` -type formatter_out_functions = { -``` -`out_string : string -> int -> int -> unit;` -`out_flush : unit -> unit;` -`out_newline : unit -> unit;` -`out_spaces : int -> unit;` -`out_indent : int -> unit;` -since 4.06 -``` -} -``` -The set of output functions specific to a formatter: - -- the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. -- the `out_flush` function flushes the pretty-printer output device. -- `out_newline` is called to open a new line when the pretty-printer splits the line. -- the `out_spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output. -- the `out_indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. -By default: - -- fields `out_string` and `out_flush` are output device specific; (e.g. [`Stdlib.output_string`](./Stdlib.md#val-output_string) and [`Stdlib.flush`](./Stdlib.md#val-flush) for a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) device, or `Buffer.add_substring` and [`Stdlib.ignore`](./Stdlib.md#val-ignore) for a `Buffer.t` output device), -- field `out_newline` is equivalent to `out_string "\n" 0 1`; -- fields `out_spaces` and `out_indent` are equivalent to `out_string (String.make n ' ') 0 n`. -since 4.01 -``` -val pp_set_formatter_out_functions : - formatter -> - formatter_out_functions -> - unit -``` -``` -val set_formatter_out_functions : formatter_out_functions -> unit -``` -`pp_set_formatter_out_functions ppf out_funs` Set all the pretty-printer output functions of `ppf` to those of argument `out_funs`, - -This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand). - -Reasonable defaults for functions `out_spaces` and `out_newline` are respectively `out_funs.out_string (String.make n ' ') 0 n` and `out_funs.out_string "\n" 0 1`. - -since 4.01 -``` -val pp_get_formatter_out_functions : - formatter -> - unit -> - formatter_out_functions -``` -``` -val get_formatter_out_functions : unit -> formatter_out_functions -``` -Return the current output functions of the pretty-printer, including line splitting and indentation functions. Useful to record the current setting and restore it afterwards. - -since 4.01 - -## Redefining semantic tag operations - -``` -type formatter_stag_functions = { -``` -`mark_open_stag : stag -> string;` -`mark_close_stag : stag -> string;` -`print_open_stag : stag -> unit;` -`print_close_stag : stag -> unit;` -``` -} -``` -The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. `print` versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened. - -since 4.08 -``` -val pp_set_formatter_stag_functions : - formatter -> - formatter_stag_functions -> - unit -``` -``` -val set_formatter_stag_functions : formatter_stag_functions -> unit -``` -`pp_set_formatter_stag_functions ppf tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`. - -When opening a semantic tag with name `t`, the string `t` is passed to the opening tag-marking function (the `mark_open_stag` field of the record `tag_funs`), that must return the opening tag marker for that name. When the next call to `close_stag ()` happens, the semantic tag name `t` is sent back to the closing tag-marking function (the `mark_close_stag` field of record `tag_funs`), that must return a closing tag marker for that name. - -The `print_` field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue. - -since 4.08 -``` -val pp_get_formatter_stag_functions : - formatter -> - unit -> - formatter_stag_functions -``` -``` -val get_formatter_stag_functions : unit -> formatter_stag_functions -``` -Return the current semantic tag operation functions of the standard pretty-printer. - -since 4.08 - -## Defining formatters - -Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently. - -For instance, given a [`Buffer.t`](./Stdlib-Buffer.md#type-t) buffer `b`, [`formatter_of_buffer`](./#val-formatter_of_buffer) `b` returns a new formatter using buffer `b` as its output device. Similarly, given a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) output channel `oc`, [`formatter_of_out_channel`](./#val-formatter_of_out_channel) `oc` returns a new formatter using channel `oc` as its output device. - -Alternatively, given `out_funs`, a complete set of output functions for a formatter, then [`formatter_of_out_functions`](./#val-formatter_of_out_functions) `out_funs` computes a new formatter using those functions for output. - -``` -val formatter_of_out_channel : out_channel -> formatter -``` -`formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`. - -``` -val synchronized_formatter_of_out_channel : - out_channel -> - formatter Domain.DLS.key -``` -`synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`. - -When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -alert unstable -``` -val std_formatter : formatter -``` -The initial domain's standard formatter to write to standard output. - -It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stdout`](./Stdlib.md#val-stdout). - -``` -val get_std_formatter : unit -> formatter -``` -`get_std_formatter ()` returns the current domain's standard formatter used to write to standard output. - -since 5.0 -``` -val err_formatter : formatter -``` -The initial domain's formatter to write to standard error. - -It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stderr`](./Stdlib.md#val-stderr). - -``` -val get_err_formatter : unit -> formatter -``` -`get_err_formatter ()` returns the current domain's formatter used to write to standard error. - -since 5.0 -``` -val formatter_of_buffer : Buffer.t -> formatter -``` -`formatter_of_buffer b` returns a new formatter writing to buffer `b`. At the end of pretty-printing, the formatter must be flushed using [`pp_print_flush`](./#val-pp_print_flush) or [`pp_print_newline`](./#val-pp_print_newline), to print all the pending material into the buffer. - -``` -val stdbuf : Buffer.t -``` -The initial domain's string buffer in which `str_formatter` writes. - -``` -val get_stdbuf : unit -> Buffer.t -``` -`get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes. - -since 5.0 -``` -val str_formatter : formatter -``` -The initial domain's formatter to output to the [`stdbuf`](./#val-stdbuf) string buffer. - -`str_formatter` is defined as [`formatter_of_buffer`](./#val-formatter_of_buffer) [`stdbuf`](./#val-stdbuf). - -``` -val get_str_formatter : unit -> formatter -``` -The current domain's formatter to output to the current domains string buffer. - -since 5.0 -``` -val flush_str_formatter : unit -> string -``` -Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer. - -``` -val make_formatter : - (string -> int -> int -> unit) -> - (unit -> unit) -> - formatter -``` -`make_formatter out flush` returns a new formatter that outputs with function `out`, and flushes with function `flush`. - -For instance, - -```ocaml - make_formatter - (Stdlib.output_substring oc) - (fun () -> Stdlib.flush oc) -``` -returns a formatter to the [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) `oc`. - -``` -val make_synchronized_formatter : - (string -> int -> int -> unit) -> - (unit -> unit) -> - formatter Domain.DLS.key -``` -`make_synchronized_formatter out flush` returns the key to the domain-local state that holds the domain-local formatter that outputs with function `out`, and flushes with function `flush`. - -When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -since 5.0 -alert unstable -``` -val formatter_of_out_functions : formatter_out_functions -> formatter -``` -`formatter_of_out_functions out_funs` returns a new formatter that writes with the set of output functions `out_funs`. - -See definition of type [`formatter_out_functions`](./#type-formatter_out_functions) for the meaning of argument `out_funs`. - -since 4.06 - -### Symbolic pretty-printing - -Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items. - -When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations. - -In practice, first define a symbolic output buffer `b` using: - -- `let sob = make_symbolic_output_buffer ()`. Then define a symbolic formatter with: -- `let ppf = formatter_of_symbolic_output_buffer sob` -Use symbolic formatter `ppf` as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer `sob` with: - -- `flush_symbolic_output_buffer sob`. -``` -type symbolic_output_item = -``` -``` -| Output_flush -``` -symbolic flush command - -``` -| Output_newline -``` -symbolic newline command - -``` -| Output_string of string -``` -`Output_string s`: symbolic output for string `s` - -``` -| Output_spaces of int -``` -`Output_spaces n`: symbolic command to output `n` spaces - -``` -| Output_indent of int -``` -`Output_indent i`: symbolic indentation of size `i` - -``` - -``` -Items produced by symbolic pretty-printers - -since 4.06 -``` -type symbolic_output_buffer -``` -The output buffer of a symbolic pretty-printer. - -since 4.06 -``` -val make_symbolic_output_buffer : unit -> symbolic_output_buffer -``` -`make_symbolic_output_buffer ()` returns a fresh buffer for symbolic output. - -since 4.06 -``` -val clear_symbolic_output_buffer : symbolic_output_buffer -> unit -``` -`clear_symbolic_output_buffer sob` resets buffer `sob`. - -since 4.06 -``` -val get_symbolic_output_buffer : - symbolic_output_buffer -> - symbolic_output_item list -``` -`get_symbolic_output_buffer sob` returns the contents of buffer `sob`. - -since 4.06 -``` -val flush_symbolic_output_buffer : - symbolic_output_buffer -> - symbolic_output_item list -``` -`flush_symbolic_output_buffer sob` returns the contents of buffer `sob` and resets buffer `sob`. `flush_symbolic_output_buffer sob` is equivalent to `let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items` - -since 4.06 -``` -val add_symbolic_output_item : - symbolic_output_buffer -> - symbolic_output_item -> - unit -``` -`add_symbolic_output_item sob itm` adds item `itm` to buffer `sob`. - -since 4.06 -``` -val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter -``` -`formatter_of_symbolic_output_buffer sob` returns a symbolic formatter that outputs to `symbolic_output_buffer` `sob`. - -since 4.06 - -## Convenience formatting functions. - -``` -val pp_print_iter : - ?pp_sep:(formatter -> unit -> unit) -> - (('a -> unit) -> 'b -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'b -> - unit -``` -`pp_print_iter ~pp_sep iter pp_v ppf v` formats on `ppf` the iterations of `iter` over a collection `v` of values using `pp_v`. Iterations are separated by `pp_sep` (defaults to [`pp_print_cut`](./#val-pp_print_cut)). - -since 5.1 -``` -val pp_print_list : - ?pp_sep:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a list -> - unit -``` -`pp_print_list ?pp_sep pp_v ppf l` prints items of list `l`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty lists. - -since 4.02 -``` -val pp_print_array : - ?pp_sep:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a array -> - unit -``` -`pp_print_array ?pp_sep pp_v ppf a` prints items of array `a`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty arrays. - -If `a` is mutated after `pp_print_array` is called, the printed values may not be what is expected because `Format` can delay the printing. This can be avoided by flushing `ppf`. - -since 5.1 -``` -val pp_print_seq : - ?pp_sep:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a Seq.t -> - unit -``` -`pp_print_seq ?pp_sep pp_v ppf s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut). Does nothing on empty sequences. - -This function does not terminate on infinite sequences. - -since 4.12 -``` -val pp_print_text : formatter -> string -> unit -``` -`pp_print_text ppf s` prints `s` with spaces and newlines respectively printed using [`pp_print_space`](./#val-pp_print_space) and [`pp_force_newline`](./#val-pp_force_newline). - -since 4.02 -``` -val pp_print_option : - ?none:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a option -> - unit -``` -`pp_print_option ?none pp_v ppf o` prints `o` on `ppf` using `pp_v` if `o` is `Some v` and `none` if it is `None`. `none` prints nothing by default. - -since 4.08 -``` -val pp_print_result : - ok:(formatter -> 'a -> unit) -> - error:(formatter -> 'e -> unit) -> - formatter -> - ('a, 'e) result -> - unit -``` -`pp_print_result ~ok ~error ppf r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`. - -since 4.08 -``` -val pp_print_either : - left:(formatter -> 'a -> unit) -> - right:(formatter -> 'b -> unit) -> - formatter -> - ('a, 'b) Either.t -> - unit -``` -`pp_print_either ~left ~right ppf e` prints `e` on `ppf` using `left` if `e` is `Either.Left _` and `right` if `e` is `Either.Right _`. - -since 4.13 - -## Formatted pretty-printing - -Module `Format` provides a complete set of `printf` like functions for pretty-printing using format string specifications. - -Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine. - -Those annotations are introduced in the format strings using the `@` character. For instance, `@ ` means a space break, `@,` means a cut, `@[` opens a new box, and `@]` closes the last open box. - -``` -val fprintf : formatter -> ('a, formatter, unit) format -> 'a -``` -`fprintf ff fmt arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `fmt`, and outputs the resulting string on the formatter `ff`. - -The format string `fmt` is a character string which contains three types of objects: plain characters and conversion specifications as specified in the [`Printf`](./Stdlib-Printf.md) module, and pretty-printing indications specific to the `Format` module. - -The pretty-printing indication characters are introduced by a `@` character, and their meanings are: - -- `@[`: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the `<` character, followed by an optional box type indication, then an optional integer offset, and the closing `>` character. Pretty-printing box type is one of `h`, `v`, `hv`, `b`, or `hov`. '`h`' stands for an 'horizontal' pretty-printing box, '`v`' stands for a 'vertical' pretty-printing box, '`hv`' stands for an 'horizontal/vertical' pretty-printing box, '`b`' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '`hov`' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, `@[` opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with `open_hovbox 2`. For more details about pretty-printing boxes, see the various box opening functions `open_*box`. -- `@]`: close the most recently opened pretty-printing box. -- `@,`: output a 'cut' break hint, as with `print_cut ()`. -- `@ `: output a 'space' break hint, as with `print_space ()`. -- `@;`: output a 'full' break hint as with `print_break`. The `nspaces` and `offset` parameters of the break hint may be optionally specified with the following syntax: the `<` character, followed by an integer `nspaces` value, then an integer `offset`, and a closing `>` character. If no parameters are provided, the full break defaults to a 'space' break hint. -- `@.`: flush the pretty-printer and split the line, as with `print_newline ()`. -- `@`: print the following item as if it were of length `n`. Hence, `printf "@<0>%s" arg` prints `arg` as a zero length string. If `@` is not followed by a conversion specification, then the following character of the format is printed as if it were of length `n`. -- `@\{`: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the `<` character, followed by an optional string specification, and the closing `>` character. The string specification is any character string that does not contain the closing character `'>'`. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions [`open_stag`](./#val-open_stag) and [`close_stag`](./#val-close_stag). -- `@\}`: close the most recently opened semantic tag. -- `@?`: flush the pretty-printer as with `print_flush ()`. This is equivalent to the conversion `%!`. -- `@\n`: force a newline, as with `force_newline ()`, not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box. -Note: To prevent the interpretation of a `@` character as a pretty-printing indication, escape it with a `%` character. Old quotation mode `@@` is deprecated since it is not compatible with formatted input interpretation of character `'@'`. - -Example: `printf "@[%s@ %d@]@." "x =" 1` is equivalent to `open_box (); print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()`. It prints `x = 1` within a pretty-printing 'horizontal-or-vertical' box. - -``` -val printf : ('a, formatter, unit) format -> 'a -``` -Same as `fprintf` above, but output on `get_std_formatter ()`. - -It is defined similarly to `fun fmt -> fprintf (get_std_formatter ()) fmt` but delays calling `get_std_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -``` -val eprintf : ('a, formatter, unit) format -> 'a -``` -Same as `fprintf` above, but output on `get_err_formatter ()`. - -It is defined similarly to `fun fmt -> fprintf (get_err_formatter ()) fmt` but delays calling `get_err_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -``` -val sprintf : ('a, unit, string) format -> 'a -``` -Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of *each call* to `sprintf`. Note that if your format string contains a `%a`, you should use `asprintf`. - -In case of multiple and related calls to `sprintf` to output material on a single string, you should consider using `fprintf` with the predefined formatter `str_formatter` and call `flush_str_formatter ()` to get the final result. - -Alternatively, you can use `Format.fprintf` with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string. - -``` -val asprintf : ('a, formatter, unit, string) format4 -> 'a -``` -Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. The type of `asprintf` is general enough to interact nicely with `%a` conversions. - -since 4.01 -``` -val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a -``` -Same as [`fprintf`](./#val-fprintf), except the formatter is the last argument. `dprintf "..." a b c` is a function of type `formatter -> unit` which can be given to a format specifier `%t`. - -This can be used as a replacement for [`asprintf`](./#val-asprintf) to delay formatting decisions. Using the string returned by [`asprintf`](./#val-asprintf) in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. [`dprintf`](./#val-dprintf) allows delay of formatting decisions until the final formatting context is known. For example: - -```ocaml - let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in - ... - Format.printf "@[%t@]" t -``` -since 4.08 -``` -val ifprintf : formatter -> ('a, formatter, unit) format -> 'a -``` -Same as `fprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 3.10 -Formatted Pretty-Printing with continuations. - -``` -val kfprintf : - (formatter -> 'a) -> - formatter -> - ('b, formatter, unit, 'a) format4 -> - 'b -``` -Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing. - -``` -val kdprintf : - ((formatter -> unit) -> 'a) -> - ('b, formatter, unit, 'a) format4 -> - 'b -``` -Same as [`dprintf`](./#val-dprintf) above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing. - -since 4.08 -``` -val ikfprintf : - (formatter -> 'a) -> - formatter -> - ('b, formatter, unit, 'a) format4 -> - 'b -``` -Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 3.12 -``` -val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b -``` -Same as `sprintf` above, but instead of returning the string, passes it to the first argument. - -``` -val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b -``` -Same as `asprintf` above, but instead of returning the string, passes it to the first argument. - -since 4.03 - -## Examples - -A few warmup examples to get an idea of how Format is used. - -We have a list `l` of pairs `(int * bool)`, which the toplevel prints for us: - -```ocaml -# let l = List.init 20 (fun n -> n, n mod 2 = 0) -val l : (int * bool) list = -[(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); - (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); - (12, true); (13, false); (14, true); (15, false); (16, true); (17, false); - (18, true); (19, false)] -``` -If we want to print it ourself without the toplevel magic, we can try this: - -```ocaml -# let pp_pair out (x,y) = Format.fprintf out "(%d, %b)" x y -val pp_pair : Format.formatter -> int * bool -> unit = -# Format.printf "l: [@[%a@]]@." - Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out ";@ ") pp_pair) l - l: [(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); - (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); - (12, true); (13, false); (14, true); (15, false); (16, true); - (17, false); (18, true); (19, false)] - -``` -What this does, briefly, is: - -- `pp_pair` prints a pair `bool*int` surrounded in "(" ")". It takes a formatter (into which formatting happens), and the pair itself. When printing is done it returns `()`. -- `Format.printf "l = [@[%a@]]@." ... l` is like `printf`, but with additional formatting instructions (denoted with "@"). The pair "`@[`" and "`@]`" is a "horizontal-or-vertical box". -- "@." ends formatting with a newline. It is similar to "\\n" but is also aware of the `Format.formatter`'s state. Do not use "\\n" with `Format`. -- "%a" is a formatting instruction, like "%d" or "%s" for `printf`. However, where "%d" prints an integer and "%s" prints a string, "%a" takes a printer (of type `Format.formatter -> 'a -> unit`) and a value (of type `'a`) and applies the printer to the value. This is key to compositionality of printers. -- We build a list printer using `Format.pp_print_list ~pp_sep:(...) pp_pair`. `pp_print_list` takes an element printer and returns a list printer. The `?pp_sep` optional argument, if provided, is called in between each element to print a separator. -- Here, for a separator, we use `(fun out () -> Format.fprintf out ";@ ")`. It prints ";", and then "@ " which is a breaking space (either it prints " ", or it prints a newline if the box is about to overflow). This "@ " is responsible for the list printing splitting into several lines. -If we omit "@ ", we get an ugly single-line print: - -```ocaml - # Format.printf "l: [@[%a@]]@." - Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out "; ") pp_pair) l - l: [(0, true); (1, false); (2, true); (* ... *); (18, true); (19, false)] -- : unit = () -``` -Generally, it is good practice to define custom printers for important types in your program. If, for example, you were to define basic geometry types like so: - -```ocaml -type point = { - x: float; - y: float; -} - -type rectangle = { - ll: point; (* lower left *) - ur: point; (* upper right *) -} -``` -For debugging purpose, or to display information in logs, or on the console, it would be convenient to define printers for these types. Here is an example of to do it. Note that "%.3f" is a `float` printer up to 3 digits of precision after the dot; "%f" would print as many digits as required, which is somewhat verbose; "%h" is an hexadecimal float printer. - -```ocaml -let pp_point out (p:point) = - Format.fprintf out "{ @[x=%.3f;@ y=%.3f@] }" p.x p.y - -let pp_rectangle out (r:rectangle) = - Format.fprintf out "{ @[ll=%a;@ ur=%a@] }" - pp_point r.ll pp_point r.ur -``` -In the `.mli` file, we could have: - -```ocaml - val pp_point : Format.formatter -> point -> unit - - val pp_rectangle : Format.formatter -> rectangle -> unit -``` -These printers can now be used with "%a" inside other printers. - -```ocaml - # Format.printf "some rectangle: %a@." - (Format.pp_print_option pp_rectangle) - (Some {ll={x=1.; y=2.}; ur={x=42.; y=500.12345}}) -some rectangle: { l={ x=1.000; y=2.000 }; ur={ x=42.000; y=500.123 } } - -# Format.printf "no rectangle: %a@." - (Format.pp_option pp_rectangle) - None -no rectangle: -``` -See how we combine `pp_print_option` (option printer) and our newly defined rectangle printer, like we did with `pp_print_list` earlier. - -For a more extensive tutorial, see ["Using the Format module"](https://caml.inria.fr/resources/doc/guides/format.en.html). - -A final note: the `Format` module is a starting point. The OCaml ecosystem has libraries that makes formatting easier and more expressive, with more combinators, more concise names, etc. An example of such a library is [Fmt](https://erratique.ch/software/fmt). - -Automatic deriving of pretty-printers from type definitions is also possible, using [https://github.com/ocaml-ppx/ppx\_deriving](ppx_deriving.show) or similar ppx derivers. diff --git a/docs/api/ml/melange/Stdlib-Fun.md b/docs/api/ml/melange/Stdlib-Fun.md deleted file mode 100644 index ce11eb91e..000000000 --- a/docs/api/ml/melange/Stdlib-Fun.md +++ /dev/null @@ -1,51 +0,0 @@ - -# Module `Stdlib.Fun` - -Function manipulation. - -since 4.08 - -## Combinators - -``` -val id : 'a -> 'a -``` -`id` is the identity function. For any argument `x`, `id x` is `x`. - -``` -val const : 'a -> _ -> 'a -``` -`const c` is a function that always returns the value `c`. For any argument `x`, `(const c) x` is `c`. - -``` -val compose : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c -``` -`compose f g` is a function composition of applying `g` then `f`. For any arguments `f`, `g`, and `x`, `compose f g x` is `f (g x)`. - -since 5.2 -``` -val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c -``` -`flip f` reverses the argument order of the binary function `f`. For any arguments `x` and `y`, `(flip f) x y` is `f y x`. - -``` -val negate : ('a -> bool) -> 'a -> bool -``` -`negate p` is the negation of the predicate function `p`. For any argument `x`, `(negate p) x` is `not (p x)`. - - -## Exception handling - -``` -val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a -``` -`protect ~finally work` invokes `work ()` and then `finally ()` before `work ()` returns with its value or an exception. In the latter case the exception is re-raised after `finally ()`. If `finally ()` raises an exception, then the exception [`Finally_raised`](./#exception-Finally_raised) is raised instead. - -`protect` can be used to enforce local invariants whether `work ()` returns normally or raises an exception. However, it does not protect against unexpected exceptions raised inside `finally ()` such as [`Stdlib.Out_of_memory`](./Stdlib.md#exception-Out_of_memory), [`Stdlib.Stack_overflow`](./Stdlib.md#exception-Stack_overflow), or asynchronous exceptions raised by signal handlers (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)). - -Note: It is a *programming error* if other kinds of exceptions are raised by `finally`, as any exception raised in `work ()` will be lost in the event of a [`Finally_raised`](./#exception-Finally_raised) exception. Therefore, one should make sure to handle those inside the finally. - -``` -exception Finally_raised of exn -``` -`Finally_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally_raised` exception except as part of a catch-all handler. diff --git a/docs/api/ml/melange/Stdlib-Gc-Memprof.md b/docs/api/ml/melange/Stdlib-Gc-Memprof.md deleted file mode 100644 index 4258d4511..000000000 --- a/docs/api/ml/melange/Stdlib-Gc-Memprof.md +++ /dev/null @@ -1,113 +0,0 @@ - -# Module `Gc.Memprof` - -`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. - -Since blocks are composed of several words, a block can potentially be sampled several times. If a block is sampled several times, then each of the callbacks is called once for each event of this block: the multiplicity is given in the `n_samples` field of the `allocation` structure. - -This engine makes it possible to implement a low-overhead memory profiler as an OCaml library. - -Note: this API is EXPERIMENTAL. It may change without prior notice. - -``` -type t -``` -the type of a profile - -``` -type allocation_source = -``` -``` -| Normal -``` -``` -| Marshal -``` -``` -| Custom -``` -``` - -``` -``` -type allocation = private { -``` -`n_samples : int;` -The number of samples in this block (\>= 1\). - -`size : int;` -The size of the block, in words, excluding the header. - -`source : allocation_source;` -The cause of the allocation. - -`callstack : Printexc.raw_backtrace;` -The callstack for the allocation. - -``` -} -``` -The type of metadata associated with allocations. This is the type of records passed to the callback triggered by the sampling of an allocation. - -``` -type ('minor, 'major) tracker = { -``` -`alloc_minor : allocation -> 'minor option;` -`alloc_major : allocation -> 'major option;` -`promote : 'minor -> 'major option;` -`dealloc_minor : 'minor -> unit;` -`dealloc_major : 'major -> unit;` -``` -} -``` -A `('minor, 'major) tracker` describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: `'minor` is the type of metadata to keep for minor blocks, and `'major` the type of metadata for major blocks. - -The member functions in a `tracker` are called callbacks. - -If an allocation or promotion callback raises an exception or returns `None`, memprof stops tracking the corresponding block. - -``` -val null_tracker : ('minor, 'major) tracker -``` -Default callbacks simply return `None` or `()` - -``` -val start : - sampling_rate:float -> - ?callstack_size:int -> - ('minor, 'major) tracker -> - t -``` -Start a profile with the given parameters. Raises an exception if a profile is already sampling in the current domain. - -Sampling begins immediately. The parameter `sampling_rate` is the sampling rate in samples per word (including headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on performance, and 1e-3 causes the program to run a few percent slower. 0.0 \<= sampling\_rate \<= 1\.0. - -The parameter `callstack_size` is the length of the callstack recorded at every sample. Its default is `max_int`. - -The parameter `tracker` determines how to track sampled blocks over their lifetime in the minor and major heap. - -Sampling and running callbacks are temporarily disabled on the current thread when calling a callback, so callbacks do not need to be re-entrant if the program is single-threaded and single-domain. However, if threads or multiple domains are used, it is possible that several callbacks will run in parallel. In this case, callback functions must be re-entrant. - -Note that a callback may be postponed slightly after the actual event. The callstack passed to an allocation callback always accurately reflects the allocation, but the program state may have evolved between the allocation and the call to the callback. - -If a new thread or domain is created when the current domain is sampling for a profile, the child thread or domain joins that profile (using the same `sampling_rate`, `callstack_size`, and `tracker` callbacks). - -An allocation callback is always run by the thread which allocated the block. If the thread exits or the profile is stopped before the callback is called, the allocation callback is not called and the block is not tracked. - -Each subsequent callback is generally run by the domain which allocated the block. If the domain terminates or the profile is stopped before the callback is called, the callback may be run by a different domain. - -Different domains may sample for different profiles simultaneously. - -``` -val stop : unit -> unit -``` -Stop sampling for the current profile. Fails if no profile is sampling in the current domain. Stops sampling in all threads and domains sharing the profile. - -Promotion and deallocation callbacks from a profile may run after `stop` is called, until `discard` is applied to the profile. - -A profile is implicitly stopped (but not discarded) if all domains and threads sampling for it are terminated. - -``` -val discard : t -> unit -``` -Discards all profiling state for a stopped profile, which prevents any more callbacks for it. Raises an exception if called on a profile which has not been stopped. diff --git a/docs/api/ml/melange/Stdlib-Gc.md b/docs/api/ml/melange/Stdlib-Gc.md deleted file mode 100644 index 37e04a556..000000000 --- a/docs/api/ml/melange/Stdlib-Gc.md +++ /dev/null @@ -1,295 +0,0 @@ - -# Module `Stdlib.Gc` - -Memory management control and statistics; finalised values. - -``` -type stat = { -``` -`minor_words : float;` -Number of words allocated in the minor heap since the program was started. - -`promoted_words : float;` -Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap since the program was started. - -`major_words : float;` -Number of words allocated in the major heap, including the promoted words, since the program was started. - -`minor_collections : int;` -Number of minor collections since the program was started. - -`major_collections : int;` -Number of major collection cycles completed since the program was started. - -`heap_words : int;` -Total size of the major heap, in words. - -`heap_chunks : int;` -Number of contiguous pieces of memory that make up the major heap. This metric is currently not available in OCaml 5: the field value is always `0`. - -`live_words : int;` -Number of words of live data in the major heap, including the header words. - -Note that "live" words refers to every word in the major heap that isn't currently known to be collectable, which includes words that have become unreachable by the program after the start of the previous gc cycle. It is typically much simpler and more predictable to call [`Gc.full_major`](./#val-full_major) (or [`Gc.compact`](./#val-compact)) then computing gc stats, as then "live" words has the simple meaning of "reachable by the program". One caveat is that a single call to [`Gc.full_major`](./#val-full_major) will not reclaim values that have a finaliser from [`Gc.finalise`](./#val-finalise) (this does not apply to [`Gc.finalise_last`](./#val-finalise_last)). If this caveat matters, simply call [`Gc.full_major`](./#val-full_major) twice instead of once. - -`live_blocks : int;` -Number of live blocks in the major heap. - -See `live_words` for a caveat about what "live" means. - -`free_words : int;` -Number of words in the free list. - -`free_blocks : int;` -Number of blocks in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. - -`largest_free : int;` -Size (in words) of the largest block in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. - -`fragments : int;` -Number of wasted words due to fragmentation. These are 1-words free blocks placed between two live blocks. They are not available for allocation. - -`compactions : int;` -Number of heap compactions since the program was started. - -`top_heap_words : int;` -Maximum size reached by the major heap, in words. - -`stack_size : int;` -Current size of the stack, in words. This metric is currently not available in OCaml 5: the field value is always `0`. - -since 3.12 -`forced_major_collections : int;` -Number of forced full major collections completed since the program was started. - -since 4.12 -``` -} -``` -The memory management counters are returned in a `stat` record. These counters give values for the whole program. - -The total amount of memory allocated by the program since it was started is (in words) `minor_words + major_words - promoted_words`. Multiply by the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes. - -``` -type control = { -``` -`minor_heap_size : int;` -The size (in words) of the minor heap. Changing this parameter will trigger a minor collection. The total size of the minor heap used by this program is the sum of the heap sizes of the active domains. Default: 256k. - -`major_heap_increment : int;` -How much to add to the major heap when increasing it. If this number is less than or equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will double the heap size at each increase). If it is more than 1000, it is a fixed number of words that will be added to the heap. - -This field is currently not available in OCaml 5: the field value is always `0`. - -`space_overhead : int;` -The major GC speed is computed from this parameter. This is the memory that will be "wasted" because the GC does not immediately collect unreachable blocks. It is expressed as a percentage of the memory used for live data. The GC will work more (use more CPU time and collect blocks more eagerly) if `space_overhead` is smaller. Default: 120. - -`verbose : int;` -This value controls the GC messages on standard error output. It is a sum of some of the following flags, to print messages on the corresponding events: - -- `0x001` Start and end of major GC cycle. -- `0x002` Minor collection and major GC slice. -- `0x004` Growing and shrinking of the heap. -- `0x008` Resizing of stacks and memory manager tables. -- `0x010` Heap compaction. -- `0x020` Change of GC parameters. -- `0x040` Computation of major GC slice size. -- `0x080` Calling of finalisation functions. -- `0x100` Bytecode executable and shared library search at start-up. -- `0x200` Computation of compaction-triggering condition. -- `0x400` Output GC statistics at program exit. Default: 0. -`max_overhead : int;` -Heap compaction is triggered when the estimated amount of "wasted" memory is more than `max_overhead` percent of the amount of live data. If `max_overhead` is set to 0, heap compaction is triggered at the end of each major GC cycle (this setting is intended for testing purposes only). If `max_overhead >= 1000000`, compaction is never triggered. - -This field is currently not available in OCaml 5: the field value is always `0`. - -`stack_limit : int;` -The maximum size of the fiber stacks (in words). Default: 128M. - -`allocation_policy : int;` -The policy used for allocating in the major heap. - -This field is currently not available in OCaml 5: the field value is always `0`. - -Prior to OCaml 5.0, possible values were 0, 1 and 2. - -- 0 was the next-fit policy -- 1 was the first-fit policy (since OCaml 3.11) -- 2 was the best-fit policy (since OCaml 4.10) -since 3.11 -`window_size : int;` -The size of the window used by the major GC for smoothing out variations in its workload. This is an integer between 1 and 50. - -since 4.03 -This field is currently not available in OCaml 5: the field value is always `0`. - -`custom_major_ratio : int;` -Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. The default value keeps the out-of-heap floating garbage about the same size as the in-heap overhead. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 44. - -since 4.08 -`custom_minor_ratio : int;` -Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 100. - -since 4.08 -`custom_minor_max_size : int;` -Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. Custom values that hold more than this many bytes are allocated on the major heap. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 70000 bytes. - -since 4.08 -``` -} -``` -The GC parameters are given as a `control` record. Note that these parameters can also be initialised by setting the OCAMLRUNPARAM environment variable. See the documentation of `ocamlrun`. - -``` -val stat : unit -> stat -``` -Return the current values of the memory management counters in a `stat` record that represents the program's total memory stats. The `heap_chunks`, `free_blocks`, `largest_free`, and `stack_size` metrics are currently not available in OCaml 5: their returned field values are therefore `0`. This function causes a full major collection. - -``` -val quick_stat : unit -> stat -``` -Returns a record with the current values of the memory management counters like `stat`. Unlike `stat`, `quick_stat` does not perform a full major collection, and hence, is much faster. However, `quick_stat` reports the counters sampled at the last minor collection or at the end of the last major collection cycle (whichever is the latest). Hence, the memory stats returned by `quick_stat` are not instantaneously accurate. - -``` -val counters : unit -> float * float * float -``` -Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. This function is as fast as `quick_stat`. - -``` -val minor_words : unit -> float -``` -Number of words allocated in the minor heap by this domain or potentially previous domains. This number is accurate in byte-code programs, but only an approximation in programs compiled to native code. - -In native code this function does not allocate. - -since 4.04 -``` -val get : unit -> control -``` -Return the current values of the GC parameters in a `control` record. - -The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: their returned field values are therefore `0`. - -alert unsynchronized\_access GC parameters are a mutable global state. -``` -val set : control -> unit -``` -`set r` changes the GC parameters according to the `control` record `r`. The normal usage is: `Gc.set { (Gc.get()) with Gc.verbose = 0x00d }` - -The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: setting them therefore has no effect. - -alert unsynchronized\_access GC parameters are a mutable global state. -``` -val minor : unit -> unit -``` -Trigger a minor collection. - -``` -val major_slice : int -> int -``` -`major_slice n` Do a minor collection and a slice of major collection. `n` is the size of the slice: the GC will do enough work to free (on average) `n` words of memory. If `n` \= 0, the GC will try to do enough work to ensure that the next automatic slice has no work to do. This function returns an unspecified integer (currently: 0). - -``` -val major : unit -> unit -``` -Do a minor collection and finish the current major collection cycle. - -``` -val full_major : unit -> unit -``` -Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. This will collect all currently unreachable blocks. - -``` -val compact : unit -> unit -``` -Perform a full major collection and compact the heap. Note that heap compaction is a lengthy operation. - -``` -val print_stat : out_channel -> unit -``` -Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument. - -``` -val allocated_bytes : unit -> float -``` -Return the number of bytes allocated by this domain and potentially a previous domain. It is returned as a `float` to avoid overflow problems with `int` on 32-bit machines. - -``` -val get_minor_free : unit -> int -``` -Return the current size of the free space inside the minor heap of this domain. - -since 4.03 -``` -val finalise : ('a -> unit) -> 'a -> unit -``` -`finalise f v` registers `f` as a finalisation function for `v`. `v` must be heap-allocated. `f` will be called with `v` as argument at some point between the first time `v` becomes unreachable (including through weak pointers) and the time `v` is collected by the GC. Several functions can be registered for the same value, or even several instances of the same function. Each instance will be called once (or never, if the program terminates before `v` becomes unreachable). - -The GC will call the finalisation functions in the order of deallocation. When several values become unreachable at the same time (i.e. during the same GC cycle), the finalisation functions will be called in the reverse order of the corresponding calls to `finalise`. If `finalise` is called in the same order as the values are allocated, that means each value is finalised before the values it depends upon. Of course, this becomes false if additional dependencies are introduced by assignments. - -In the presence of multiple OCaml threads it should be assumed that any particular finaliser may be executed in any of the threads. - -Anything reachable from the closure of finalisation functions is considered reachable, so the following code will not work as expected: - -- ` let v = ... in Gc.finalise (fun _ -> ...v...) v ` -Instead you should make sure that `v` is not in the closure of the finalisation function by writing: - -- ` let f = fun x -> ... let v = ... in Gc.finalise f v ` -The `f` function can use all features of OCaml, including assignments that make the value reachable again. It can also loop forever (in this case, the other finalisation functions will not be called during the execution of f, unless it calls `finalise_release`). It can call `finalise` on `v` or other values to register other functions or even itself. It can raise an exception; in this case the exception will interrupt whatever the program was doing when the function was called. - -`finalise` will raise `Invalid_argument` if `v` is not guaranteed to be heap-allocated. Some examples of values that are not heap-allocated are integers, constant constructors, booleans, the empty array, the empty list, the unit value. The exact list of what is heap-allocated or not is implementation-dependent. Some constant values can be heap-allocated but never deallocated during the lifetime of the program, for example a list of integer constants; this is also implementation-dependent. Note that values of types `float` are sometimes allocated and sometimes not, so finalising them is unsafe, and `finalise` will also raise `Invalid_argument` for them. Values of type `'a Lazy.t` (for any `'a`) are like `float` in this respect, except that the compiler sometimes optimizes them in a way that prevents `finalise` from detecting them. In this case, it will not raise `Invalid_argument`, but you should still avoid calling `finalise` on lazy values. - -The results of calling [`String.make`](./Stdlib-String.md#val-make), [`Bytes.make`](./Stdlib-Bytes.md#val-make), [`Bytes.create`](./Stdlib-Bytes.md#val-create), [`Array.make`](./Stdlib-Array.md#val-make), and [`Stdlib.ref`](./Stdlib.md#val-ref) are guaranteed to be heap-allocated and non-constant except when the length argument is `0`. - -``` -val finalise_last : (unit -> unit) -> 'a -> unit -``` -same as [`finalise`](./#val-finalise) except the value is not given as argument. So you can't use the given value for the computation of the finalisation function. The benefit is that the function is called after the value is unreachable for the last time instead of the first time. So contrary to [`finalise`](./#val-finalise) the value will never be reachable again or used again. In particular every weak pointer and ephemeron that contained this value as key or data is unset before running the finalisation function. Moreover the finalisation functions attached with [`finalise`](./#val-finalise) are always called before the finalisation functions attached with [`finalise_last`](./#val-finalise_last). - -since 4.04 -``` -val finalise_release : unit -> unit -``` -A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return. - -``` -type alarm -``` -An alarm is a piece of data that calls a user function at the end of major GC cycle. The following functions are provided to create and delete alarms. - -``` -val create_alarm : (unit -> unit) -> alarm -``` -`create_alarm f` will arrange for `f` to be called at the end of major GC cycles, not caused by `f` itself, starting with the current cycle or the next one. `f` will run on the same domain that created the alarm, until the domain exits or `delete_alarm` is called. A value of type `alarm` is returned that you can use to call `delete_alarm`. - -It is not guaranteed that the Gc alarm runs at the end of every major GC cycle, but it is guaranteed that it will run eventually. - -As an example, here is a crude way to interrupt a function if the memory consumption of the program exceeds a given `limit` in MB, suitable for use in the toplevel: - -```ocaml -let run_with_memory_limit (limit : int) (f : unit -> 'a) : 'a = - let limit_memory () = - let mem = Gc.(quick_stat ()).heap_words in - if mem / (1024 * 1024) > limit / (Sys.word_size / 8) then - raise Out_of_memory - in - let alarm = Gc.create_alarm limit_memory in - Fun.protect f ~finally:(fun () -> Gc.delete_alarm alarm ; Gc.compact ()) -``` -``` -val delete_alarm : alarm -> unit -``` -`delete_alarm a` will stop the calls to the function associated to `a`. Calling `delete_alarm a` again has no effect. - -``` -val eventlog_pause : unit -> unit -``` -deprecated Use Runtime\_events.pause instead. -``` -val eventlog_resume : unit -> unit -``` -deprecated Use Runtime\_events.resume instead. -``` -module Memprof : sig ... end -``` -`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-Make-argument-1-H.md b/docs/api/ml/melange/Stdlib-Hashtbl-Make-argument-1-H.md deleted file mode 100644 index 80efdc53c..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-Make-argument-1-H.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Parameter `Make.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-Make.md b/docs/api/ml/melange/Stdlib-Hashtbl-Make.md deleted file mode 100644 index ec79c26fe..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-Make.md +++ /dev/null @@ -1,96 +0,0 @@ - -# Module `Hashtbl.Make` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - - -## Parameters - -``` -module H : HashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type !'a t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md deleted file mode 100644 index 66eb409ed..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md +++ /dev/null @@ -1,17 +0,0 @@ - -# Parameter `MakeSeeded.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded.md b/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded.md deleted file mode 100644 index 23f14bd52..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-MakeSeeded.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Hashtbl.MakeSeeded` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-Hashtbl.md#val-randomize)). - -since 4.00 - -## Parameters - -``` -module H : SeededHashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type !'a t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-HashedType.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-HashedType.md deleted file mode 100644 index 6c2dc6de5..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-HashedType.md +++ /dev/null @@ -1,23 +0,0 @@ - -# Module type `Hashtbl.HashedType` - -The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-S.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-S.md deleted file mode 100644 index c4d7f8b23..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-S.md +++ /dev/null @@ -1,87 +0,0 @@ - -# Module type `Hashtbl.S` - -The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -type key -``` -``` -type !'a t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md deleted file mode 100644 index 63efb5650..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md +++ /dev/null @@ -1,20 +0,0 @@ - -# Module type `Hashtbl.SeededHashedType` - -The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededS.md b/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededS.md deleted file mode 100644 index da23d5c25..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl-module-type-SeededS.md +++ /dev/null @@ -1,86 +0,0 @@ - -# Module type `Hashtbl.SeededS` - -The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type key -``` -``` -type !'a t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Hashtbl.md b/docs/api/ml/melange/Stdlib-Hashtbl.md deleted file mode 100644 index cd0022e7f..000000000 --- a/docs/api/ml/melange/Stdlib-Hashtbl.md +++ /dev/null @@ -1,388 +0,0 @@ - -# Module `Stdlib.Hashtbl` - -Hash tables and hash functions. - -Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-Map.md). - -The functors [`Make`](./Stdlib-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. - -**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. - -The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. - -See [the examples section](./#examples). - -**Unsynchronized accesses** - -Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -## Generic interface - -``` -type (!'a, !'b) t -``` -The type of hash tables from type `'a` to type `'b`. - -``` -val create : ?random:bool -> int -> ('a, 'b) t -``` -`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. - -A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. - -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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. - -before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. -``` -val clear : ('a, 'b) t -> unit -``` -Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. - -``` -val reset : ('a, 'b) t -> unit -``` -Empty a hash table and shrink the size of the bucket table to its initial size. - -since 4.00 -``` -val copy : ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. - -``` -val add : ('a, 'b) t -> 'a -> 'b -> unit -``` -`Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`. - -**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) - -If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). - -``` -val find : ('a, 'b) t -> 'a -> 'b -``` -`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. - -``` -val find_opt : ('a, 'b) t -> 'a -> 'b option -``` -`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. - -since 4.05 -``` -val find_all : ('a, 'b) t -> 'a -> 'b list -``` -`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. - -``` -val mem : ('a, 'b) t -> 'a -> bool -``` -`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. - -``` -val remove : ('a, 'b) t -> 'a -> unit -``` -`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. - -``` -val replace : ('a, 'b) t -> 'a -> 'b -> unit -``` -`Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. - -``` -val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit -``` -`Hashtbl.iter f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit -``` -`Hashtbl.filter_map_inplace f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. - -Other comments for [`iter`](./#val-iter) apply as well. - -since 4.03 -``` -val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc -``` -`Hashtbl.fold f tbl init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val length : ('a, 'b) t -> int -``` -`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. - -``` -val randomize : unit -> unit -``` -After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. - -It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. - -Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. - -since 4.00 -``` -val is_randomized : unit -> bool -``` -Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. - -since 4.03 -``` -val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. - -[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. - -since 4.12 -``` -type statistics = { -``` -`num_bindings : int;` -Number of bindings present in the table. Same value as returned by [`length`](./#val-length). - -`num_buckets : int;` -Number of buckets in the table. - -`max_bucket_length : int;` -Maximal number of bindings per bucket. - -`bucket_histogram : int array;` -Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. - -``` -} -``` -since 4.00 -``` -val stats : ('a, 'b) t -> statistics -``` -`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. - -since 4.00 - -## Hash tables and Sequences - -``` -val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t -``` -Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. - -The behavior is not specified if the hash table is modified during the iteration. - -since 4.07 -``` -val to_seq_keys : ('a, _) t -> 'a Seq.t -``` -Same as `Seq.map fst (to_seq m)` - -since 4.07 -``` -val to_seq_values : (_, 'b) t -> 'b Seq.t -``` -Same as `Seq.map snd (to_seq m)` - -since 4.07 -``` -val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`add`](./#val-add) - -since 4.07 -``` -val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`replace`](./#val-replace) - -since 4.07 -``` -val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t -``` -Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. - -since 4.07 - -## Functorial interface - -The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. - -For instance, one might want to specialize a table for integer keys: - -```ocaml - module IntHash = - struct - type t = int - let equal i j = i=j - let hash i = i land max_int - end - - module IntHashtbl = Hashtbl.Make(IntHash) - - let h = IntHashtbl.create 17 in - IntHashtbl.add h 12 "hello" -``` -This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. - -Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. - -``` -module type HashedType = sig ... end -``` -The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -module type S = sig ... end -``` -The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -module Make (H : HashedType) : S with type key = H.t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - -``` -module type SeededHashedType = sig ... end -``` -The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -``` -module type SeededS = sig ... end -``` -The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -``` -module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). - - -## The polymorphic hash functions - -``` -val hash : 'a -> int -``` -`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. - -``` -val seeded_hash : int -> 'a -> int -``` -A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. - -since 4.00 -``` -val hash_param : int -> int -> 'a -> int -``` -`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. - -``` -val seeded_hash_param : int -> int -> int -> 'a -> int -``` -A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. - -since 4.00 - -## 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 - 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 -``` - -### Counting Elements - -Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. - -Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. - -```ocaml - # module Char_tbl = Hashtbl.Make(struct - type t = char - let equal = Char.equal - let hash = Hashtbl.hash - end) - - (* count distinct occurrences of chars in [seq] *) - # let count_chars (seq : char Seq.t) : _ list = - let counts = Char_tbl.create 16 in - Seq.iter - (fun c -> - let count_c = - Char_tbl.find_opt counts c - |> Option.value ~default:0 - in - Char_tbl.replace counts c (count_c + 1)) - seq; - (* turn into a list *) - Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] - |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) - val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = - - (* basic seq from a string *) - # let seq = String.to_seq "hello world, and all the camels in it!" - val seq : char Seq.t = - - # count_chars seq - - : (Char.t * int) list = - [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); - ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); - ('s', 1); ('t', 2); ('w', 1)] - - (* "abcabcabc..." *) - # let seq2 = - Seq.cycle (String.to_seq "abc") |> Seq.take 31 - val seq2 : char Seq.t = - - # String.of_seq seq2 - - : String.t = "abcabcabcabcabcabcabcabcabcabca" - - # count_chars seq2 - - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] - -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-In_channel.md b/docs/api/ml/melange/Stdlib-In_channel.md deleted file mode 100644 index 7f2f9497e..000000000 --- a/docs/api/ml/melange/Stdlib-In_channel.md +++ /dev/null @@ -1,238 +0,0 @@ - -# Module `Stdlib.In_channel` - -Input channels. - -This module provides functions for working with input channels. - -See [the example section](./#examples) below. - -since 4.14 - -## Channels - -``` -type t = in_channel -``` -The type of input channel. - -``` -type open_flag = open_flag = -``` -``` -| Open_rdonly -``` -open for reading. - -``` -| Open_wronly -``` -open for writing. - -``` -| Open_append -``` -open for appending: always write at end of file. - -``` -| Open_creat -``` -create the file if it does not exist. - -``` -| Open_trunc -``` -empty the file if it already exists. - -``` -| Open_excl -``` -fail if Open\_creat and the file already exists. - -``` -| Open_binary -``` -open in binary mode (no conversion). - -``` -| Open_text -``` -open in text mode (may perform conversions). - -``` -| Open_nonblock -``` -open in non-blocking mode. - -``` - -``` -Opening modes for [`open_gen`](./#val-open_gen). - -``` -val stdin : t -``` -The standard input for the process. - -``` -val open_bin : string -> t -``` -Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. - -``` -val open_text : string -> t -``` -Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). - -``` -val open_gen : open_flag list -> int -> string -> t -``` -`open_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. - -``` -val with_open_bin : string -> (t -> 'a) -> 'a -``` -`with_open_bin fn f` opens a channel `ic` on file `fn` and returns `f ic`. After `f` returns, either with a value or by raising an exception, `ic` is guaranteed to be closed. - -``` -val with_open_text : string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). - -``` -val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). - -``` -val close : t -> unit -``` -Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except [`close`](./#val-close), which does nothing when applied to an already closed channel. - -``` -val close_noerr : t -> unit -``` -Same as [`close`](./#val-close), but ignore all errors. - - -## Input - -``` -val input_char : t -> char option -``` -Read one character from the given input channel. Returns `None` if there are no more characters to read. - -``` -val input_byte : t -> int option -``` -Same as [`input_char`](./#val-input_char), but return the 8-bit integer representing the character. Returns `None` if the end of file was reached. - -``` -val input_line : t -> string option -``` -`input_line ic` reads characters from `ic` until a newline or the end of file is reached. Returns the string of all characters read, without the newline (if any). Returns `None` if the end of the file has been reached. In particular, this will be the case if the last line of input is empty. - -A newline is the character `\n` unless the file is open in text mode and [`Sys.win32`](./Stdlib-Sys.md#val-win32) is `true` in which case it is the sequence of characters `\r\n`. - -``` -val really_input_string : t -> int -> string option -``` -`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. Returns `None` if the end of file is reached before `len` characters have been read. - -If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. - -``` -val input_all : t -> string -``` -`input_all ic` reads all remaining data from `ic`. - -If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. - -``` -val input_lines : t -> string list -``` -`input_lines ic` reads lines using [`input_line`](./#val-input_line) until the end of file is reached. It returns the list of all lines read, in the order they were read. The newline characters that terminate lines are not included in the returned strings. Empty lines produce empty strings. - -since 5.1 - -## Advanced input - -``` -val input : t -> bytes -> int -> int -> int -``` -`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. - -Use [`really_input`](./#val-really_input) to read exactly `len` characters. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val really_input : t -> bytes -> int -> int -> unit option -``` -`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. - -Returns `None` if the end of file is reached before `len` characters have been read. - -If the same channel is read concurrently by multiple threads, the bytes read by `really_input` are not guaranteed to be contiguous. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val fold_lines : ('acc -> string -> 'acc) -> 'acc -> t -> 'acc -``` -`fold_lines f init ic` reads lines from `ic` using [`input_line`](./#val-input_line) until the end of file is reached, and successively passes each line to function `f` in the style of a fold. More precisely, if lines `l1, ..., lN` are read, `fold_lines f init ic` computes `f (... (f (f init l1) l2) ...) lN`. If `f` has no side effects, this is equivalent to `List.fold_left f init (In_channel.input_lines ic)`, but is more efficient since it does not construct the list of all lines read. - -since 5.1 - -## Seeking - -``` -val seek : t -> int64 -> unit -``` -`seek chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. - -``` -val pos : t -> int64 -``` -Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - - -## Attributes - -``` -val length : t -> int64 -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. - -``` -val set_binary_mode : t -> bool -> unit -``` -`set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input. - -`set_binary_mode ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. - -This function has no effect under operating systems that do not distinguish between text mode and binary mode. - -``` -val is_binary_mode : t -> bool -``` -`is_binary_mode ic` returns whether the channel `ic` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). - -since 5.2 -``` -val isatty : t -> bool -``` -`isatty ic` is `true` if `ic` refers to a terminal or console window, `false` otherwise. - -since 5.1 - -## Examples - -Reading the contents of a file: - -```ocaml - let read_file file = In_channel.with_open_bin file In_channel.input_all -``` -Reading a line from stdin: - -```ocaml - let user_input () = In_channel.input_line In_channel.stdin -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Int.md b/docs/api/ml/melange/Stdlib-Int.md deleted file mode 100644 index cf5344cce..000000000 --- a/docs/api/ml/melange/Stdlib-Int.md +++ /dev/null @@ -1,176 +0,0 @@ - -# Module `Stdlib.Int` - -Integer values. - -Integers are [`Sys.int_size`](./Stdlib-Sys.md#val-int_size) bits wide and use two's complement representation. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. - -since 4.08 - -## Integers - -``` -type t = int -``` -The type for integer values. - -``` -val zero : int -``` -`zero` is the integer `0`. - -``` -val one : int -``` -`one` is the integer `1`. - -``` -val minus_one : int -``` -`minus_one` is the integer `-1`. - -``` -val neg : int -> int -``` -`neg x` is `~-x`. - -``` -val add : int -> int -> int -``` -`add x y` is the addition `x + y`. - -``` -val sub : int -> int -> int -``` -`sub x y` is the subtraction `x - y`. - -``` -val mul : int -> int -> int -``` -`mul x y` is the multiplication `x * y`. - -``` -val div : int -> int -> int -``` -`div x y` is the division `x / y`. See [`Stdlib.(/)`](./Stdlib.md#val-\(/\)) for details. - -``` -val rem : int -> int -> int -``` -`rem x y` is the remainder `x mod y`. See [`Stdlib.(mod)`](./Stdlib.md#val-\(mod\)) for details. - -``` -val succ : int -> int -``` -`succ x` is `add x 1`. - -``` -val pred : int -> int -``` -`pred x` is `sub x 1`. - -``` -val abs : int -> int -``` -`abs x` is the absolute value of `x`. That is `x` if `x` is positive and `neg x` if `x` is negative. **Warning.** This may be negative if the argument is [`min_int`](./#val-min_int). - -``` -val max_int : int -``` -`max_int` is the greatest representable integer, `2``Sys.int_size - 1``-1`. - -``` -val min_int : int -``` -`min_int` is the smallest representable integer, `-2``Sys.int_size - 1`. - -``` -val logand : int -> int -> int -``` -`logand x y` is the bitwise logical and of `x` and `y`. - -``` -val logor : int -> int -> int -``` -`logor x y` is the bitwise logical or of `x` and `y`. - -``` -val logxor : int -> int -> int -``` -`logxor x y` is the bitwise logical exclusive or of `x` and `y`. - -``` -val lognot : int -> int -``` -`lognot x` is the bitwise logical negation of `x`. - -``` -val shift_left : int -> int -> int -``` -`shift_left x n` shifts `x` to the left by `n` bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). - -``` -val shift_right : int -> int -> int -``` -`shift_right x n` shifts `x` to the right by `n` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). - -``` -val shift_right_logical : int -> int -> int -``` -`shift_right x n` shifts `x` to the right by `n` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). - - -## Predicates and comparisons - -``` -val equal : int -> int -> bool -``` -`equal x y` is `true` if and only if `x = y`. - -``` -val compare : int -> int -> int -``` -`compare x y` is [`Stdlib.compare`](./Stdlib.md#val-compare)` x y` but more efficient. - -``` -val min : int -> int -> int -``` -Return the smaller of the two arguments. - -since 4.13 -``` -val max : int -> int -> int -``` -Return the greater of the two arguments. - -since 4.13 - -## Converting - -``` -val to_float : int -> float -``` -`to_float x` is `x` as a floating point number. - -``` -val of_float : float -> int -``` -`of_float x` truncates `x` to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. - -``` -val to_string : int -> string -``` -`to_string x` is the written representation of `x` in decimal. - -``` -val seeded_hash : int -> int -> int -``` -A seeded hash function for ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : int -> int -``` -An unseeded hash function for ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Int32.md b/docs/api/ml/melange/Stdlib-Int32.md deleted file mode 100644 index 0f3011b3a..000000000 --- a/docs/api/ml/melange/Stdlib-Int32.md +++ /dev/null @@ -1,237 +0,0 @@ - -# Module `Stdlib.Int32` - -32-bit integers. - -This module provides operations on the type `int32` of signed 32-bit integers. Unlike the built-in `int` type, the type `int32` is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over `int32` are taken modulo 232. - -Performance notice: values of type `int32` occupy more memory space than values of type `int`, and arithmetic operations on `int32` are generally slower than those on `int`. Use `int32` only when the application requires exact 32-bit arithmetic. - -Literals for 32-bit integers are suffixed by l: - -```ocaml - let zero: int32 = 0l - let one: int32 = 1l - let m_one: int32 = -1l -``` -``` -val zero : int32 -``` -The 32-bit integer 0. - -``` -val one : int32 -``` -The 32-bit integer 1\. - -``` -val minus_one : int32 -``` -The 32-bit integer \-1. - -``` -val neg : int32 -> int32 -``` -Unary negation. - -``` -val add : int32 -> int32 -> int32 -``` -Addition. - -``` -val sub : int32 -> int32 -> int32 -``` -Subtraction. - -``` -val mul : int32 -> int32 -> int32 -``` -Multiplication. - -``` -val div : int32 -> int32 -> int32 -``` -Integer division. This division rounds the real quotient of its arguments towards zero, as specified for [`Stdlib.(/)`](./Stdlib.md#val-\(/\)). - -raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. -``` -val unsigned_div : int32 -> int32 -> int32 -``` -Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 32-bit integers. - -since 4.08 -``` -val rem : int32 -> int32 -> int32 -``` -Integer remainder. If `y` is not zero, the result of `Int32.rem x y` satisfies the following property: `x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)`. If `y = 0`, `Int32.rem x y` raises `Division_by_zero`. - -``` -val unsigned_rem : int32 -> int32 -> int32 -``` -Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 32-bit integers. - -since 4.08 -``` -val succ : int32 -> int32 -``` -Successor. `Int32.succ x` is `Int32.add x Int32.one`. - -``` -val pred : int32 -> int32 -``` -Predecessor. `Int32.pred x` is `Int32.sub x Int32.one`. - -``` -val abs : int32 -> int32 -``` -`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. - -``` -val max_int : int32 -``` -The greatest representable 32-bit integer, 231 \- 1\. - -``` -val min_int : int32 -``` -The smallest representable 32-bit integer, \-231. - -``` -val logand : int32 -> int32 -> int32 -``` -Bitwise logical and. - -``` -val logor : int32 -> int32 -> int32 -``` -Bitwise logical or. - -``` -val logxor : int32 -> int32 -> int32 -``` -Bitwise logical exclusive or. - -``` -val lognot : int32 -> int32 -``` -Bitwise logical negation. - -``` -val shift_left : int32 -> int -> int32 -``` -`Int32.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 32`. - -``` -val shift_right : int32 -> int -> int32 -``` -`Int32.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 32`. - -``` -val shift_right_logical : int32 -> int -> int32 -``` -`Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 32`. - -``` -val of_int : int -> int32 -``` -Convert the given integer (type `int`) to a 32-bit integer (type `int32`). On 64-bit platforms, the argument is taken modulo 232. - -``` -val to_int : int32 -> int -``` -Convert the given 32-bit integer (type `int32`) to an integer (type `int`). On 32-bit platforms, the 32-bit integer is taken modulo 231, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. - -``` -val unsigned_to_int : int32 -> int option -``` -Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. - -since 4.08 -``` -val of_float : float -> int32 -``` -Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int32.min_int`](./#val-min_int), [`Int32.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. - -``` -val to_float : int32 -> float -``` -Convert the given 32-bit integer to a floating-point number. - -``` -val of_string : string -> int32 -``` -Convert the given string to a 32-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. - -The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int32.max_int+1]`. If the input exceeds [`Int32.max_int`](./#val-max_int) it is converted to the signed integer `Int32.min_int + input - Int32.max_int - 1`. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int32. -``` -val of_string_opt : string -> int32 option -``` -Same as `of_string`, but return `None` instead of raising. - -since 4.05 -``` -val to_string : int32 -> string -``` -Return the string representation of its argument, in signed decimal. - -``` -val bits_of_float : float -> int32 -``` -Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa. - -``` -val float_of_bits : int32 -> float -``` -Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`. - -``` -type t = int32 -``` -An alias for the type of 32-bit integers. - -``` -val compare : t -> t -> int -``` -The comparison function for 32-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val unsigned_compare : t -> t -> int -``` -Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 32-bit integers. - -since 4.08 -``` -val equal : t -> t -> bool -``` -The equal function for int32s. - -since 4.03 -``` -val min : t -> t -> t -``` -Return the smaller of the two arguments. - -since 4.13 -``` -val max : t -> t -> t -``` -Return the greater of the two arguments. - -since 4.13 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for 32-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for 32-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Int64.md b/docs/api/ml/melange/Stdlib-Int64.md deleted file mode 100644 index f7d334e83..000000000 --- a/docs/api/ml/melange/Stdlib-Int64.md +++ /dev/null @@ -1,257 +0,0 @@ - -# Module `Stdlib.Int64` - -64-bit integers. - -This module provides operations on the type `int64` of signed 64-bit integers. Unlike the built-in `int` type, the type `int64` is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over `int64` are taken modulo 264 - -Performance notice: values of type `int64` occupy more memory space than values of type `int`, and arithmetic operations on `int64` are generally slower than those on `int`. Use `int64` only when the application requires exact 64-bit arithmetic. - -Literals for 64-bit integers are suffixed by L: - -```ocaml - let zero: int64 = 0L - let one: int64 = 1L - let m_one: int64 = -1L -``` -``` -val zero : int64 -``` -The 64-bit integer 0. - -``` -val one : int64 -``` -The 64-bit integer 1\. - -``` -val minus_one : int64 -``` -The 64-bit integer \-1. - -``` -val neg : int64 -> int64 -``` -Unary negation. - -``` -val add : int64 -> int64 -> int64 -``` -Addition. - -``` -val sub : int64 -> int64 -> int64 -``` -Subtraction. - -``` -val mul : int64 -> int64 -> int64 -``` -Multiplication. - -``` -val div : int64 -> int64 -> int64 -``` -Integer division. - -raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/). -``` -val unsigned_div : int64 -> int64 -> int64 -``` -Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 64-bit integers. - -since 4.08 -``` -val rem : int64 -> int64 -> int64 -``` -Integer remainder. If `y` is not zero, the result of `Int64.rem x y` satisfies the following property: `x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)`. If `y = 0`, `Int64.rem x y` raises `Division_by_zero`. - -``` -val unsigned_rem : int64 -> int64 -> int64 -``` -Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 64-bit integers. - -since 4.08 -``` -val succ : int64 -> int64 -``` -Successor. `Int64.succ x` is `Int64.add x Int64.one`. - -``` -val pred : int64 -> int64 -``` -Predecessor. `Int64.pred x` is `Int64.sub x Int64.one`. - -``` -val abs : int64 -> int64 -``` -`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. - -``` -val max_int : int64 -``` -The greatest representable 64-bit integer, 263 \- 1\. - -``` -val min_int : int64 -``` -The smallest representable 64-bit integer, \-263. - -``` -val logand : int64 -> int64 -> int64 -``` -Bitwise logical and. - -``` -val logor : int64 -> int64 -> int64 -``` -Bitwise logical or. - -``` -val logxor : int64 -> int64 -> int64 -``` -Bitwise logical exclusive or. - -``` -val lognot : int64 -> int64 -``` -Bitwise logical negation. - -``` -val shift_left : int64 -> int -> int64 -``` -`Int64.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 64`. - -``` -val shift_right : int64 -> int -> int64 -``` -`Int64.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 64`. - -``` -val shift_right_logical : int64 -> int -> int64 -``` -`Int64.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 64`. - -``` -val of_int : int -> int64 -``` -Convert the given integer (type `int`) to a 64-bit integer (type `int64`). - -``` -val to_int : int64 -> int -``` -Convert the given 64-bit integer (type `int64`) to an integer (type `int`). On 64-bit platforms, the 64-bit integer is taken modulo 263, i.e. the high-order bit is lost during the conversion. On 32-bit platforms, the 64-bit integer is taken modulo 231, i.e. the top 33 bits are lost during the conversion. - -``` -val unsigned_to_int : int64 -> int option -``` -Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. - -since 4.08 -``` -val of_float : float -> int64 -``` -Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int64.min_int`](./#val-min_int), [`Int64.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. - -``` -val to_float : int64 -> float -``` -Convert the given 64-bit integer to a floating-point number. - -``` -val of_int32 : int32 -> int64 -``` -Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`). - -``` -val to_int32 : int64 -> int32 -``` -Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). The 64-bit integer is taken modulo 232, i.e. the top 32 bits are lost during the conversion. - -``` -val of_nativeint : nativeint -> int64 -``` -Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`). - -``` -val to_nativeint : int64 -> nativeint -``` -Convert the given 64-bit integer (type `int64`) to a native integer. On 32-bit platforms, the 64-bit integer is taken modulo 232. On 64-bit platforms, the conversion is exact. - -``` -val of_string : string -> int64 -``` -Convert the given string to a 64-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. - -The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int64.max_int+1]`. If the input exceeds [`Int64.max_int`](./#val-max_int) it is converted to the signed integer `Int64.min_int + input - Int64.max_int - 1`. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int64. -``` -val of_string_opt : string -> int64 option -``` -Same as `of_string`, but return `None` instead of raising. - -since 4.05 -``` -val to_string : int64 -> string -``` -Return the string representation of its argument, in decimal. - -``` -val bits_of_float : float -> int64 -``` -Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. Bit 63 of the result represents the sign of the float; bits 62 to 52 represent the (biased) exponent; bits 51 to 0 represent the mantissa. - -``` -val float_of_bits : int64 -> float -``` -Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`. - -``` -type t = int64 -``` -An alias for the type of 64-bit integers. - -``` -val compare : t -> t -> int -``` -The comparison function for 64-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int64` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val unsigned_compare : t -> t -> int -``` -Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 64-bit integers. - -since 4.08 -``` -val equal : t -> t -> bool -``` -The equal function for int64s. - -since 4.03 -``` -val min : t -> t -> t -``` -Return the smaller of the two arguments. - -since 4.13 -``` -val max : t -> t -> t -``` -Return the greater of the two arguments. - -since 4.13 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for 64-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for 64-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-LargeFile.md b/docs/api/ml/melange/Stdlib-LargeFile.md deleted file mode 100644 index b4e663dc2..000000000 --- a/docs/api/ml/melange/Stdlib-LargeFile.md +++ /dev/null @@ -1,23 +0,0 @@ - -# Module `Stdlib.LargeFile` - -Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. - -``` -val seek_out : out_channel -> int64 -> unit -``` -``` -val pos_out : out_channel -> int64 -``` -``` -val out_channel_length : out_channel -> int64 -``` -``` -val seek_in : in_channel -> int64 -> unit -``` -``` -val pos_in : in_channel -> int64 -``` -``` -val in_channel_length : in_channel -> int64 -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Lazy.md b/docs/api/ml/melange/Stdlib-Lazy.md deleted file mode 100644 index 519b7cec5..000000000 --- a/docs/api/ml/melange/Stdlib-Lazy.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Stdlib.Lazy` - -Deferred computations. - -``` -type 'a t = 'a CamlinternalLazy.t -``` -A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. The special expression syntax `lazy (expr)` makes a suspension of the computation of `expr`, without computing `expr` itself yet. "Forcing" the suspension will then compute `expr` and return its result. Matching a suspension with the special pattern syntax `lazy(pattern)` also computes the underlying expression and tries to bind it to `pattern`: - -```ocaml - let lazy_option_map f x = - match x with - | lazy (Some x) -> Some (Lazy.force f x) - | _ -> None -``` -Note: If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may be forced even outside of the case ultimately selected by the pattern matching. In the example above, the suspension `x` is always computed. - -Note: `lazy_t` is the built-in type constructor used by the compiler for the `lazy` keyword. You should not use it directly. Always use `Lazy.t` instead. - -Note: `Lazy.force` is not concurrency-safe. If you use this module with multiple fibers, systhreads or domains, then you will need to add some locks. The module however ensures memory-safety, and hence, concurrently accessing this module will not lead to a crash but the behaviour is unspecified. - -Note: if the program is compiled with the `-rectypes` option, ill-founded recursive definitions of the form `let rec x = lazy x` or `let rec x = lazy(lazy(...(lazy x)))` are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the `-rectypes` option, such ill-founded recursive definitions are rejected by the type-checker. - -``` -exception Undefined -``` -Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or when the suspension tries to force itself recursively. - -``` -val force : 'a t -> 'a -``` -`force x` forces the suspension `x` and returns its result. If `x` has already been forced, `Lazy.force x` returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. - -raises [`Undefined`](./#exception-Undefined) (see Undefined). - -## Iterators - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f x` returns a suspension that, when forced, forces `x` and applies `f` to its value. - -It is equivalent to `lazy (f (Lazy.force x))`. - -since 4.13 - -## Reasoning on already-forced suspensions - -``` -val is_val : 'a t -> bool -``` -`is_val x` returns `true` if `x` has already been forced and did not raise an exception. - -since 4.00 -``` -val from_val : 'a -> 'a t -``` -`from_val v` evaluates `v` first (as any function would) and returns an already-forced suspension of its result. It is the same as `let x = v in lazy x`, but uses dynamic tests to optimize suspension creation in some cases. - -since 4.00 -``` -val map_val : ('a -> 'b) -> 'a t -> 'b t -``` -`map_val f x` applies `f` directly if `x` is already forced, otherwise it behaves as `map f x`. - -When `x` is already forced, this behavior saves the construction of a suspension, but on the other hand it performs more work eagerly that may not be useful if you never force the function result. - -If `f` raises an exception, it will be raised immediately when `is_val x`, or raised only when forcing the thunk otherwise. - -If `map_val f x` does not raise an exception, then `is_val (map_val f x)` is equal to `is_val x`. - -since 4.13 - -## Advanced - -The following definitions are for advanced uses only; they require familiarity with the lazy compilation scheme to be used appropriately. - -``` -val from_fun : (unit -> 'a) -> 'a t -``` -`from_fun f` is the same as `lazy (f ())` but slightly more efficient. - -It should only be used if the function `f` is already defined. In particular it is always less efficient to write `from_fun (fun () -> expr)` than `lazy expr`. - -since 4.00 -``` -val force_val : 'a t -> 'a -``` -`force_val x` forces the suspension `x` and returns its result. If `x` has already been forced, `force_val x` returns the same value again without recomputing it. - -If the computation of `x` raises an exception, it is unspecified whether `force_val x` raises the same exception or [`Undefined`](./#exception-Undefined). - -raises [`Undefined`](./#exception-Undefined) if the forcing of x tries to force x itself recursively. -raises [`Undefined`](./#exception-Undefined) (see Undefined). \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Lexing.md b/docs/api/ml/melange/Stdlib-Lexing.md deleted file mode 100644 index 44ca6045c..000000000 --- a/docs/api/ml/melange/Stdlib-Lexing.md +++ /dev/null @@ -1,136 +0,0 @@ - -# Module `Stdlib.Lexing` - -The run-time library for lexers generated by `ocamllex`. - - -## Positions - -``` -type position = { -``` -`pos_fname : string;` -`pos_lnum : int;` -`pos_bol : int;` -`pos_cnum : int;` -``` -} -``` -A value of type `position` describes a point in a source file. `pos_fname` is the file name; `pos_lnum` is the line number; `pos_bol` is the offset of the beginning of the line (number of characters between the beginning of the lexbuf and the beginning of the line); `pos_cnum` is the offset of the position (number of characters between the beginning of the lexbuf and the position). The difference between `pos_cnum` and `pos_bol` is the character offset within the line (i.e. the column number, assuming each character is one column wide). - -See the documentation of type `lexbuf` for information about how the lexing engine will manage positions. - -``` -val dummy_pos : position -``` -A value of type `position`, guaranteed to be different from any valid position. - - -## Lexer buffers - -``` -type lexbuf = { -``` -`refill_buff : lexbuf -> unit;` -`mutable lex_buffer : bytes;` -`mutable lex_buffer_len : int;` -`mutable lex_abs_pos : int;` -`mutable lex_start_pos : int;` -`mutable lex_curr_pos : int;` -`mutable lex_last_pos : int;` -`mutable lex_last_action : int;` -`mutable lex_eof_reached : bool;` -`mutable lex_mem : int array;` -`mutable lex_start_p : position;` -`mutable lex_curr_p : position;` -``` -} -``` -The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input. - -Lexers can optionally maintain the `lex_curr_p` and `lex_start_p` position fields. This "position tracking" mode is the default, and it corresponds to passing `~with_position:true` to functions that create lexer buffers. In this mode, the lexing engine and lexer actions are co-responsible for properly updating the position fields, as described in the next paragraph. When the mode is explicitly disabled (with `~with_position:false`), the lexing engine will not touch the position fields and the lexer actions should be careful not to do it either; the `lex_curr_p` and `lex_start_p` field will then always hold the `dummy_pos` invalid position. Not tracking positions avoids allocations and memory writes and can significantly improve the performance of the lexer in contexts where `lex_start_p` and `lex_curr_p` are not needed. - -Position tracking mode works as follows. At each token, the lexing engine will copy `lex_curr_p` to `lex_start_p`, then change the `pos_cnum` field of `lex_curr_p` by updating it with the number of characters read since the start of the `lexbuf`. The other fields are left unchanged by the lexing engine. In order to keep them accurate, they must be initialised before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end of line \-- see also `new_line`). - -``` -val from_channel : ?with_positions:bool -> in_channel -> lexbuf -``` -Create a lexer buffer on the given input channel. `Lexing.from_channel inchan` returns a lexer buffer which reads from the input channel `inchan`, at the current reading position. - -``` -val from_string : ?with_positions:bool -> string -> lexbuf -``` -Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached. - -``` -val from_function : ?with_positions:bool -> (bytes -> int -> int) -> lexbuf -``` -Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a byte sequence `s` and a byte count `n`. The function should put `n` bytes or fewer in `s`, starting at index 0, and return the number of bytes provided. A return value of 0 means end of input. - -``` -val set_position : lexbuf -> position -> unit -``` -Set the initial tracked input position for `lexbuf` to a custom value. Ignores `pos_fname`. See [`set_filename`](./#val-set_filename) for changing this field. - -since 4.11 -``` -val set_filename : lexbuf -> string -> unit -``` -Set filename in the initial tracked position to `file` in `lexbuf`. - -since 4.11 -``` -val with_positions : lexbuf -> bool -``` -Tell whether the lexer buffer keeps track of position fields `lex_curr_p` / `lex_start_p`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`). - -When `with_positions` is `false`, lexer actions should not modify position fields. Doing it nevertheless could re-enable the `with_position` mode and degrade performances. - - -## Functions for lexer semantic actions - -The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument `lexbuf`, which, in the code generated by `ocamllex`, is bound to the lexer buffer passed to the parsing function. - -``` -val lexeme : lexbuf -> string -``` -`Lexing.lexeme lexbuf` returns the string matched by the regular expression. - -``` -val lexeme_char : lexbuf -> int -> char -``` -`Lexing.lexeme_char lexbuf i` returns character number `i` in the matched string. - -``` -val lexeme_start : lexbuf -> int -``` -`Lexing.lexeme_start lexbuf` returns the offset in the input stream of the first character of the matched string. The first character of the stream has offset 0. - -``` -val lexeme_end : lexbuf -> int -``` -`Lexing.lexeme_end lexbuf` returns the offset in the input stream of the character following the last character of the matched string. The first character of the stream has offset 0. - -``` -val lexeme_start_p : lexbuf -> position -``` -Like `lexeme_start`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. - -``` -val lexeme_end_p : lexbuf -> position -``` -Like `lexeme_end`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. - -``` -val new_line : lexbuf -> unit -``` -Update the `lex_curr_p` field of the lexbuf to reflect the start of a new line. You can call this function in the semantic action of the rule that matches the end-of-line character. The function does nothing when position tracking is disabled. - -since 3.11 - -## Miscellaneous functions - -``` -val flush_input : lexbuf -> unit -``` -Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill. diff --git a/docs/api/ml/melange/Stdlib-List.md b/docs/api/ml/melange/Stdlib-List.md deleted file mode 100644 index 448c79785..000000000 --- a/docs/api/ml/melange/Stdlib-List.md +++ /dev/null @@ -1,482 +0,0 @@ - -# Module `Stdlib.List` - -List operations. - -Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. - -The above considerations can usually be ignored if your lists are not longer than about 10000 elements. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a list = -``` -``` -| [] -``` -``` -| :: of 'a * 'a list -``` -``` - -``` -An alias for the type of lists. - -``` -val length : 'a list -> int -``` -Return the length (number of elements) of the given list. - -``` -val compare_lengths : 'a list -> 'b list -> int -``` -Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. - -since 4.05 -``` -val compare_length_with : 'a list -> int -> int -``` -Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. - -since 4.05 -``` -val is_empty : 'a list -> bool -``` -`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. - -since 5.1 -``` -val cons : 'a -> 'a list -> 'a list -``` -`cons x xs` is `x :: xs` - -since 4.03 (4.05 in ListLabels) -``` -val hd : 'a list -> 'a -``` -Return the first element of the given list. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val tl : 'a list -> 'a list -``` -Return the given list without its first element. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val nth : 'a list -> int -> 'a -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -``` -val nth_opt : 'a list -> int -> 'a option -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.05 -``` -val rev : 'a list -> 'a list -``` -List reversal. - -``` -val init : int -> (int -> 'a) -> 'a list -``` -`init len f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. -since 4.06 -``` -val append : 'a list -> 'a list -> 'a list -``` -`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. - -since 5.1 this function is tail-recursive. -``` -val rev_append : 'a list -> 'a list -> 'a list -``` -`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. - -``` -val concat : 'a list list -> 'a list -``` -Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). - -``` -val flatten : 'a list list -> 'a list -``` -Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). - - -## Comparison - -``` -val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool -``` -`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. - -Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. - -since 4.12 -``` -val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int -``` -`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): - -- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` -- the empty list `[]` is strictly smaller than non-empty lists -Note: the `cmp` function will be called even if the lists have different lengths. - -since 4.12 - -## Iterators - -``` -val iter : ('a -> unit) -> 'a list -> unit -``` -`iter f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. - -``` -val iteri : (int -> 'a -> unit) -> 'a list -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val map : ('a -> 'b) -> 'a list -> 'b list -``` -`map f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. - -``` -val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val rev_map : ('a -> 'b) -> 'a list -> 'b list -``` -`rev_map f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. - -``` -val filter_map : ('a -> 'b option) -> 'a list -> 'b list -``` -`filter_map f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. - -since 4.08 -``` -val concat_map : ('a -> 'b list) -> 'a list -> 'b list -``` -`concat_map f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. - -since 4.10 -``` -val fold_left_map : - ('acc -> 'a -> 'acc * 'b) -> - 'acc -> - 'a list -> - 'acc * 'b list -``` -`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. - -since 4.11 -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc -``` -`fold_left f init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. - -``` -val fold_right : ('a -> 'acc -> 'acc) -> 'a list -> 'acc -> 'acc -``` -`fold_right f [a1; ...; an] init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. - - -## Iterators on two lists - -``` -val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit -``` -`iter2 f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`map2 f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`rev_map2 f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. - -``` -val fold_left2 : - ('acc -> 'a -> 'b -> 'acc) -> - 'acc -> - 'a list -> - 'b list -> - 'acc -``` -`fold_left2 f init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val fold_right2 : - ('a -> 'b -> 'acc -> 'acc) -> - 'a list -> - 'b list -> - 'acc -> - 'acc -``` -`fold_right2 f [a1; ...; an] [b1; ...; bn] init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. - -## List scanning - -``` -val for_all : ('a -> bool) -> 'a list -> bool -``` -`for_all f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. - -``` -val exists : ('a -> bool) -> 'a list -> bool -``` -`exists f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. - -``` -val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val mem : 'a -> 'a list -> bool -``` -`mem a set` is true if and only if `a` is equal to an element of `set`. - -``` -val memq : 'a -> 'a list -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. - - -## List searching - -``` -val find : ('a -> bool) -> 'a list -> 'a -``` -`find f l` returns the first element of the list `l` that satisfies the predicate `f`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. -``` -val find_opt : ('a -> bool) -> 'a list -> 'a option -``` -`find f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. - -since 4.05 -``` -val find_index : ('a -> bool) -> 'a list -> int option -``` -`find_index f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : ('a -> 'b option) -> 'a list -> 'b option -``` -`find_map f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.10 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a list -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 -``` -val filter : ('a -> bool) -> 'a list -> 'a list -``` -`filter f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. - -``` -val find_all : ('a -> bool) -> 'a list -> 'a list -``` -`find_all` is another name for [`filter`](./#val-filter). - -``` -val filteri : (int -> 'a -> bool) -> 'a list -> 'a list -``` -Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.11 - -## List manipulation - -``` -val take : int -> 'a list -> 'a list -``` -`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val drop : int -> 'a list -> 'a list -``` -`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val take_while : ('a -> bool) -> 'a list -> 'a list -``` -`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. - -since 5.3 -``` -val drop_while : ('a -> bool) -> 'a list -> 'a list -``` -`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. - -since 5.3 -``` -val partition : ('a -> bool) -> 'a list -> 'a list * 'a list -``` -`partition f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. - -``` -val partition_map : ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list -``` -`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: - -- if `f x` is `Left y1`, then `y1` is in `l1`, and -- if `f x` is `Right y2`, then `y2` is in `l2`. -The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. - -In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. - -since 4.12 - -## Association lists - -``` -val assoc : 'a -> ('a * 'b) list -> 'b -``` -`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. -``` -val assoc_opt : 'a -> ('a * 'b) list -> 'b option -``` -`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. - -since 4.05 -``` -val assq : 'a -> ('a * 'b) list -> 'b -``` -Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val assq_opt : 'a -> ('a * 'b) list -> 'b option -``` -Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. - -since 4.05 -``` -val mem_assoc : 'a -> ('a * 'b) list -> bool -``` -Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. - -``` -val mem_assq : 'a -> ('a * 'b) list -> bool -``` -Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. - -``` -val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. - - -## Lists of pairs - -``` -val split : ('a * 'b) list -> 'a list * 'b list -``` -Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. - -``` -val combine : 'a list -> 'b list -> ('a * 'b) list -``` -Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. - -## Sorting - -``` -val sort : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but also remove duplicates. - -since 4.02 (4.03 in ListLabels) -``` -val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list -``` -Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). - - -## Lists and Sequences - -``` -val to_seq : 'a list -> 'a Seq.t -``` -Iterate on the list. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a list -``` -Create a list from a sequence. - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-ListLabels.md b/docs/api/ml/melange/Stdlib-ListLabels.md deleted file mode 100644 index 03b11df1f..000000000 --- a/docs/api/ml/melange/Stdlib-ListLabels.md +++ /dev/null @@ -1,482 +0,0 @@ - -# Module `Stdlib.ListLabels` - -List operations. - -Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. - -The above considerations can usually be ignored if your lists are not longer than about 10000 elements. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a list = -``` -``` -| [] -``` -``` -| :: of 'a * 'a list -``` -``` - -``` -An alias for the type of lists. - -``` -val length : 'a list -> int -``` -Return the length (number of elements) of the given list. - -``` -val compare_lengths : 'a list -> 'b list -> int -``` -Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. - -since 4.05 -``` -val compare_length_with : 'a list -> len:int -> int -``` -Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. - -since 4.05 -``` -val is_empty : 'a list -> bool -``` -`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. - -since 5.1 -``` -val cons : 'a -> 'a list -> 'a list -``` -`cons x xs` is `x :: xs` - -since 4.03 (4.05 in ListLabels) -``` -val hd : 'a list -> 'a -``` -Return the first element of the given list. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val tl : 'a list -> 'a list -``` -Return the given list without its first element. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val nth : 'a list -> int -> 'a -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -``` -val nth_opt : 'a list -> int -> 'a option -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.05 -``` -val rev : 'a list -> 'a list -``` -List reversal. - -``` -val init : len:int -> f:(int -> 'a) -> 'a list -``` -`init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. -since 4.06 -``` -val append : 'a list -> 'a list -> 'a list -``` -`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. - -since 5.1 this function is tail-recursive. -``` -val rev_append : 'a list -> 'a list -> 'a list -``` -`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. - -``` -val concat : 'a list list -> 'a list -``` -Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). - -``` -val flatten : 'a list list -> 'a list -``` -Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). - - -## Comparison - -``` -val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool -``` -`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. - -Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. - -since 4.12 -``` -val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int -``` -`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): - -- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` -- the empty list `[]` is strictly smaller than non-empty lists -Note: the `cmp` function will be called even if the lists have different lengths. - -since 4.12 - -## Iterators - -``` -val iter : f:('a -> unit) -> 'a list -> unit -``` -`iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. - -``` -val iteri : f:(int -> 'a -> unit) -> 'a list -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val map : f:('a -> 'b) -> 'a list -> 'b list -``` -`map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. - -``` -val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val rev_map : f:('a -> 'b) -> 'a list -> 'b list -``` -`rev_map ~f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. - -``` -val filter_map : f:('a -> 'b option) -> 'a list -> 'b list -``` -`filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. - -since 4.08 -``` -val concat_map : f:('a -> 'b list) -> 'a list -> 'b list -``` -`concat_map ~f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. - -since 4.10 -``` -val fold_left_map : - f:('acc -> 'a -> 'acc * 'b) -> - init:'acc -> - 'a list -> - 'acc * 'b list -``` -`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. - -since 4.11 -``` -val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc -``` -`fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. - -``` -val fold_right : f:('a -> 'acc -> 'acc) -> 'a list -> init:'acc -> 'acc -``` -`fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. - - -## Iterators on two lists - -``` -val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit -``` -`iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`rev_map2 ~f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. - -``` -val fold_left2 : - f:('acc -> 'a -> 'b -> 'acc) -> - init:'acc -> - 'a list -> - 'b list -> - 'acc -``` -`fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val fold_right2 : - f:('a -> 'b -> 'acc -> 'acc) -> - 'a list -> - 'b list -> - init:'acc -> - 'acc -``` -`fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. - -## List scanning - -``` -val for_all : f:('a -> bool) -> 'a list -> bool -``` -`for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. - -``` -val exists : f:('a -> bool) -> 'a list -> bool -``` -`exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. - -``` -val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val mem : 'a -> set:'a list -> bool -``` -`mem a ~set` is true if and only if `a` is equal to an element of `set`. - -``` -val memq : 'a -> set:'a list -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. - - -## List searching - -``` -val find : f:('a -> bool) -> 'a list -> 'a -``` -`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. -``` -val find_opt : f:('a -> bool) -> 'a list -> 'a option -``` -`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. - -since 4.05 -``` -val find_index : f:('a -> bool) -> 'a list -> int option -``` -`find_index ~f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : f:('a -> 'b option) -> 'a list -> 'b option -``` -`find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.10 -``` -val find_mapi : f:(int -> 'a -> 'b option) -> 'a list -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 -``` -val filter : f:('a -> bool) -> 'a list -> 'a list -``` -`filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. - -``` -val find_all : f:('a -> bool) -> 'a list -> 'a list -``` -`find_all` is another name for [`filter`](./#val-filter). - -``` -val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list -``` -Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.11 - -## List manipulation - -``` -val take : int -> 'a list -> 'a list -``` -`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val drop : int -> 'a list -> 'a list -``` -`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val take_while : f:('a -> bool) -> 'a list -> 'a list -``` -`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. - -since 5.3 -``` -val drop_while : f:('a -> bool) -> 'a list -> 'a list -``` -`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. - -since 5.3 -``` -val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list -``` -`partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. - -``` -val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list -``` -`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: - -- if `f x` is `Left y1`, then `y1` is in `l1`, and -- if `f x` is `Right y2`, then `y2` is in `l2`. -The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. - -In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. - -since 4.12 - -## Association lists - -``` -val assoc : 'a -> ('a * 'b) list -> 'b -``` -`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. -``` -val assoc_opt : 'a -> ('a * 'b) list -> 'b option -``` -`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. - -since 4.05 -``` -val assq : 'a -> ('a * 'b) list -> 'b -``` -Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val assq_opt : 'a -> ('a * 'b) list -> 'b option -``` -Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. - -since 4.05 -``` -val mem_assoc : 'a -> map:('a * 'b) list -> bool -``` -Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. - -``` -val mem_assq : 'a -> map:('a * 'b) list -> bool -``` -Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. - -``` -val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. - - -## Lists of pairs - -``` -val split : ('a * 'b) list -> 'a list * 'b list -``` -Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. - -``` -val combine : 'a list -> 'b list -> ('a * 'b) list -``` -Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. - -## Sorting - -``` -val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but also remove duplicates. - -since 4.02 (4.03 in ListLabels) -``` -val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list -``` -Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). - - -## Lists and Sequences - -``` -val to_seq : 'a list -> 'a Seq.t -``` -Iterate on the list. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a list -``` -Create a list from a sequence. - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Map-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-Map-Make-argument-1-Ord.md deleted file mode 100644 index d02ffc06f..000000000 --- a/docs/api/ml/melange/Stdlib-Map-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-Map-Make.md b/docs/api/ml/melange/Stdlib-Map-Make.md deleted file mode 100644 index ce73f7b9a..000000000 --- a/docs/api/ml/melange/Stdlib-Map-Make.md +++ /dev/null @@ -1,315 +0,0 @@ - -# Module `Map.Make` - -Functor building an implementation of the map structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Maps - -``` -type key = Ord.t -``` -The type of the map keys. - -``` -type !+'a t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key -> 'a -> 'a t -> 'a t -``` -`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key -> 'a -> 'a list t -> 'a list t -``` -`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key -> ('a option -> 'a option) -> 'a t -> 'a t -``` -`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - (key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : (key -> bool) -> 'a t -> key * 'a -``` -`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : (key -> bool) -> 'a t -> key * 'a -``` -`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : (key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : (key -> 'a -> bool) -> 'a t -> bool -``` -`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : (key -> 'a -> bool) -> 'a t -> bool -``` -`exists f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Map-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-Map-module-type-OrderedType.md deleted file mode 100644 index 269a6a025..000000000 --- a/docs/api/ml/melange/Stdlib-Map-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Map.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-Map-Make.md). - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-Map-module-type-S.md b/docs/api/ml/melange/Stdlib-Map-module-type-S.md deleted file mode 100644 index 849b1ff51..000000000 --- a/docs/api/ml/melange/Stdlib-Map-module-type-S.md +++ /dev/null @@ -1,306 +0,0 @@ - -# Module type `Map.S` - -Output signature of the functor [`Make`](./Stdlib-Map-Make.md). - - -## Maps - -``` -type key -``` -The type of the map keys. - -``` -type !+'a t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key -> 'a -> 'a t -> 'a t -``` -`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key -> 'a -> 'a list t -> 'a list t -``` -`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key -> ('a option -> 'a option) -> 'a t -> 'a t -``` -`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - (key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-Map-Make.md). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : (key -> bool) -> 'a t -> key * 'a -``` -`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : (key -> bool) -> 'a t -> key * 'a -``` -`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : (key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : (key -> 'a -> bool) -> 'a t -> bool -``` -`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : (key -> 'a -> bool) -> 'a t -> bool -``` -`exists f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Map.md b/docs/api/ml/melange/Stdlib-Map.md deleted file mode 100644 index e91aa6845..000000000 --- a/docs/api/ml/melange/Stdlib-Map.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `Stdlib.Map` - -Association tables over ordered types. - -This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For instance: - -```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") -``` -This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-Map-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-Map-Make.md). - -``` -module Make (Ord : OrderedType) : S with type key = Ord.t -``` -Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/ml/melange/Stdlib-Marshal.md b/docs/api/ml/melange/Stdlib-Marshal.md deleted file mode 100644 index b2619652a..000000000 --- a/docs/api/ml/melange/Stdlib-Marshal.md +++ /dev/null @@ -1,106 +0,0 @@ - -# Module `Stdlib.Marshal` - -Marshaling of data structures. - -This module provides functions to encode arbitrary data structures as sequences of bytes, which can then be written on a file or sent over a pipe or network connection. The bytes can then be read back later, possibly in another process, and decoded back into a data structure. The format for the byte sequences is compatible across all machines for a given version of OCaml. - -Warning: marshaling is currently not type-safe. The type of marshaled data is not transmitted along the value of the data, making it impossible to check that the data read back possesses the type expected by the context. In particular, the result type of the `Marshal.from_*` functions is given as `'a`, but this is misleading: the returned OCaml value does not possess type `'a` for all `'a`; it has one, unique type which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax: - -- `(Marshal.from_channel chan : type)`. Anything can happen at run-time if the object in the file does not belong to the given type. -Values of extensible variant types, for example exceptions (of extensible type `exn`), returned by the unmarshaller should not be pattern-matched over through `match ... with` or `try ... with`, because unmarshalling does not preserve the information required for matching their constructors. Structural equalities with other extensible variant values does not work either. Most other uses such as Printexc.to\_string, will still work as expected. - -The representation of marshaled values is not human-readable, and uses bytes that are not printable characters. Therefore, input and output channels used in conjunction with `Marshal.to_channel` and `Marshal.from_channel` must be opened in binary mode, using e.g. `open_out_bin` or `open_in_bin`; channels opened in text mode will cause unmarshaling errors on platforms where text channels behave differently than binary channels, e.g. Windows. - -``` -type extern_flags = -``` -``` -| No_sharing -``` -Don't preserve sharing - -``` -| Closures -``` -Send function closures - -``` -| Compat_32 -``` -Ensure 32-bit compatibility - -``` - -``` -The flags to the `Marshal.to_*` functions below. - -``` -val to_channel : out_channel -> 'a -> extern_flags list -> unit -``` -`Marshal.to_channel chan v flags` writes the representation of `v` on channel `chan`. The `flags` argument is a possibly empty list of flags that governs the marshaling behavior with respect to sharing, functional values, and compatibility between 32- and 64-bit platforms. - -If `flags` does not contain `Marshal.No_sharing`, circularities and sharing inside the value `v` are detected and preserved in the sequence of bytes produced. In particular, this guarantees that marshaling always terminates. Sharing between values marshaled by successive calls to `Marshal.to_channel` is neither detected nor preserved, though. If `flags` contains `Marshal.No_sharing`, sharing is ignored. This results in faster marshaling if `v` contains no shared substructures, but may cause slower marshaling and larger byte representations if `v` actually contains sharing, or even non-termination if `v` contains cycles. - -If `flags` does not contain `Marshal.Closures`, marshaling fails when it encounters a functional value inside `v`: only 'pure' data structures, containing neither functions nor objects, can safely be transmitted between different programs. If `flags` contains `Marshal.Closures`, functional values will be marshaled as a the position in the code of the program together with the values corresponding to the free variables captured in the closure. In this case, the output of marshaling can only be read back in processes that run exactly the same program, with exactly the same compiled code. (This is checked at un-marshaling time, using an MD5 digest of the code transmitted along with the code position.) - -The exact definition of which free variables are captured in a closure is not specified and can vary between bytecode and native code (and according to optimization flags). In particular, a function value accessing a global reference may or may not include the reference in its closure. If it does, unmarshaling the corresponding closure will create a new reference, different from the global one. - -If `flags` contains `Marshal.Compat_32`, marshaling fails when it encounters an integer value outside the range `-2``30`, `2``30``-1` of integers that are representable on a 32-bit platform. This ensures that marshaled data generated on a 64-bit platform can be safely read back on a 32-bit platform. If `flags` does not contain `Marshal.Compat_32`, integer values outside the range `-2``30`, `2``30``-1` are marshaled, and can be read back on a 64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit platform. The `Mashal.Compat_32` flag only matters when marshaling is performed on a 64-bit platform; it has no effect if marshaling is performed on a 32-bit platform. - -raises [`Failure`](./Stdlib.md#exception-Failure) if chan is not in binary mode. -``` -val to_bytes : 'a -> extern_flags list -> bytes -``` -`Marshal.to_bytes v flags` returns a byte sequence containing the representation of `v`. The `flags` argument has the same meaning as for [`Marshal.to_channel`](./#val-to_channel). - -since 4.02 -``` -val to_string : 'a -> extern_flags list -> string -``` -Same as `to_bytes` but return the result as a string instead of a byte sequence. - -``` -val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int -``` -`Marshal.to_buffer buff ofs len v flags` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. It returns the number of bytes actually written to the sequence. If the byte representation of `v` does not fit in `len` characters, the exception `Failure` is raised. - -``` -val from_channel : in_channel -> 'a -``` -`Marshal.from_channel chan` reads from channel `chan` the byte representation of a structured value, as produced by one of the `Marshal.to_*` functions, and reconstructs and returns the corresponding value. - -raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if chan is already at the end of the file. -raises [`Failure`](./Stdlib.md#exception-Failure) if the end of the file is reached during unmarshalling itself or if chan is not in binary mode. -``` -val from_bytes : bytes -> int -> 'a -``` -`Marshal.from_bytes buff ofs` unmarshals a structured value like [`Marshal.from_channel`](./#val-from_channel) does, except that the byte representation is not read from a channel, but taken from the byte sequence `buff`, starting at position `ofs`. The byte sequence is not mutated. - -since 4.02 -``` -val from_string : string -> int -> 'a -``` -Same as `from_bytes` but take a string as argument instead of a byte sequence. - -``` -val header_size : int -``` -The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header. [`Marshal.header_size`](./#val-header_size) is the size, in bytes, of the header. [`Marshal.data_size`](./#val-data_size)` buff ofs` is the size, in bytes, of the data part, assuming a valid header is stored in `buff` starting at position `ofs`. Finally, [`Marshal.total_size`](./#val-total_size) `buff ofs` is the total size, in bytes, of the marshaled value. Both [`Marshal.data_size`](./#val-data_size) and [`Marshal.total_size`](./#val-total_size) raise `Failure` if `buff`, `ofs` does not contain a valid header. - -To read the byte representation of a marshaled value into a byte sequence, the program needs to read first [`Marshal.header_size`](./#val-header_size) bytes into the sequence, then determine the length of the remainder of the representation using [`Marshal.data_size`](./#val-data_size), make sure the sequence is large enough to hold the remaining data, then read it, and finally call [`Marshal.from_bytes`](./#val-from_bytes) to unmarshal the value. - -``` -val data_size : bytes -> int -> int -``` -See [`Marshal.header_size`](./#val-header_size). - -``` -val total_size : bytes -> int -> int -``` -See [`Marshal.header_size`](./#val-header_size). - - -## Marshal and domain safety - -Care must be taken when marshaling a mutable value that may be modified by a different domain. Mutating a value that is being marshaled (i.e., turned into a sequence of bytes) is a programming error and might result in surprising values (when unmarshaling) due to tearing, since marshaling involves byte-per-byte copy. diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md deleted file mode 100644 index 80efdc53c..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Parameter `Make.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make.md deleted file mode 100644 index 3743681ec..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-Make.md +++ /dev/null @@ -1,96 +0,0 @@ - -# Module `Hashtbl.Make` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - - -## Parameters - -``` -module H : HashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type 'a t = 'a Hashtbl.Make(H).t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md deleted file mode 100644 index d47afa082..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md +++ /dev/null @@ -1,17 +0,0 @@ - -# Parameter `MakeSeeded.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md deleted file mode 100644 index 3fe6e44f2..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Hashtbl.MakeSeeded` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-MoreLabels-Hashtbl.md#val-randomize)). - -since 4.00 - -## Parameters - -``` -module H : SeededHashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type 'a t = 'a Hashtbl.MakeSeeded(H).t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md deleted file mode 100644 index b8aa185ce..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md +++ /dev/null @@ -1,23 +0,0 @@ - -# Module type `Hashtbl.HashedType` - -The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md deleted file mode 100644 index 9843ac29b..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md +++ /dev/null @@ -1,87 +0,0 @@ - -# Module type `Hashtbl.S` - -The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -type key -``` -``` -type !'a t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md deleted file mode 100644 index 09e30086f..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md +++ /dev/null @@ -1,20 +0,0 @@ - -# Module type `Hashtbl.SeededHashedType` - -The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md deleted file mode 100644 index 909c707c6..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md +++ /dev/null @@ -1,86 +0,0 @@ - -# Module type `Hashtbl.SeededS` - -The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type key -``` -``` -type !'a t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl.md b/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl.md deleted file mode 100644 index 9a4b5177e..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Hashtbl.md +++ /dev/null @@ -1,399 +0,0 @@ - -# Module `MoreLabels.Hashtbl` - -Hash tables and hash functions. - -Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-MoreLabels-Map.md). - -The functors [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. - -**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. - -The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. - -See [the examples section](./#examples). - -**Unsynchronized accesses** - -Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -## Generic interface - -``` -type (!'a, !'b) t = ('a, 'b) Hashtbl.t -``` -The type of hash tables from type `'a` to type `'b`. - -``` -val create : ?random:bool -> int -> ('a, 'b) t -``` -`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. - -A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. - -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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. - -before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. -``` -val clear : ('a, 'b) t -> unit -``` -Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. - -``` -val reset : ('a, 'b) t -> unit -``` -Empty a hash table and shrink the size of the bucket table to its initial size. - -since 4.00 -``` -val copy : ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. - -``` -val add : ('a, 'b) t -> key:'a -> data:'b -> unit -``` -`Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`. - -**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) - -If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). - -``` -val find : ('a, 'b) t -> 'a -> 'b -``` -`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. - -``` -val find_opt : ('a, 'b) t -> 'a -> 'b option -``` -`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. - -since 4.05 -``` -val find_all : ('a, 'b) t -> 'a -> 'b list -``` -`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. - -``` -val mem : ('a, 'b) t -> 'a -> bool -``` -`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. - -``` -val remove : ('a, 'b) t -> 'a -> unit -``` -`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. - -``` -val replace : ('a, 'b) t -> key:'a -> data:'b -> unit -``` -`Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. - -``` -val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit -``` -`Hashtbl.iter ~f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val filter_map_inplace : - f:(key:'a -> data:'b -> 'b option) -> - ('a, 'b) t -> - unit -``` -`Hashtbl.filter_map_inplace ~f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. - -Other comments for [`iter`](./#val-iter) apply as well. - -since 4.03 -``` -val fold : - f:(key:'a -> data:'b -> 'acc -> 'acc) -> - ('a, 'b) t -> - init:'acc -> - 'acc -``` -`Hashtbl.fold ~f tbl ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val length : ('a, 'b) t -> int -``` -`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. - -``` -val randomize : unit -> unit -``` -After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. - -It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. - -Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. - -since 4.00 -``` -val is_randomized : unit -> bool -``` -Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. - -since 4.03 -``` -val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. - -[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. - -since 4.12 -``` -type statistics = Hashtbl.statistics = { -``` -`num_bindings : int;` -Number of bindings present in the table. Same value as returned by [`length`](./#val-length). - -`num_buckets : int;` -Number of buckets in the table. - -`max_bucket_length : int;` -Maximal number of bindings per bucket. - -`bucket_histogram : int array;` -Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. - -``` -} -``` -since 4.00 -``` -val stats : ('a, 'b) t -> statistics -``` -`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. - -since 4.00 - -## Hash tables and Sequences - -``` -val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t -``` -Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. - -The behavior is not specified if the hash table is modified during the iteration. - -since 4.07 -``` -val to_seq_keys : ('a, _) t -> 'a Seq.t -``` -Same as `Seq.map fst (to_seq m)` - -since 4.07 -``` -val to_seq_values : (_, 'b) t -> 'b Seq.t -``` -Same as `Seq.map snd (to_seq m)` - -since 4.07 -``` -val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`add`](./#val-add) - -since 4.07 -``` -val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`replace`](./#val-replace) - -since 4.07 -``` -val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t -``` -Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. - -since 4.07 - -## Functorial interface - -The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. - -For instance, one might want to specialize a table for integer keys: - -```ocaml - module IntHash = - struct - type t = int - let equal i j = i=j - let hash i = i land max_int - end - - module IntHashtbl = Hashtbl.Make(IntHash) - - let h = IntHashtbl.create 17 in - IntHashtbl.add h 12 "hello" -``` -This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. - -Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. - -``` -module type HashedType = sig ... end -``` -The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -module type S = sig ... end -``` -The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -module Make - (H : HashedType) : - S with type key = H.t and type 'a t = 'a Hashtbl.Make(H).t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - -``` -module type SeededHashedType = sig ... end -``` -The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -``` -module type SeededS = sig ... end -``` -The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -``` -module MakeSeeded - (H : SeededHashedType) : - SeededS with type key = H.t and type 'a t = 'a Hashtbl.MakeSeeded(H).t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). - - -## The polymorphic hash functions - -``` -val hash : 'a -> int -``` -`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. - -``` -val seeded_hash : int -> 'a -> int -``` -A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. - -since 4.00 -``` -val hash_param : int -> int -> 'a -> int -``` -`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. - -``` -val seeded_hash_param : int -> int -> int -> 'a -> int -``` -A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. - -since 4.00 - -## 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 - 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 -``` - -### Counting Elements - -Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. - -Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. - -```ocaml - # module Char_tbl = Hashtbl.Make(struct - type t = char - let equal = Char.equal - let hash = Hashtbl.hash - end) - - (* count distinct occurrences of chars in [seq] *) - # let count_chars (seq : char Seq.t) : _ list = - let counts = Char_tbl.create 16 in - Seq.iter - (fun c -> - let count_c = - Char_tbl.find_opt counts c - |> Option.value ~default:0 - in - Char_tbl.replace counts c (count_c + 1)) - seq; - (* turn into a list *) - Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] - |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) - val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = - - (* basic seq from a string *) - # let seq = String.to_seq "hello world, and all the camels in it!" - val seq : char Seq.t = - - # count_chars seq - - : (Char.t * int) list = - [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); - ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); - ('s', 1); ('t', 2); ('w', 1)] - - (* "abcabcabc..." *) - # let seq2 = - Seq.cycle (String.to_seq "abc") |> Seq.take 31 - val seq2 : char Seq.t = - - # String.of_seq seq2 - - : String.t = "abcabcabcabcabcabcabcabcabcabca" - - # count_chars seq2 - - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] - -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md deleted file mode 100644 index d02ffc06f..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make.md deleted file mode 100644 index b876ef70d..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Map-Make.md +++ /dev/null @@ -1,315 +0,0 @@ - -# Module `Map.Make` - -Functor building an implementation of the map structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Maps - -``` -type key = Ord.t -``` -The type of the map keys. - -``` -type 'a t = 'a Map.Make(Ord).t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key:key -> data:'a -> 'a t -> 'a t -``` -`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t -``` -`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t -``` -`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - f:(key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : f:('a -> 'b) -> 'a t -> 'b t -``` -`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md deleted file mode 100644 index 6858e0bdf..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Map.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-S.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-S.md deleted file mode 100644 index 83ac73341..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Map-module-type-S.md +++ /dev/null @@ -1,306 +0,0 @@ - -# Module type `Map.S` - -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - - -## Maps - -``` -type key -``` -The type of the map keys. - -``` -type !+'a t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key:key -> data:'a -> 'a t -> 'a t -``` -`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t -``` -`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t -``` -`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - f:(key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-MoreLabels-Map-Make.md). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : f:('a -> 'b) -> 'a t -> 'b t -``` -`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Map.md b/docs/api/ml/melange/Stdlib-MoreLabels-Map.md deleted file mode 100644 index d7033ed13..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Map.md +++ /dev/null @@ -1,41 +0,0 @@ - -# Module `MoreLabels.Map` - -Association tables over ordered types. - -This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For instance: - -```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") -``` -This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - -``` -module Make - (Ord : OrderedType) : - S with type key = Ord.t and type 'a t = 'a Map.Make(Ord).t -``` -Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md deleted file mode 100644 index 3abdead73..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make.md deleted file mode 100644 index df47ebd04..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Set-Make.md +++ /dev/null @@ -1,297 +0,0 @@ - -# Module `Set.Make` - -Functor building an implementation of the set structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Sets - -``` -type elt = Ord.t -``` -The type of the set elements. - -``` -type t = Set.Make(Ord).t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : f:(elt -> bool) -> t -> elt -``` -`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : f:(elt -> bool) -> t -> elt option -``` -`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : f:(elt -> bool) -> t -> elt -``` -`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : f:(elt -> bool) -> t -> elt option -``` -`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(elt -> unit) -> t -> unit -``` -`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc -``` -`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : f:(elt -> elt) -> t -> t -``` -`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : f:(elt -> bool) -> t -> t -``` -`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(elt -> elt option) -> t -> t -``` -`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : f:(elt -> bool) -> t -> t * t -``` -`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : f:(elt -> bool) -> t -> bool -``` -`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : f:(elt -> bool) -> t -> bool -``` -`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md deleted file mode 100644 index 4f07540de..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Set.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-S.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-S.md deleted file mode 100644 index 853191d56..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Set-module-type-S.md +++ /dev/null @@ -1,288 +0,0 @@ - -# Module type `Set.S` - -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - - -## Sets - -``` -type elt -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : f:(elt -> bool) -> t -> elt -``` -`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : f:(elt -> bool) -> t -> elt option -``` -`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : f:(elt -> bool) -> t -> elt -``` -`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : f:(elt -> bool) -> t -> elt option -``` -`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(elt -> unit) -> t -> unit -``` -`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc -``` -`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : f:(elt -> elt) -> t -> t -``` -`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : f:(elt -> bool) -> t -> t -``` -`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(elt -> elt option) -> t -> t -``` -`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : f:(elt -> bool) -> t -> t * t -``` -`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : f:(elt -> bool) -> t -> bool -``` -`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : f:(elt -> bool) -> t -> bool -``` -`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-MoreLabels-Set.md b/docs/api/ml/melange/Stdlib-MoreLabels-Set.md deleted file mode 100644 index 489cab218..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels-Set.md +++ /dev/null @@ -1,41 +0,0 @@ - -# Module `MoreLabels.Set` - -Sets over ordered types. - -This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. - -The [`Make`](./Stdlib-MoreLabels-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: - -```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 PairsSet = Set.Make(IntPairs) - - let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) -``` -This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -module Make - (Ord : OrderedType) : - S with type elt = Ord.t and type t = Set.Make(Ord).t -``` -Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/ml/melange/Stdlib-MoreLabels.md b/docs/api/ml/melange/Stdlib-MoreLabels.md deleted file mode 100644 index 3dda53b24..000000000 --- a/docs/api/ml/melange/Stdlib-MoreLabels.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Module `Stdlib.MoreLabels` - -Extra labeled libraries. - -This meta-module provides labelized versions of the [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md) and [`Set`](./Stdlib-MoreLabels-Set.md) modules. - -This module is intended to be used through `open MoreLabels` which replaces [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md), and [`Set`](./Stdlib-MoreLabels-Set.md) with their labeled counterparts. - -For example: - -```ocaml - open MoreLabels - - Hashtbl.iter ~f:(fun ~key ~data -> g key data) table -``` -``` -module Hashtbl : sig ... end -``` -Hash tables and hash functions. - -``` -module Map : sig ... end -``` -Association tables over ordered types. - -``` -module Set : sig ... end -``` -Sets over ordered types. diff --git a/docs/api/ml/melange/Stdlib-Mutex.md b/docs/api/ml/melange/Stdlib-Mutex.md deleted file mode 100644 index 7e8180f6c..000000000 --- a/docs/api/ml/melange/Stdlib-Mutex.md +++ /dev/null @@ -1,49 +0,0 @@ - -# Module `Stdlib.Mutex` - -Locks for mutual exclusion. - -Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if `m` is the mutex associated with the data structure `D`): - -```ocaml - Mutex.lock m; - (* Critical section that operates over D *); - Mutex.unlock m -``` -``` -type t -``` -The type of mutexes. - -``` -val create : unit -> t -``` -Return a new mutex. - -``` -val lock : t -> unit -``` -Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is already locked by the thread calling Mutex.lock. -before 4.12 Sys\_error was not raised for recursive locking (platform-dependent behaviour) -``` -val try_lock : t -> bool -``` -Same as [`Mutex.lock`](./#val-lock), but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. If the mutex is unlocked, lock it and return `true`. - -``` -val unlock : t -> unit -``` -Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. The mutex must have been previously locked by the thread that calls [`Mutex.unlock`](./#val-unlock). - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is unlocked or was locked by another thread. -before 4.12 Sys\_error was not raised when unlocking an unlocked mutex or when unlocking a mutex from a different thread. -``` -val protect : t -> (unit -> 'a) -> 'a -``` -`protect mutex f` runs `f()` in a critical section where `mutex` is locked (using [`lock`](./#val-lock)); it then takes care of releasing `mutex`, whether `f()` returned a value or raised an exception. - -The unlocking operation is guaranteed to always takes place, even in the event an asynchronous exception (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)) is raised in some signal handler. - -since 5.1 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Obj-Ephemeron.md b/docs/api/ml/melange/Stdlib-Obj-Ephemeron.md deleted file mode 100644 index 4020b901b..000000000 --- a/docs/api/ml/melange/Stdlib-Obj-Ephemeron.md +++ /dev/null @@ -1,65 +0,0 @@ - -# Module `Obj.Ephemeron` - -Ephemeron with arbitrary arity and untyped - -``` -type obj_t = t -``` -alias for [`Obj.t`](./Stdlib-Obj.md#type-t) - -``` -type t -``` -an ephemeron cf [`Ephemeron`](#) - -``` -val create : int -> t -``` -`create n` returns an ephemeron with `n` keys. All the keys and the data are initially empty. The argument `n` must be between zero and [`max_ephe_length`](./#val-max_ephe_length) (limits included). - -``` -val length : t -> int -``` -return the number of keys - -``` -val get_key : t -> int -> obj_t option -``` -``` -val get_key_copy : t -> int -> obj_t option -``` -``` -val set_key : t -> int -> obj_t -> unit -``` -``` -val unset_key : t -> int -> unit -``` -``` -val check_key : t -> int -> bool -``` -``` -val blit_key : t -> int -> t -> int -> int -> unit -``` -``` -val get_data : t -> obj_t option -``` -``` -val get_data_copy : t -> obj_t option -``` -``` -val set_data : t -> obj_t -> unit -``` -``` -val unset_data : t -> unit -``` -``` -val check_data : t -> bool -``` -``` -val blit_data : t -> t -> unit -``` -``` -val max_ephe_length : int -``` -Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain diff --git a/docs/api/ml/melange/Stdlib-Obj-Extension_constructor.md b/docs/api/ml/melange/Stdlib-Obj-Extension_constructor.md deleted file mode 100644 index c08771eb4..000000000 --- a/docs/api/ml/melange/Stdlib-Obj-Extension_constructor.md +++ /dev/null @@ -1,15 +0,0 @@ - -# Module `Obj.Extension_constructor` - -``` -type t = extension_constructor -``` -``` -val of_val : 'a -> t -``` -``` -val name : t -> string -``` -``` -val id : t -> int -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Obj.md b/docs/api/ml/melange/Stdlib-Obj.md deleted file mode 100644 index 2e619aff6..000000000 --- a/docs/api/ml/melange/Stdlib-Obj.md +++ /dev/null @@ -1,139 +0,0 @@ - -# Module `Stdlib.Obj` - -Operations on internal representations of values. - -Not for the casual user. - -``` -type t -``` -``` -type raw_data = nativeint -``` -``` -val repr : 'a -> t -``` -``` -val obj : t -> 'a -``` -``` -val magic : 'a -> 'b -``` -``` -val is_block : t -> bool -``` -``` -val is_int : t -> bool -``` -``` -val tag : t -> int -``` -``` -val size : t -> int -``` -``` -val reachable_words : t -> int -``` -Computes the total size (in words, including the headers) of all heap blocks accessible from the argument. Statically allocated blocks are included. - -since 4.04 -``` -val field : t -> int -> t -``` -``` -val set_field : t -> int -> t -> unit -``` -When using flambda: - -`set_field` MUST NOT be called on immutable blocks. (Blocks allocated in C stubs, or with `new_block` below, are always considered mutable.) - -The same goes for `set_double_field`. - -For experts only: `set_field` et al can be made safe by first wrapping the block in [`Sys.opaque_identity`](./Stdlib-Sys.md#val-opaque_identity), so any information about its contents will not be propagated. - -``` -val double_field : t -> int -> float -``` -``` -val set_double_field : t -> int -> float -> unit -``` -``` -val raw_field : t -> int -> raw_data -``` -``` -val set_raw_field : t -> int -> raw_data -> unit -``` -``` -val new_block : int -> int -> t -``` -``` -val dup : t -> t -``` -``` -val add_offset : t -> Int32.t -> t -``` -``` -val with_tag : int -> t -> t -``` -``` -val first_non_constant_constructor_tag : int -``` -``` -val last_non_constant_constructor_tag : int -``` -``` -val forcing_tag : int -``` -``` -val cont_tag : int -``` -``` -val lazy_tag : int -``` -``` -val closure_tag : int -``` -``` -val object_tag : int -``` -``` -val infix_tag : int -``` -``` -val forward_tag : int -``` -``` -val no_scan_tag : int -``` -``` -val abstract_tag : int -``` -``` -val string_tag : int -``` -``` -val double_tag : int -``` -``` -val double_array_tag : int -``` -``` -val custom_tag : int -``` -``` -val int_tag : int -``` -``` -val out_of_heap_tag : int -``` -``` -val unaligned_tag : int -``` -``` -module Extension_constructor : sig ... end -``` -``` -module Ephemeron : sig ... end -``` -Ephemeron with arbitrary arity and untyped diff --git a/docs/api/ml/melange/Stdlib-Oo.md b/docs/api/ml/melange/Stdlib-Oo.md deleted file mode 100644 index f212cee13..000000000 --- a/docs/api/ml/melange/Stdlib-Oo.md +++ /dev/null @@ -1,15 +0,0 @@ - -# Module `Stdlib.Oo` - -Operations on objects - -``` -val copy : < .. > as 'a -> 'a -``` -`Oo.copy o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`. - -alert unsynchronized\_access Unsynchronized accesses to mutable objects are a programming error. -``` -val id : < .. > -> int -``` -Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures. diff --git a/docs/api/ml/melange/Stdlib-Option.md b/docs/api/ml/melange/Stdlib-Option.md deleted file mode 100644 index c84df4dca..000000000 --- a/docs/api/ml/melange/Stdlib-Option.md +++ /dev/null @@ -1,111 +0,0 @@ - -# Module `Stdlib.Option` - -Option values. - -Option values explicitly indicate the presence or absence of a value. - -since 4.08 - -## Options - -``` -type 'a t = 'a option = -``` -``` -| None -``` -``` -| Some of 'a -``` -``` - -``` -The type for option values. Either `None` or a value `Some v`. - -``` -val none : 'a option -``` -`none` is `None`. - -``` -val some : 'a -> 'a option -``` -`some v` is `Some v`. - -``` -val value : 'a option -> default:'a -> 'a -``` -`value o ~default` is `v` if `o` is `Some v` and `default` otherwise. - -``` -val get : 'a option -> 'a -``` -`get o` is `v` if `o` is `Some v` and raise otherwise. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if o is None. -``` -val bind : 'a option -> ('a -> 'b option) -> 'b option -``` -`bind o f` is `f v` if `o` is `Some v` and `None` if `o` is `None`. - -``` -val join : 'a option option -> 'a option -``` -`join oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise. - -``` -val map : ('a -> 'b) -> 'a option -> 'b option -``` -`map f o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`. - -``` -val fold : none:'a -> some:('b -> 'a) -> 'b option -> 'a -``` -`fold ~none ~some o` is `none` if `o` is `None` and `some v` if `o` is `Some v`. - -``` -val iter : ('a -> unit) -> 'a option -> unit -``` -`iter f o` is `f v` if `o` is `Some v` and `()` otherwise. - - -## Predicates and comparisons - -``` -val is_none : 'a option -> bool -``` -`is_none o` is `true` if and only if `o` is `None`. - -``` -val is_some : 'a option -> bool -``` -`is_some o` is `true` if and only if `o` is `Some o`. - -``` -val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool -``` -`equal eq o0 o1` is `true` if and only if `o0` and `o1` are both `None` or if they are `Some v0` and `Some v1` and `eq v0 v1` is `true`. - -``` -val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int -``` -`compare cmp o0 o1` is a total order on options using `cmp` to compare values wrapped by `Some _`. `None` is smaller than `Some _` values. - - -## Converting - -``` -val to_result : none:'e -> 'a option -> ('a, 'e) result -``` -`to_result ~none o` is `Ok v` if `o` is `Some v` and `Error none` otherwise. - -``` -val to_list : 'a option -> 'a list -``` -`to_list o` is `[]` if `o` is `None` and `[v]` if `o` is `Some v`. - -``` -val to_seq : 'a option -> 'a Seq.t -``` -`to_seq o` is `o` as a sequence. `None` is the empty sequence and `Some v` is the singleton sequence containing `v`. diff --git a/docs/api/ml/melange/Stdlib-Out_channel.md b/docs/api/ml/melange/Stdlib-Out_channel.md deleted file mode 100644 index 35eade38e..000000000 --- a/docs/api/ml/melange/Stdlib-Out_channel.md +++ /dev/null @@ -1,239 +0,0 @@ - -# Module `Stdlib.Out_channel` - -Output channels. - -This module provides functions for working with output channels. - -See [the example section](./#examples) below. - -since 4.14 - -## Channels - -``` -type t = out_channel -``` -The type of output channel. - -``` -type open_flag = open_flag = -``` -``` -| Open_rdonly -``` -open for reading. - -``` -| Open_wronly -``` -open for writing. - -``` -| Open_append -``` -open for appending: always write at end of file. - -``` -| Open_creat -``` -create the file if it does not exist. - -``` -| Open_trunc -``` -empty the file if it already exists. - -``` -| Open_excl -``` -fail if Open\_creat and the file already exists. - -``` -| Open_binary -``` -open in binary mode (no conversion). - -``` -| Open_text -``` -open in text mode (may perform conversions). - -``` -| Open_nonblock -``` -open in non-blocking mode. - -``` - -``` -Opening modes for [`open_gen`](./#val-open_gen). - -``` -val stdout : t -``` -The standard output for the process. - -``` -val stderr : t -``` -The standard error output for the process. - -``` -val open_bin : string -> t -``` -Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. - -``` -val open_text : string -> t -``` -Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). - -``` -val open_gen : open_flag list -> int -> string -> t -``` -`open_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. - -``` -val with_open_bin : string -> (t -> 'a) -> 'a -``` -`with_open_bin fn f` opens a channel `oc` on file `fn` and returns `f oc`. After `f` returns, either with a value or by raising an exception, `oc` is guaranteed to be closed. - -``` -val with_open_text : string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). - -``` -val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). - -``` -val close : t -> unit -``` -Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except [`close`](./#val-close) and [`flush`](./#val-flush), which do nothing when applied to an already closed channel. Note that [`close`](./#val-close) may raise `Sys_error` if the operating system signals an error when flushing or closing. - -``` -val close_noerr : t -> unit -``` -Same as [`close`](./#val-close), but ignore all errors. - - -## Output - -``` -val output_char : t -> char -> unit -``` -Write the character on the given output channel. - -``` -val output_byte : t -> int -> unit -``` -Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. - -``` -val output_string : t -> string -> unit -``` -Write the string on the given output channel. - -``` -val output_bytes : t -> bytes -> unit -``` -Write the byte sequence on the given output channel. - - -## Advanced output - -``` -val output : t -> bytes -> int -> int -> unit -``` -`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val output_substring : t -> string -> int -> int -> unit -``` -Same as [`output`](./#val-output) but take a string as argument instead of a byte sequence. - - -## Flushing - -``` -val flush : t -> unit -``` -Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. - -``` -val flush_all : unit -> unit -``` -Flush all open output channels; ignore errors. - - -## Seeking - -``` -val seek : t -> int64 -> unit -``` -`seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. - -``` -val pos : t -> int64 -``` -Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). - -For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - - -## Attributes - -``` -val length : t -> int64 -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. - -``` -val set_binary_mode : t -> bool -> unit -``` -`set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output. - -`set_binary_mode oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. - -This function has no effect under operating systems that do not distinguish between text mode and binary mode. - -``` -val is_binary_mode : t -> bool -``` -`is_binary_mode oc` returns whether the channel `oc` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). - -since 5.2 -``` -val set_buffered : t -> bool -> unit -``` -`set_buffered oc true` sets the channel `oc` to *buffered* mode. In this mode, data output on `oc` will be buffered until either the internal buffer is full or the function [`flush`](./#val-flush) or [`flush_all`](./#val-flush_all) is called, at which point it will be sent to the output device. - -`set_buffered oc false` sets the channel `oc` to *unbuffered* mode. In this mode, data output on `oc` will be sent to the output device immediately. - -All channels are open in *buffered* mode by default. - -``` -val is_buffered : t -> bool -``` -`is_buffered oc` returns whether the channel `oc` is buffered (see [`set_buffered`](./#val-set_buffered)). - -``` -val isatty : t -> bool -``` -`isatty oc` is `true` if `oc` refers to a terminal or console window, `false` otherwise. - -since 5.1 - -## Examples - -Writing the contents of a file: - -```ocaml - let write_file file s = - Out_channel.with_open_bin file - (fun oc -> Out_channel.output_string oc s)) -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Parsing.md b/docs/api/ml/melange/Stdlib-Parsing.md deleted file mode 100644 index b95445513..000000000 --- a/docs/api/ml/melange/Stdlib-Parsing.md +++ /dev/null @@ -1,61 +0,0 @@ - -# Module `Stdlib.Parsing` - -The run-time library for parsers generated by `ocamlyacc`. - -``` -val symbol_start : unit -> int -``` -`symbol_start` and [`Parsing.symbol_end`](./#val-symbol_end) are to be called in the action part of a grammar rule only. They return the offset of the string that matches the left-hand side of the rule: `symbol_start()` returns the offset of the first character; `symbol_end()` returns the offset after the last character. The first character in a file is at offset 0. - -``` -val symbol_end : unit -> int -``` -See [`Parsing.symbol_start`](./#val-symbol_start). - -``` -val rhs_start : int -> int -``` -Same as [`Parsing.symbol_start`](./#val-symbol_start) and [`Parsing.symbol_end`](./#val-symbol_end), but return the offset of the string matching the `n`th item on the right-hand side of the rule, where `n` is the integer parameter to `rhs_start` and `rhs_end`. `n` is 1 for the leftmost item. - -``` -val rhs_end : int -> int -``` -See [`Parsing.rhs_start`](./#val-rhs_start). - -``` -val symbol_start_pos : unit -> Lexing.position -``` -Same as `symbol_start`, but return a `position` instead of an offset. - -``` -val symbol_end_pos : unit -> Lexing.position -``` -Same as `symbol_end`, but return a `position` instead of an offset. - -``` -val rhs_start_pos : int -> Lexing.position -``` -Same as `rhs_start`, but return a `position` instead of an offset. - -``` -val rhs_end_pos : int -> Lexing.position -``` -Same as `rhs_end`, but return a `position` instead of an offset. - -``` -val clear_parser : unit -> unit -``` -Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs. - -``` -exception Parse_error -``` -Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery. - -``` -val set_trace : bool -> bool -``` -Control debugging support for `ocamlyacc`\-generated parsers. After `Parsing.set_trace true`, the pushdown automaton that executes the parsers prints a trace of its actions (reading a token, shifting a state, reducing by a rule) on standard output. `Parsing.set_trace false` turns this debugging trace off. The boolean returned is the previous state of the trace flag. - -since 3.11 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Printexc-Slot.md b/docs/api/ml/melange/Stdlib-Printexc-Slot.md deleted file mode 100644 index 452eda49a..000000000 --- a/docs/api/ml/melange/Stdlib-Printexc-Slot.md +++ /dev/null @@ -1,45 +0,0 @@ - -# Module `Printexc.Slot` - -since 4.02 -``` -type t = backtrace_slot -``` -``` -val is_raise : t -> bool -``` -`is_raise slot` is `true` when `slot` refers to a raising point in the code, and `false` when it comes from a simple function call. - -since 4.02 -``` -val is_inline : t -> bool -``` -`is_inline slot` is `true` when `slot` refers to a call that got inlined by the compiler, and `false` when it comes from any other context. - -since 4.04 -``` -val location : t -> location option -``` -`location slot` returns the location information of the slot, if available, and `None` otherwise. - -Some possible reasons for failing to return a location are as follow: - -- the slot corresponds to a compiler-inserted raise -- the slot corresponds to a part of the program that has not been compiled with debug information (`-g`) -since 4.02 -``` -val name : t -> string option -``` -`name slot` returns the name of the function or definition enclosing the location referred to by the slot. - -`name slot` returns None if the name is unavailable, which may happen for the same reasons as `location` returning None. - -since 4.11 -``` -val format : int -> t -> string option -``` -`format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`\-th element of the backtrace: the `0`\-th element is pretty-printed differently than the others. - -Whole-backtrace printing functions also skip some uninformative slots; in that case, `format pos slot` returns `None`. - -since 4.02 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Printexc.md b/docs/api/ml/melange/Stdlib-Printexc.md deleted file mode 100644 index 47bfc94fe..000000000 --- a/docs/api/ml/melange/Stdlib-Printexc.md +++ /dev/null @@ -1,280 +0,0 @@ - -# Module `Stdlib.Printexc` - -Facilities for printing exceptions and inspecting current call stack. - -``` -type t = exn = .. -``` -The type of exception values. - -``` -val to_string : exn -> string -``` -`Printexc.to_string e` returns a string representation of the exception `e`. - -``` -val to_string_default : exn -> string -``` -`Printexc.to_string_default e` returns a string representation of the exception `e`, ignoring all registered exception printers. - -since 4.09 -``` -val print : ('a -> 'b) -> 'a -> 'b -``` -`Printexc.print fn x` applies `fn` to `x` and returns the result. If the evaluation of `fn x` raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application. - -``` -val catch : ('a -> 'b) -> 'a -> 'b -``` -`Printexc.catch fn x` is similar to [`Printexc.print`](./#val-print), but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as `Printexc.catch` does. Moreover, calling `Printexc.catch` makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use `Printexc.catch` in new code. - -deprecated This function is no longer needed. -``` -val print_backtrace : out_channel -> unit -``` -`Printexc.print_backtrace oc` prints an exception backtrace on the output channel `oc`. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls. - -If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one. - -since 3.11 -``` -val get_backtrace : unit -> string -``` -`Printexc.get_backtrace ()` returns a string containing the same exception backtrace that `Printexc.print_backtrace` would print. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). - -since 3.11 -``` -val record_backtrace : bool -> unit -``` -`Printexc.record_backtrace b` turns recording of exception backtraces on (if `b = true`) or off (if `b = false`). Initially, backtraces are not recorded, unless the `b` flag is given to the program through the `OCAMLRUNPARAM` variable. - -since 3.11 -``` -val backtrace_status : unit -> bool -``` -`Printexc.backtrace_status()` returns `true` if exception backtraces are currently recorded, `false` if not. - -since 3.11 -``` -val register_printer : (exn -> string option) -> unit -``` -`Printexc.register_printer fn` registers `fn` as an exception printer. The printer should return `None` or raise an exception if it does not know how to convert the passed exception, and `Some s` with `s` the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored. - -When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a `Some s` value (if no such printer exists, the runtime will use a generic printer). - -When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to `fn` should not use the backtrace if it has itself raised an exception before. - -since 3.11.2 -``` -val use_printers : exn -> string option -``` -`Printexc.use_printers e` returns `None` if there are no registered printers and `Some s` with `s` the resulting string otherwise. - -since 4.09 - -## Raw backtraces - -``` -type raw_backtrace -``` -The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below. - -Converting backtraces to `backtrace_slot`s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use `raw_backtrace` to avoid or delay conversion. - -Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the `backtrace_slots` function of the next section. - -since 4.01 -``` -type raw_backtrace_entry = private int -``` -A `raw_backtrace_entry` is an element of a `raw_backtrace`. - -Each `raw_backtrace_entry` is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary. - -A `raw_backtrace_entry` can be converted to a usable form using `backtrace_slots_of_raw_entry` below. Note that, due to inlining, a single `raw_backtrace_entry` may convert to several `backtrace_slot`s. Since the values of a `raw_backtrace_entry` are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them. - -Again due to inlining, there may be multiple distinct raw\_backtrace\_entry values that convert to equal `backtrace_slot`s. However, if two `raw_backtrace_entry`s are equal as integers, then they represent the same `backtrace_slot`s. - -since 4.12 -``` -val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array -``` -since 4.12 -``` -val get_raw_backtrace : unit -> raw_backtrace -``` -`Printexc.get_raw_backtrace ()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). - -since 4.01 -``` -val print_raw_backtrace : out_channel -> raw_backtrace -> unit -``` -Print a raw backtrace in the same format `Printexc.print_backtrace` uses. - -since 4.01 -``` -val raw_backtrace_to_string : raw_backtrace -> string -``` -Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses. - -since 4.01 -``` -val raise_with_backtrace : exn -> raw_backtrace -> 'a -``` -Reraise the exception using the given raw\_backtrace for the origin of the exception - -since 4.05 - -## Current call stack - -``` -val get_callstack : int -> raw_backtrace -``` -`Printexc.get_callstack n` returns a description of the top of the call stack on the current program point (for the current thread), with at most `n` entries. (Note: this function is not related to exceptions at all, despite being part of the `Printexc` module.) - -since 4.01 - -## Uncaught exceptions - -``` -val default_uncaught_exception_handler : exn -> raw_backtrace -> unit -``` -`Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output. - -since 4.11 -``` -val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit -``` -`Printexc.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. The default handler is [`Printexc.default_uncaught_exception_handler`](./#val-default_uncaught_exception_handler). - -Note that when `fn` is called all the functions registered with [`Stdlib.at_exit`](./Stdlib.md#val-at_exit) have already been called. Because of this you must make sure any output channel `fn` writes on is flushed. - -Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself. - -If `fn` raises an exception, both the exceptions passed to `fn` and raised by `fn` will be printed with their respective backtrace. - -since 4.02 - -## Manipulation of backtrace information - -These functions are used to traverse the slots of a raw backtrace and extract information from them in a programmer-friendly format. - -``` -type backtrace_slot -``` -The abstract type `backtrace_slot` represents a single slot of a backtrace. - -since 4.02 -``` -val backtrace_slots : raw_backtrace -> backtrace_slot array option -``` -Returns the slots of a raw backtrace, or `None` if none of them contain useful information. - -In the return array, the slot at index `0` corresponds to the most recent function call, raise, or primitive `get_backtrace` call in the trace. - -Some possible reasons for returning `None` are as follow: - -- none of the slots in the trace come from modules compiled with debug information (`-g`) -- the program is a bytecode program that has not been linked with debug information enabled (`ocamlc -g`) -since 4.02 -``` -val backtrace_slots_of_raw_entry : - raw_backtrace_entry -> - backtrace_slot array option -``` -Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information. - -Slots are returned in the same order as `backtrace_slots`: the slot at index `0` is the most recent call, raise, or primitive, and subsequent slots represent callers. - -since 4.12 -``` -type location = { -``` -`filename : string;` -`line_number : int;` -`start_char : int;` -`end_char : int;` -`end_line : int;` -since 5.2 -`end_col : int;` -since 5.2 -``` -} -``` -The type of location information found in backtraces. `start_char` and `end_char` are positions relative to the beginning of `line_number`. `end_col` is relative to the beginning of `end_line`. - -since 4.02 -``` -module Slot : sig ... end -``` - -## Raw backtrace slots - -``` -type raw_backtrace_slot -``` -This type is used to iterate over the slots of a `raw_backtrace`. For most purposes, `backtrace_slots_of_raw_entry` is easier to use. - -Like `raw_backtrace_entry`, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior). - -Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example). - -since 4.02 -``` -val raw_backtrace_length : raw_backtrace -> int -``` -`raw_backtrace_length bckt` returns the number of slots in the backtrace `bckt`. - -since 4.02 -``` -val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot -``` -`get_raw_backtrace_slot bckt pos` returns the slot in position `pos` in the backtrace `bckt`. - -since 4.02 -``` -val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot -``` -Extracts the user-friendly `backtrace_slot` from a low-level `raw_backtrace_slot`. - -since 4.02 -``` -val get_raw_backtrace_next_slot : - raw_backtrace_slot -> - raw_backtrace_slot option -``` -`get_raw_backtrace_next_slot slot` returns the next slot inlined, if any. - -Sample code to iterate over all frames (inlined and non-inlined): - -```ocaml - (* Iterate over inlined frames *) - let rec iter_raw_backtrace_slot f slot = - f slot; - match get_raw_backtrace_next_slot slot with - | None -> () - | Some slot' -> iter_raw_backtrace_slot f slot' - - (* Iterate over stack frames *) - let iter_raw_backtrace f bt = - for i = 0 to raw_backtrace_length bt - 1 do - iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i) - done -``` -since 4.04 - -## Exception slots - -``` -val exn_slot_id : exn -> int -``` -`Printexc.exn_slot_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime). - -since 4.02 -``` -val exn_slot_name : exn -> string -``` -`Printexc.exn_slot_name exn` returns the internal name of the constructor used to create the exception value `exn`. - -since 4.02 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Printf.md b/docs/api/ml/melange/Stdlib-Printf.md deleted file mode 100644 index 4c1d41539..000000000 --- a/docs/api/ml/melange/Stdlib-Printf.md +++ /dev/null @@ -1,144 +0,0 @@ - -# Module `Stdlib.Printf` - -Formatted output functions. - -``` -val fprintf : out_channel -> ('a, out_channel, unit) format -> 'a -``` -`fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`. - -The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments. - -Conversion specifications have the following form: - -`% [flags] [width] [.precision] type` - -In short, a conversion specification consists in the `%` character, followed by optional modifiers and a type which is made of one or two characters. - -The types and their meanings are: - -- `d`, `i`: convert an integer argument to signed decimal. The flag `#` adds underscores to large values for readability. -- `u`, `n`, `l`, `L`, or `N`: convert an integer argument to unsigned decimal. Warning: `n`, `l`, `L`, and `N` are used for `scanf`, and should not be used for `printf`. The flag `#` adds underscores to large values for readability. -- `x`: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag `#` adds a `0x` prefix to non zero values. -- `X`: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag `#` adds a `0X` prefix to non zero values. -- `o`: convert an integer argument to unsigned octal. The flag `#` adds a `0` prefix to non zero values. -- `s`: insert a string argument. -- `S`: convert a string argument to OCaml syntax (double quotes, escapes). -- `c`: insert a character argument. -- `C`: convert a character argument to OCaml syntax (single quotes, escapes). -- `f`: convert a floating-point argument to decimal notation, in the style `dddd.ddd`. -- `F`: convert a floating-point argument to OCaml syntax (`dddd.` or `dddd.ddd` or `d.ddd e+-dd`). Converts to hexadecimal with the `#` flag (see `h`). -- `e` or `E`: convert a floating-point argument to decimal notation, in the style `d.ddd e+-dd` (mantissa and exponent). -- `g` or `G`: convert a floating-point argument to decimal notation, in style `f` or `e`, `E` (whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining. -- `h` or `H`: convert a floating-point argument to hexadecimal notation, in the style `0xh.hhhh p+-dd` (hexadecimal mantissa, exponent in decimal and denotes a power of 2). -- `B`: convert a boolean argument to the string `true` or `false` -- `b`: convert a boolean argument (deprecated; do not use in new programs). -- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: convert an `int32` argument to the format specified by the second letter (decimal, hexadecimal, etc). -- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: convert a `nativeint` argument to the format specified by the second letter. -- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: convert an `int64` argument to the format specified by the second letter. -- `a`: user-defined printer. Take two arguments and apply the first one to `outchan` (the current output channel) and to the second argument. The first argument must therefore have type `out_channel -> 'b -> unit` and the second `'b`. The output produced by the function is inserted in the output of `fprintf` at the current point. -- `t`: same as `%a`, but take only one argument (with type `out_channel -> unit`) and apply it to `outchan`. -- `\{ fmt %\}`: convert a format string argument to its type digest. The argument must have the same type as the internal format string `fmt`. -- `( fmt %)`: format string substitution. Take a format string argument and substitute it to the internal format string `fmt` to print following arguments. The argument must have the same type as the internal format string `fmt`. -- `!`: take no argument and flush the output. -- `%`: take no argument and output one `%` character. -- `\@`: take no argument and output one `\@` character. -- `,`: take no argument and output nothing: a no-op delimiter for conversion specifications. -The optional `flags` are: - -- `-`: left-justify the output (default is right justification). -- `0`: for numerical conversions, pad with zeroes instead of spaces. -- `+`: for signed numerical conversions, prefix number with a `+` sign if positive. -- space: for signed numerical conversions, prefix number with a space if positive. -- `#`: request an alternate formatting style for the integer types and the floating-point type `F`. -The optional `width` is an integer indicating the minimal width of the result. For instance, `%6d` prints an integer, prefixing it with spaces to fill at least 6 characters. - -The optional `precision` is a dot `.` followed by an integer indicating how many digits follow the decimal point in the `%f`, `%e`, `%E`, `%h`, and `%H` conversions or the maximum number of significant digits to appear for the `%F`, `%g` and `%G` conversions. For instance, `%.4f` prints a `float` with 4 fractional digits. - -The integer in a `width` or `precision` can also be specified as `*`, in which case an extra integer argument is taken to specify the corresponding `width` or `precision`. This integer argument precedes immediately the argument to print. For instance, `%.*f` prints a `float` with as many fractional digits as the value of the argument given before the float. - -``` -val printf : ('a, out_channel, unit) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but output on `stdout`. - -``` -val eprintf : ('a, out_channel, unit) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but output on `stderr`. - -``` -val sprintf : ('a, unit, string) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, return a string containing the result of formatting the arguments. - -``` -val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module [`Buffer`](./Stdlib-Buffer.md)). - -``` -val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but does not print anything. Useful to ignore some material when conditionally printing. - -since 3.10 -``` -val ibprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a -``` -Same as [`Printf.bprintf`](./#val-bprintf), but does not print anything. Useful to ignore some material when conditionally printing. - -since 4.11 -Formatted output functions with continuations. - -``` -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 -``` -val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a -``` -Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 4.01 -``` -val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a -``` -Same as `sprintf` above, but instead of returning the string, passes it to the first argument. - -since 3.09 -``` -val kbprintf : - (Buffer.t -> 'd) -> - Buffer.t -> - ('a, Buffer.t, unit, 'd) format4 -> - 'a -``` -Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing. - -since 3.10 -``` -val ikbprintf : - (Buffer.t -> 'd) -> - Buffer.t -> - ('a, Buffer.t, unit, 'd) format4 -> - 'a -``` -Same as `kbprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 4.11 -Deprecated - -``` -val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a -``` -A deprecated synonym for `ksprintf`. - -deprecated Use Printf.ksprintf instead. \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Queue.md b/docs/api/ml/melange/Stdlib-Queue.md deleted file mode 100644 index 820e40343..000000000 --- a/docs/api/ml/melange/Stdlib-Queue.md +++ /dev/null @@ -1,225 +0,0 @@ - -# Module `Stdlib.Queue` - -First-in first-out queues. - -This module implements queues (FIFOs), with in-place modification. See [the example section](./#examples) below. - -**Unsynchronized accesses** - -Unsynchronized accesses to a queue may lead to an invalid queue state. Thus, concurrent accesses to queues must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -type !'a t -``` -The type of queues containing elements of type `'a`. - -``` -exception Empty -``` -Raised when [`Queue.take`](./#val-take) or [`Queue.peek`](./#val-peek) is applied to an empty queue. - -``` -val create : unit -> 'a t -``` -Return a new queue, initially empty. - -``` -val add : 'a -> 'a t -> unit -``` -`add x q` adds the element `x` at the end of the queue `q`. - -``` -val push : 'a -> 'a t -> unit -``` -`push` is a synonym for `add`. - -``` -val take : 'a t -> 'a -``` -`take q` removes and returns the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. - -``` -val take_opt : 'a t -> 'a option -``` -`take_opt q` removes and returns the first element in queue `q`, or returns `None` if the queue is empty. - -since 4.08 -``` -val pop : 'a t -> 'a -``` -`pop` is a synonym for `take`. - -``` -val peek : 'a t -> 'a -``` -`peek q` returns the first element in queue `q`, without removing it from the queue, or raises [`Empty`](./#exception-Empty) if the queue is empty. - -``` -val peek_opt : 'a t -> 'a option -``` -`peek_opt q` returns the first element in queue `q`, without removing it from the queue, or returns `None` if the queue is empty. - -since 4.08 -``` -val top : 'a t -> 'a -``` -`top` is a synonym for `peek`. - -``` -val drop : 'a t -> unit -``` -`drop q` removes the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. - -since 5.3 -``` -val clear : 'a t -> unit -``` -Discard all elements from a queue. - -``` -val copy : 'a t -> 'a t -``` -Return a copy of the given queue. - -``` -val is_empty : 'a t -> bool -``` -Return `true` if the given queue is empty, `false` otherwise. - -``` -val length : 'a t -> int -``` -Return the number of elements in a queue. - -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f q` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. - -``` -val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold f accu q` is equivalent to `List.fold_left f accu l`, where `l` is the list of `q`'s elements. The queue remains unchanged. - -``` -val transfer : 'a t -> 'a t -> unit -``` -`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `iter (fun x -> add x q2) q1; clear q1`, but runs in constant time. - - -## Iterators - -``` -val to_seq : 'a t -> 'a Seq.t -``` -Iterate on the queue, in front-to-back order. The behavior is not specified if the queue is modified during the iteration. - -since 4.07 -``` -val add_seq : 'a t -> 'a Seq.t -> unit -``` -Add the elements from a sequence to the end of the queue. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a t -``` -Create a queue from a sequence. - -since 4.07 - -## Examples - - -### Basic Example - -A basic example: - -```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. -``` - -### Search Through a Graph - -For a more elaborate example, a classic algorithmic use of queues is to implement a BFS (breadth-first search) through a graph. - -```ocaml - type graph = { - edges: (int, int list) Hashtbl.t - } - - (* Search in graph [g] using BFS, starting from node [start]. - It returns the first node that satisfies [p], or [None] if - no node reachable from [start] satisfies [p]. - *) - let search_for ~(g:graph) ~(start:int) (p:int -> bool) : int option = - let to_explore = Queue.create() in - let explored = Hashtbl.create 16 in - - Queue.push start to_explore; - let rec loop () = - if Queue.is_empty to_explore then None - else - (* node to explore *) - let node = Queue.pop to_explore in - explore_node node - - and explore_node node = - if not (Hashtbl.mem explored node) then ( - if p node then Some node (* found *) - else ( - Hashtbl.add explored node (); - let children = - Hashtbl.find_opt g.edges node - |> Option.value ~default:[] - in - List.iter (fun child -> Queue.push child to_explore) children; - loop() - ) - ) else loop() - in - loop() - - (* a sample graph *) - let my_graph: graph = - let edges = - List.to_seq [ - 1, [2;3]; - 2, [10; 11]; - 3, [4;5]; - 5, [100]; - 11, [0; 20]; - ] - |> Hashtbl.of_seq - in {edges} - - # search_for ~g:my_graph ~start:1 (fun x -> x = 30) - - : int option = None - - # search_for ~g:my_graph ~start:1 (fun x -> x >= 15) - - : int option = Some 20 - - # search_for ~g:my_graph ~start:1 (fun x -> x >= 50) - - : int option = Some 100 -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Random-State.md b/docs/api/ml/melange/Stdlib-Random-State.md deleted file mode 100644 index cf10b7a30..000000000 --- a/docs/api/ml/melange/Stdlib-Random-State.md +++ /dev/null @@ -1,50 +0,0 @@ - -# Module `Random.State` - -``` -type t -``` -The type of PRNG states. - -``` -val make : int array -> t -``` -Create a new state and initialize it with the given seed. - -``` -val make_self_init : unit -> t -``` -Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in [`Random.self_init`](./Stdlib-Random.md#val-self_init). - -``` -val copy : t -> t -``` -Return a copy of the given state. - -``` -val bits : t -> int -``` -``` -val int : t -> int -> int -``` -``` -val full_int : t -> int -> int -``` -``` -val int32 : t -> Int32.t -> Int32.t -``` -``` -val int64 : t -> Int64.t -> Int64.t -``` -``` -val float : t -> float -> float -``` -``` -val bool : t -> bool -``` -``` -val bits32 : t -> Int32.t -``` -``` -val bits64 : t -> Int64.t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Random.md b/docs/api/ml/melange/Stdlib-Random.md deleted file mode 100644 index 98f498047..000000000 --- a/docs/api/ml/melange/Stdlib-Random.md +++ /dev/null @@ -1,103 +0,0 @@ - -# Module `Stdlib.Random` - -Pseudo-random number generators (PRNG). - -With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain. - -In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the `Random.split` function and used with the functions from the [`Random.State`](./Stdlib-Random-State.md) module. - -before 5.0 Random value generation used a different algorithm. This affects all the functions in this module which return random values. - -## Basic functions - -``` -val init : int -> unit -``` -Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. - -``` -val full_init : int array -> unit -``` -Same as [`Random.init`](./#val-init) but takes more data as seed. - -``` -val self_init : unit -> unit -``` -Initialize the domain-local generator with a random seed chosen in a system-dependent way. If `/dev/urandom` is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state). - -``` -val bits : unit -> int -``` -Return 30 random bits in a nonnegative integer. - -``` -val int : int -> int -``` -`Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0 and less than 230. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0 or bound \>= 230. -``` -val full_int : int -> int -``` -`Random.full_int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` may be any positive integer. - -If `bound` is less than 231, then `Random.full_int bound` yields identical output across systems with varying `int` sizes. - -If `bound` is less than 230, then `Random.full_int bound` is equal to [`Random.int`](./#val-int)` bound`. - -If `bound` is at least 230 (on 64-bit systems, or non-standard environments such as JavaScript), then `Random.full_int` returns a value whereas [`Random.int`](./#val-int) raises [`Stdlib.Invalid_argument`](./Stdlib.md#exception-Invalid_argument). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. -since 4.13 -``` -val int32 : Int32.t -> Int32.t -``` -`Random.int32 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. -``` -val int64 : Int64.t -> Int64.t -``` -`Random.int64 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. -``` -val float : float -> float -``` -`Random.float bound` returns a random floating-point number between 0 and `bound` (inclusive). If `bound` is negative, the result is negative or zero. If `bound` is 0, the result is 0. - -``` -val bool : unit -> bool -``` -`Random.bool ()` returns `true` or `false` with probability 0.5 each. - -``` -val bits32 : unit -> Int32.t -``` -`Random.bits32 ()` returns 32 random bits as an integer between [`Int32.min_int`](./Stdlib-Int32.md#val-min_int) and [`Int32.max_int`](./Stdlib-Int32.md#val-max_int). - -since 4.14 -``` -val bits64 : unit -> Int64.t -``` -`Random.bits64 ()` returns 64 random bits as an integer between [`Int64.min_int`](./Stdlib-Int64.md#val-min_int) and [`Int64.max_int`](./Stdlib-Int64.md#val-max_int). - -since 4.14 - -## Advanced functions - -The functions from module [`State`](./Stdlib-Random-State.md) manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. - -``` -module State : sig ... end -``` -``` -val get_state : unit -> State.t -``` -`get_state()` returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). - -``` -val set_state : State.t -> unit -``` -`set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it. diff --git a/docs/api/ml/melange/Stdlib-Result.md b/docs/api/ml/melange/Stdlib-Result.md deleted file mode 100644 index 5e42a7a68..000000000 --- a/docs/api/ml/melange/Stdlib-Result.md +++ /dev/null @@ -1,137 +0,0 @@ - -# Module `Stdlib.Result` - -Result values. - -Result values handle computation results and errors in an explicit and declarative manner without resorting to exceptions. - -since 4.08 - -## Results - -``` -type ('a, 'e) t = ('a, 'e) result = -``` -``` -| Ok of 'a -``` -``` -| Error of 'e -``` -``` - -``` -The type for result values. Either a value `Ok v` or an error `Error e`. - -``` -val ok : 'a -> ('a, 'e) result -``` -`ok v` is `Ok v`. - -``` -val error : 'e -> ('a, 'e) result -``` -`error e` is `Error e`. - -``` -val value : ('a, 'e) result -> default:'a -> 'a -``` -`value r ~default` is `v` if `r` is `Ok v` and `default` otherwise. - -``` -val get_ok : ('a, 'e) result -> 'a -``` -`get_ok r` is `v` if `r` is `Ok v` and raise otherwise. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Error \_. -``` -val get_error : ('a, 'e) result -> 'e -``` -`get_error r` is `e` if `r` is `Error e` and raise otherwise. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Ok \_. -``` -val bind : ('a, 'e) result -> ('a -> ('b, 'e) result) -> ('b, 'e) result -``` -`bind r f` is `f v` if `r` is `Ok v` and `r` if `r` is `Error _`. - -``` -val join : (('a, 'e) result, 'e) result -> ('a, 'e) result -``` -`join rr` is `r` if `rr` is `Ok r` and `rr` if `rr` is `Error _`. - -``` -val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result -``` -`map f r` is `Ok (f v)` if `r` is `Ok v` and `r` if `r` is `Error _`. - -``` -val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result -``` -`map_error f r` is `Error (f e)` if `r` is `Error e` and `r` if `r` is `Ok _`. - -``` -val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c -``` -`fold ~ok ~error r` is `ok v` if `r` is `Ok v` and `error e` if `r` is `Error e`. - -``` -val iter : ('a -> unit) -> ('a, 'e) result -> unit -``` -`iter f r` is `f v` if `r` is `Ok v` and `()` otherwise. - -``` -val iter_error : ('e -> unit) -> ('a, 'e) result -> unit -``` -`iter_error f r` is `f e` if `r` is `Error e` and `()` otherwise. - - -## Predicates and comparisons - -``` -val is_ok : ('a, 'e) result -> bool -``` -`is_ok r` is `true` if and only if `r` is `Ok _`. - -``` -val is_error : ('a, 'e) result -> bool -``` -`is_error r` is `true` if and only if `r` is `Error _`. - -``` -val equal : - ok:('a -> 'a -> bool) -> - error:('e -> 'e -> bool) -> - ('a, 'e) result -> - ('a, 'e) result -> - bool -``` -`equal ~ok ~error r0 r1` tests equality of `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. - -``` -val compare : - ok:('a -> 'a -> int) -> - error:('e -> 'e -> int) -> - ('a, 'e) result -> - ('a, 'e) result -> - int -``` -`compare ~ok ~error r0 r1` totally orders `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _ ` and `Error _`. `Ok _` values are smaller than `Error _` values. - - -## Converting - -``` -val to_option : ('a, 'e) result -> 'a option -``` -`to_option r` is `r` as an option, mapping `Ok v` to `Some v` and `Error _` to `None`. - -``` -val to_list : ('a, 'e) result -> 'a list -``` -`to_list r` is `[v]` if `r` is `Ok v` and `[]` otherwise. - -``` -val to_seq : ('a, 'e) result -> 'a Seq.t -``` -`to_seq r` is `r` as a sequence. `Ok v` is the singleton sequence containing `v` and `Error _` is the empty sequence. diff --git a/docs/api/ml/melange/Stdlib-Scanf-Scanning.md b/docs/api/ml/melange/Stdlib-Scanf-Scanning.md deleted file mode 100644 index 1bfe20e18..000000000 --- a/docs/api/ml/melange/Stdlib-Scanf-Scanning.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Scanf.Scanning` - -``` -type in_channel -``` -The notion of input channel for the [`Scanf`](./Stdlib-Scanf.md) module: those channels provide all the machinery necessary to read from any source of characters, including a [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) value. A Scanf.Scanning.in\_channel value is also called a *formatted input channel* or equivalently a *scanning buffer*. The type [`Scanning.scanbuf`](./#type-scanbuf) below is an alias for `Scanning.in_channel`. Note that a `Scanning.in_channel` is not concurrency-safe: concurrent use may produce arbitrary values or exceptions. - -since 3.12 -``` -type scanbuf = in_channel -``` -The type of scanning buffers. A scanning buffer is the source from which a formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far. - -Note: a scanning action may often require to examine one character in advance; when this 'lookahead' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character yet to be read. - -``` -val stdin : in_channel -``` -The standard input notion for the [`Scanf`](./Stdlib-Scanf.md) module. `Scanning.stdin` is the [`Scanning.in_channel`](./#type-in_channel) formatted input channel attached to [`Stdlib.stdin`](./Stdlib.md#val-stdin). - -Note: in the interactive system, when input is read from [`Stdlib.stdin`](./Stdlib.md#val-stdin), the newline character that triggers evaluation is part of the input; thus, the scanning specifications must properly skip this additional newline character (for instance, simply add a `'\n'` as the last character of the format string). - -since 3.12 -``` -type file_name = string -``` -A convenient alias to designate a file name. - -since 4.00 -``` -val open_in : file_name -> in_channel -``` -`Scanning.open_in fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in text mode from file `fname`. - -Note: `open_in` returns a formatted input channel that efficiently reads characters in large chunks; in contrast, `from_channel` below returns formatted input channels that must read one character at a time, leading to a much slower scanning rate. - -since 3.12 -``` -val open_in_bin : file_name -> in_channel -``` -`Scanning.open_in_bin fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in binary mode from file `fname`. - -since 3.12 -``` -val close_in : in_channel -> unit -``` -Closes the [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) associated with the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -since 3.12 -``` -val from_file : file_name -> in_channel -``` -An alias for [`Scanning.open_in`](./#val-open_in) above. - -``` -val from_file_bin : string -> in_channel -``` -An alias for [`Scanning.open_in_bin`](./#val-open_in_bin) above. - -``` -val from_string : string -> in_channel -``` -`Scanning.from_string s` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached. - -``` -val from_function : (unit -> char) -> in_channel -``` -`Scanning.from_function f` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel with the given function as its reading method. - -When scanning needs one more character, the given function is called. - -When the function has no more character to provide, it *must* signal an end-of-input condition by raising the exception `End_of_file`. - -``` -val from_channel : in_channel -> in_channel -``` -`Scanning.from_channel ic` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the regular [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) input channel `ic` argument. Reading starts at current reading position of `ic`. - -``` -val end_of_input : in_channel -> bool -``` -`Scanning.end_of_input ic` tests the end-of-input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -``` -val beginning_of_input : in_channel -> bool -``` -`Scanning.beginning_of_input ic` tests the beginning of input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -``` -val name_of_input : in_channel -> string -``` -`Scanning.name_of_input ic` returns the name of the character source for the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -since 3.09 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Scanf.md b/docs/api/ml/melange/Stdlib-Scanf.md deleted file mode 100644 index 717b966f9..000000000 --- a/docs/api/ml/melange/Stdlib-Scanf.md +++ /dev/null @@ -1,265 +0,0 @@ - -# Module `Stdlib.Scanf` - -Formatted input functions. - - -## Introduction - - -### Functional input with format strings - -The module [`Scanf`](#) provides formatted input functions or *scanners*. - -The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a *formatted input channel* (or *scanning buffer*) and has type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). The more general formatted input function reads from any scanning buffer and is named `bscanf`. - -Generally speaking, the formatted input functions have 3 arguments: - -- the first argument is a source of characters for the input, -- the second argument is a format string that specifies the values to read, -- the third argument is a *receiver function* that is applied to the values read. -Hence, a typical call to the formatted input function [`Scanf.bscanf`](./#val-bscanf) is `bscanf ic fmt f`, where: - -- `ic` is a source of characters (typically a *formatted input channel* with type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)), -- `fmt` is a format string (the same format strings as those used to print material with module [`Printf`](./Stdlib-Printf.md) or [`Format`](./Stdlib-Format.md)), -- `f` is a function that has as many arguments as the number of values to read in the input according to `fmt`. - -### A simple example - -As suggested above, the expression `bscanf ic "%d" f` reads a decimal integer `n` from the source of characters `ic` and returns `f n`. - -For instance, - -- if we use `stdin` as the source of characters ([`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) is the predefined formatted input channel that reads from standard input), -- if we define the receiver `f` as `let f x = x + 1`, -then `bscanf Scanning.stdin "%d" f` reads an integer `n` from the standard input and returns `f n` (that is `n + 1`). Thus, if we evaluate `bscanf stdin "%d" f`, and then enter `41` at the keyboard, the result we get is `42`. - - -### Formatted input as a functional feature - -The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assignment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time. - -**Unsynchronized accesses** - -Unsynchronized accesses to a [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) may lead to an invalid [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) state. Thus, concurrent accesses to [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)s must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -## Formatted input channel - -``` -module Scanning : sig ... end -``` - -## Type of formatted input functions - -``` -type ('a, 'b, 'c, 'd) scanner = - ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> - 'c -``` -The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic`. - -For instance, the [`Scanf.scanf`](./#val-scanf) function below has type `('a, 'b, 'c, 'd) scanner`, since it is a formatted input function that reads from [`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin): `scanf fmt f` applies `f` to the arguments specified by `fmt`, reading those arguments from [`Stdlib.stdin`](./Stdlib.md#val-stdin) as expected. - -If the format `fmt` has some `%r` indications, the corresponding formatted input functions must be provided *before* receiver function `f`. For instance, if `read_elem` is an input function for values of type `t`, then `bscanf ic "%r;" read_elem f` reads a value `v` of type `t` followed by a `';'` character, and returns `f v`. - -since 3.10 -``` -type ('a, 'b, 'c, 'd) scanner_opt = - ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) format6 -> - 'c -``` -``` -exception Scan_failure of string -``` -When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan_failure`. - - -## The general formatted input function - -``` -val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner -``` -`bscanf ic fmt r1 ... rN f` reads characters from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic` and converts them to values according to format string `fmt`. As a final step, receiver function `f` is applied to the values read and gives the result of the `bscanf` call. - -For instance, if `f` is the function `fun s i -> i + 1`, then `Scanf.sscanf "x = 1" "%s = %i" f` returns `2`. - -Arguments `r1` to `rN` are user-defined input functions that read the argument corresponding to the `%r` conversions specified in the format string. - -``` -val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but returns `None` in case of scanning failure. - -since 5.0 - -## Format string description - -The format string is a character string which contains three types of objects: - -- plain characters, which are simply matched with the characters of the input (with a special case for space and line feed, see [The space character in format strings](./#space)), -- conversion specifications, each of which causes reading and conversion of one argument for the function `f` (see [Conversion specifications in format strings](./#conversion)), -- scanning indications to specify boundaries of tokens (see scanning [Scanning indications in format strings](./#indication)). - -### The space character in format strings - -As mentioned above, a plain character in the format string is just matched with the next character of the input; however, two characters are special exceptions to this rule: the space character (`' '` or ASCII code 32) and the line feed character (`'\n'` or ASCII code 10). A space does not match a single space character, but any amount of 'whitespace' in the input. More precisely, a space inside the format string matches *any number* of tab, space, line feed and carriage return characters. Similarly, a line feed character in the format string matches either a single line feed or a carriage return followed by a line feed. - -Matching *any* amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call `bscanf ib "Price = %d $" (fun p -> p)` succeeds and returns `1` when reading an input with various whitespace in it, such as `Price = 1 $`, `Price = 1 $`, or even `Price=1$`. - - -### Conversion specifications in format strings - -Conversion specifications consist in the `%` character, followed by an optional flag, an optional field width, and followed by one or two conversion characters. - -The conversion characters and their meanings are: - -- `d`: reads an optionally signed decimal integer (`0-9`\+). -- `i`: reads an optionally signed integer (usual input conventions for decimal (`0-9`\+), hexadecimal (`0x[0-9a-f]+` and `0X[0-9A-F]+`), octal (`0o[0-7]+`), and binary (`0b[0-1]+`) notations are understood). -- `u`: reads an unsigned decimal integer. -- `x` or `X`: reads an unsigned hexadecimal integer (`[0-9a-fA-F]+`). -- `o`: reads an unsigned octal integer (`[0-7]+`). -- `s`: reads a string argument that spreads as much as possible, until the following bounding condition holds: - - - a whitespace has been found (see [The space character in format strings](./#space)), - - a scanning indication (see scanning [Scanning indications in format strings](./#indication)) has been encountered, - - the end-of-input has been reached. - Hence, this conversion always succeeds: it returns an empty string if the bounding condition holds when the scan begins. - -- `S`: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml). -- `c`: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification `%0c`. Raise `Invalid_argument`, if the field width specification is greater than 1\. -- `C`: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml). -- `f`, `e`, `E`, `g`, `G`: reads an optionally signed floating-point number in decimal notation, in the style `dddd.ddd e/E+-dd`. -- `h`, `H`: reads an optionally signed floating-point number in hexadecimal notation. -- `F`: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned). -- `B`: reads a boolean argument (`true` or `false`). -- `b`: reads a boolean argument (for backward compatibility; do not use in new programs). -- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: reads an `int32` argument to the format specified by the second letter for regular integers. -- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: reads a `nativeint` argument to the format specified by the second letter for regular integers. -- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: reads an `int64` argument to the format specified by the second letter for regular integers. -- `[ range ]`: reads characters that matches one of the characters mentioned in the range of characters `range` (or not mentioned in it, if the range starts with `^`). Reads a `string` that can be empty, if the next input character does not match the range. The set of characters from `c1` to `c2` (inclusively) is denoted by `c1-c2`. Hence, `%[0-9]` returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, `%[0-9a-f]` returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the `^` in case of range negation); hence `[]]` matches a `]` character and `[^]]` matches any character that is not `]`. Use `%%` and `%@` to include a `%` or a `@` in a range. -- `r`: user-defined reader. Takes the next `ri` formatted input function and applies it to the scanning buffer `ib` to read the next argument. The input function `ri` must therefore have type `Scanning.in_channel -> 'a` and the argument read has type `'a`. -- `{ fmt %}`: reads a format string argument. The format string read must have the same type as the format string specification `fmt`. For instance, `"%{ %i %}"` reads any format string that can read a value of type `int`; hence, if `s` is the string `"fmt:\"number is %u\""`, then `Scanf.sscanf s "fmt: %{%i%}"` succeeds and returns the format string `"number is %u"`. -- `( fmt %)`: scanning sub-format substitution. Reads a format string `rf` in the input, then goes on scanning with `rf` instead of scanning with `fmt`. The format string `rf` must have the same type as the format string specification `fmt` that it replaces. For instance, `"%( %i %)"` reads any format string that can read a value of type `int`. The conversion returns the format string read `rf`, and then a value read using `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%(%i%)" (fun fmt i -> fmt, i)` evaluates to `("%4d", 1234)`. This behaviour is not mere format substitution, since the conversion returns the format string read as additional argument. If you need pure format substitution, use special flag `_` to discard the extraneous argument: conversion `%_( fmt %)` reads a format string `rf` and then behaves the same as format string `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%_(%i%)"` is simply equivalent to `Scanf.sscanf "1234.00" "%4d"`. -- `l`: returns the number of lines read so far. -- `n`: returns the number of characters read so far. -- `N` or `L`: returns the number of tokens read so far. -- `!`: matches the end of input condition. -- `%`: matches one `%` character in the input. -- `@`: matches one `@` character in the input. -- `,`: does nothing. -Following the `%` character that introduces a conversion, there may be the special flag `_`: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if `f` is the function `fun i -> i + 1`, and `s` is the string `"x = 1"`, then `Scanf.sscanf s "%_s = %i" f` returns `2`. - -The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, `%6d` reads an integer, having at most 6 decimal digits; `%4f` reads a float with at most 4 characters; and `%8[\000-\255]` returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input). - -Notes: - -- as mentioned above, a `%s` conversion always succeeds, even if there is nothing to read in the input: in this case, it simply returns `""`. -- in addition to the relevant digits, `'_'` characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions. -- the `scanf` facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module `Str`), stream parsers, `ocamllex`\-generated lexers, `ocamlyacc`\-generated parsers. - -### Scanning indications in format strings - -Scanning indications appear just after the string conversions `%s` and `%[ range ]` to delimit the end of the token. A scanning indication is introduced by a `@` character, followed by some plain character `c`. It means that the string token should end just before the next matching `c` (which is skipped). If no `c` character is encountered, the string token spreads as much as possible. For instance, `"%s@\t"` reads a string up to the next tab character or to the end of input. If a `@` character appears anywhere else in the format string, it is treated as a plain character. - -Note: - -- As usual in format strings, `%` and `@` characters must be escaped using `%%` and `%@`; this rule still holds within range specifications and scanning indications. For instance, format `"%s@%%"` reads a string up to the next `%` character, and format `"%s@%@"` reads a string up to the next `@`. -- The scanning indications introduce slight differences in the syntax of [`Scanf`](#) format strings, compared to those used for the [`Printf`](./Stdlib-Printf.md) module. However, the scanning indications are similar to those used in the [`Format`](./Stdlib-Format.md) module; hence, when producing formatted text to be scanned by [`Scanf.bscanf`](./#val-bscanf), it is wise to use printing functions from the [`Format`](./Stdlib-Format.md) module (or, if you need to use functions from [`Printf`](./Stdlib-Printf.md), banish or carefully double check the format strings that contain `'@'` characters). - -### Exceptions during scanning - -Scanners may raise the following exceptions when the input cannot be read according to the format string: - -- Raise [`Scanf.Scan_failure`](./#exception-Scan_failure) if the input does not match the format. -- Raise `Failure` if a conversion to a number is not possible. -- Raise `End_of_file` if the end of input is encountered while some more characters are needed to read the current conversion specification. -- Raise `Invalid_argument` if the format string is invalid. -Note: - -- as a consequence, scanning a `%s` conversion never raises exception `End_of_file`: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or `""` if none were ever read. - -## Specialised formatted input functions - -``` -val sscanf : string -> ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the given string. - -``` -val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt -``` -Same as [`Scanf.sscanf`](./#val-sscanf), but returns `None` in case of scanning failure. - -since 5.0 -``` -val scanf : ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the predefined formatted input channel [`Scanf.Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) that is connected to [`Stdlib.stdin`](./Stdlib.md#val-stdin). - -``` -val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt -``` -Same as [`Scanf.scanf`](./#val-scanf), but returns `None` in case of scanning failure. - -since 5.0 -``` -val kscanf : - Scanning.in_channel -> - (Scanning.in_channel -> exn -> 'd) -> - ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments. - -``` -val ksscanf : - string -> - (Scanning.in_channel -> exn -> 'd) -> - ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.kscanf`](./#val-kscanf) but reads from the given string. - -since 4.02 - -## Reading format strings from input - -``` -val bscanf_format : - Scanning.in_channel -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> - 'g -``` -`bscanf_format ic fmt f` reads a format string token from the formatted input channel `ic`, according to the given format string `fmt`, and applies `f` to the resulting format string value. - -raises [`Scan_failure`](./#exception-Scan_failure) if the format string value read does not have the same type as fmt. -since 3.09 -``` -val sscanf_format : - string -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> - 'g -``` -Same as [`Scanf.bscanf_format`](./#val-bscanf_format), but reads from the given string. - -since 3.09 -``` -val format_from_string : - string -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -``` -`format_from_string s fmt` converts a string argument to a format string, according to the given format string `fmt`. - -raises [`Scan_failure`](./#exception-Scan_failure) if s, considered as a format string, does not have the same type as fmt. -since 3.10 -``` -val unescaped : string -> string -``` -`unescaped s` return a copy of `s` with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, `Scanf.unescaped` has the following property: for all string `s`, `Scanf.unescaped (String.escaped s) = s`. - -Always return a copy of the argument, even if there is no escape sequence in the argument. - -raises [`Scan_failure`](./#exception-Scan_failure) if s is not properly escaped (i.e. s has invalid escape sequences or special characters that are not properly escaped). For instance, Scanf.unescaped "\\"" will fail. -since 4.00 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Seq.md b/docs/api/ml/melange/Stdlib-Seq.md deleted file mode 100644 index fae489474..000000000 --- a/docs/api/ml/melange/Stdlib-Seq.md +++ /dev/null @@ -1,624 +0,0 @@ - -# Module `Stdlib.Seq` - -Sequences. - -A sequence of type `'a Seq.t` can be thought of as a **delayed list**, that is, a list whose elements are computed only when they are demanded by a consumer. This allows sequences to be produced and transformed lazily (one element at a time) rather than eagerly (all elements at once). This also allows constructing conceptually infinite sequences. - -The type `'a Seq.t` is defined as a synonym for `unit -> 'a Seq.node`. This is a function type: therefore, it is opaque. The consumer can **query** a sequence in order to request the next element (if there is one), but cannot otherwise inspect the sequence in any way. - -Because it is opaque, the type `'a Seq.t` does *not* reveal whether a sequence is: - -- **persistent**, which means that the sequence can be used as many times as desired, producing the same elements every time, just like an immutable list; or -- **ephemeral**, which means that the sequence is not persistent. Querying an ephemeral sequence might have an observable side effect, such as incrementing a mutable counter. As a common special case, an ephemeral sequence can be **affine**, which means that it must be queried at most once. -It also does *not* reveal whether the elements of the sequence are: - -- **pre-computed and stored** in memory, which means that querying the sequence is cheap; -- **computed when first demanded and then stored** in memory, which means that querying the sequence once can be expensive, but querying the same sequence again is cheap; or -- **re-computed every time they are demanded**, which may or may not be cheap. -It is up to the programmer to keep these distinctions in mind so as to understand the time and space requirements of sequences. - -For the sake of simplicity, most of the documentation that follows is written under the implicit assumption that the sequences at hand are persistent. We normally do not point out *when* or *how many times* each function is invoked, because that would be too verbose. For instance, in the description of `map`, we write: "if `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`". If we wished to be more explicit, we could point out that the transformation takes place on demand: that is, the elements of `map f xs` are computed only when they are demanded. In other words, the definition `let ys = map f xs` terminates immediately and does not invoke `f`. The function call `f x0` takes place only when the first element of `ys` is demanded, via the function call `ys()`. Furthermore, calling `ys()` twice causes `f x0` to be called twice as well. If one wishes for `f` to be applied at most once to each element of `xs`, even in scenarios where `ys` is queried more than once, then one should use `let ys = memoize (map f xs)`. - -As a general rule, the functions that build sequences, such as `map`, `filter`, `scan`, `take`, etc., produce sequences whose elements are computed only on demand. The functions that eagerly consume sequences, such as `is_empty`, `find`, `length`, `iter`, `fold_left`, etc., are the functions that force computation to take place. - -When possible, we recommend using sequences rather than dispensers (functions of type `unit -> 'a option` that produce elements upon demand). Whereas sequences can be persistent or ephemeral, dispensers are always ephemeral, and are typically more difficult to work with than sequences. Two conversion functions, [`to_dispenser`](./#val-to_dispenser) and [`of_dispenser`](./#val-of_dispenser), are provided. - -since 4.07 -``` -type 'a t = unit -> 'a node -``` -A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. Such a sequence is queried by performing a function application `xs()`. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail. - -``` -and +'a node = -``` -``` -| Nil -``` -``` -| Cons of 'a * 'a t -``` -``` - -``` -A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence. - - -## Consuming sequences - -The functions in this section consume their argument, a sequence, either partially or completely: - -- `is_empty` and `uncons` consume the sequence down to depth 1\. That is, they demand the first argument of the sequence, if there is one. -- `iter`, `fold_left`, `length`, etc., consume the sequence all the way to its end. They terminate only if the sequence is finite. -- `for_all`, `exists`, `find`, etc. consume the sequence down to a certain depth, which is a priori unpredictable. -Similarly, among the functions that consume two sequences, one can distinguish two groups: - -- `iter2` and `fold_left2` consume both sequences all the way to the end, provided the sequences have the same length. -- `for_all2`, `exists2`, `equal`, `compare` consume the sequences down to a certain depth, which is a priori unpredictable. -The functions that consume two sequences can be applied to two sequences of distinct lengths: in that case, the excess elements in the longer sequence are ignored. (It may be the case that one excess element is demanded, even though this element is not used.) - -None of the functions in this section is lazy. These functions are consumers: they force some computation to take place. - -``` -val is_empty : 'a t -> bool -``` -`is_empty xs` determines whether the sequence `xs` is empty. - -It is recommended that the sequence `xs` be persistent. Indeed, `is_empty xs` demands the head of the sequence `xs`, so, if `xs` is ephemeral, it may be the case that `xs` cannot be used any more after this call has taken place. - -since 4.14 -``` -val uncons : 'a t -> ('a * 'a t) option -``` -If `xs` is empty, then `uncons xs` is `None`. - -If `xs` is nonempty, then `uncons xs` is `Some (x, ys)` where `x` is the head of the sequence and `ys` its tail. - -since 4.14 -``` -val length : 'a t -> int -``` -`length xs` is the length of the sequence `xs`. - -The sequence `xs` must be finite. - -since 4.14 -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right. - -It terminates only if the sequence `xs` is finite. - -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right. - -An accumulator of type `'a` is threaded through the calls to `f`. - -It terminates only if the sequence `xs` is finite. - -``` -val iteri : (int -> 'a -> unit) -> 'a t -> unit -``` -`iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`. - -It terminates only if the sequence `xs` is finite. - -`iteri f xs` is equivalent to `iter (fun (i, x) -> f i x) (zip (ints 0) xs)`. - -since 4.14 -``` -val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`. - -An accumulator of type `'b` is threaded through the calls to `f`. - -It terminates only if the sequence `xs` is finite. - -`fold_lefti f accu xs` is equivalent to `fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)`. - -since 4.14 -``` -val for_all : ('a -> bool) -> 'a t -> bool -``` -`for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`. - -The sequence `xs` must be finite. - -since 4.14 -``` -val exists : ('a -> bool) -> 'a t -> bool -``` -`exists xs p` determines whether at least one element `x` of the sequence `xs` satisfies `p x`. - -The sequence `xs` must be finite. - -since 4.14 -``` -val find : ('a -> bool) -> 'a t -> 'a option -``` -`find p xs` returns `Some x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element. - -It returns `None` if there is no such element. - -The sequence `xs` must be finite. - -since 4.14 -``` -val find_index : ('a -> bool) -> 'a t -> int option -``` -`find_index p xs` returns `Some i`, where `i` is the index of the first element of the sequence `xs` that satisfies `p x`, if there is such an element. - -It returns `None` if there is no such element. - -The sequence `xs` must be finite. - -since 5.1 -``` -val find_map : ('a -> 'b option) -> 'a t -> 'b option -``` -`find_map f xs` returns `Some y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`. - -It returns `None` if there is no such element. - -The sequence `xs` must be finite. - -since 4.14 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -The sequence `xs` must be finite. - -since 5.1 -``` -val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit -``` -`iter2 f xs ys` invokes `f x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. - -If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. - -`iter2 f xs ys` is equivalent to `iter (fun (x, y) -> f x y) (zip xs ys)`. - -since 4.14 -``` -val fold_left2 : ('acc -> 'a -> 'b -> 'acc) -> 'acc -> 'a t -> 'b t -> 'acc -``` -`fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. - -An accumulator of type `'a` is threaded through the calls to `f`. - -If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. - -`fold_left2 f accu xs ys` is equivalent to `fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)`. - -since 4.14 -``` -val for_all2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool -``` -`for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`. - -If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if `xs` or `ys` is empty, then `for_all2 p xs ys` is true. This is where `for_all2` and `equal` differ: `equal eq xs ys` can be true only if `xs` and `ys` have the same length. - -At least one of the sequences `xs` and `ys` must be finite. - -`for_all2 p xs ys` is equivalent to `for_all (fun b -> b) (map2 p xs ys)`. - -since 4.14 -``` -val exists2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool -``` -`exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`. - -If the sequences `xs` and `ys` have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -At least one of the sequences `xs` and `ys` must be finite. - -`exists2 p xs ys` is equivalent to `exists (fun b -> b) (map2 p xs ys)`. - -since 4.14 -``` -val equal : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool -``` -Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal. - -At least one of the sequences `xs` and `ys` must be finite. - -since 4.14 -``` -val compare : ('a -> 'b -> int) -> 'a t -> 'b t -> int -``` -Provided the function `cmp` defines a preorder on elements, `compare cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder. - -For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). - -At least one of the sequences `xs` and `ys` must be finite. - -since 4.14 - -## Constructing sequences - -The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. - -``` -val empty : 'a t -``` -`empty` is the empty sequence. It has no elements. Its length is 0. - -``` -val return : 'a -> 'a t -``` -`return x` is the sequence whose sole element is `x`. Its length is 1\. - -``` -val cons : 'a -> 'a t -> 'a t -``` -`cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`. - -Writing `cons (f()) xs` causes the function call `f()` to take place immediately. For this call to be delayed until the sequence is queried, one must instead write `(fun () -> Cons(f(), xs))`. - -since 4.11 -``` -val init : int -> (int -> 'a) -> 'a t -``` -`init n f` is the sequence `f 0; f 1; ...; f (n-1)`. - -`n` must be nonnegative. - -If desired, the infinite sequence `f 0; f 1; ...` can be defined as `map f (ints 0)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.14 -``` -val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t -``` -`unfold` constructs a sequence out of a step function and an initial state. - -If `f u` is `None` then `unfold f u` is the empty sequence. If `f u` is `Some (x, u')` then `unfold f u` is the nonempty sequence `cons x (unfold f u')`. - -For example, `unfold (function [] -> None | h :: t -> Some (h, t)) l` is equivalent to `List.to_seq l`. - -since 4.11 -``` -val repeat : 'a -> 'a t -``` -`repeat x` is the infinite sequence where the element `x` is repeated indefinitely. - -`repeat x` is equivalent to `cycle (return x)`. - -since 4.14 -``` -val forever : (unit -> 'a) -> 'a t -``` -`forever f` is an infinite sequence where every element is produced (on demand) by the function call `f()`. - -For instance, `forever Random.bool` is an infinite sequence of random bits. - -`forever f` is equivalent to `map f (repeat ())`. - -since 4.14 -``` -val cycle : 'a t -> 'a t -``` -`cycle xs` is the infinite sequence that consists of an infinite number of repetitions of the sequence `xs`. - -If `xs` is an empty sequence, then `cycle xs` is empty as well. - -Consuming (a prefix of) the sequence `cycle xs` once can cause the sequence `xs` to be consumed more than once. Therefore, `xs` must be persistent. - -since 4.14 -``` -val iterate : ('a -> 'a) -> 'a -> 'a t -``` -`iterate f x` is the infinite sequence whose elements are `x`, `f x`, `f (f x)`, and so on. - -In other words, it is the orbit of the function `f`, starting at `x`. - -since 4.14 - -## Transforming sequences - -The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f xs` is the image of the sequence `xs` through the transformation `f`. - -If `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`. - -``` -val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t -``` -`mapi` is analogous to `map`, but applies the function `f` to an index and an element. - -`mapi f xs` is equivalent to `map2 f (ints 0) xs`. - -since 4.14 -``` -val filter : ('a -> bool) -> 'a t -> 'a t -``` -`filter p xs` is the sequence of the elements `x` of `xs` that satisfy `p x`. - -In other words, `filter p xs` is the sequence `xs`, deprived of the elements `x` such that `p x` is false. - -``` -val filter_map : ('a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`. - -`filter_map f xs` is equivalent to `map Option.get (filter Option.is_some (map f xs))`. - -``` -val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t -``` -If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators `[a0; a1; a2; ...]` where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on. - -Thus, `scan f a0 xs` is conceptually related to `fold_left f a0 xs`. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators. - -For instance, `scan (+) 0` transforms a sequence of integers into the sequence of its partial sums. - -If `xs` has length `n` then `scan f a0 xs` has length `n+1`. - -since 4.14 -``` -val take : int -> 'a t -> 'a t -``` -`take n xs` is the sequence of the first `n` elements of `xs`. - -If `xs` has fewer than `n` elements, then `take n xs` is equivalent to `xs`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.14 -``` -val drop : int -> 'a t -> 'a t -``` -`drop n xs` is the sequence `xs`, deprived of its first `n` elements. - -If `xs` has fewer than `n` elements, then `drop n xs` is empty. - -`n` must be nonnegative. - -`drop` is lazy: the first `n+1` elements of the sequence `xs` are demanded only when the first element of `drop n xs` is demanded. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.14 -``` -val take_while : ('a -> bool) -> 'a t -> 'a t -``` -`take_while p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`. - -since 4.14 -``` -val drop_while : ('a -> bool) -> 'a t -> 'a t -``` -`drop_while p xs` is the sequence `xs`, deprived of the prefix `take_while p xs`. - -since 4.14 -``` -val group : ('a -> 'a -> bool) -> 'a t -> 'a t t -``` -Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`. - -Every element of `group eq xs` is a nonempty sequence of equal elements. - -The concatenation `concat (group eq xs)` is equal to `xs`. - -Consuming `group eq xs`, and consuming the sequences that it contains, can cause `xs` to be consumed more than once. Therefore, `xs` must be persistent. - -since 4.14 -``` -val memoize : 'a t -> 'a t -``` -The sequence `memoize xs` has the same elements as the sequence `xs`. - -Regardless of whether `xs` is ephemeral or persistent, `memoize xs` is persistent: even if it is queried several times, `xs` is queried at most once. - -The construction of the sequence `memoize xs` internally relies on suspensions provided by the module [`Lazy`](./Stdlib-Lazy.md). These suspensions are *not* thread-safe. Therefore, the sequence `memoize xs` must *not* be queried by multiple threads concurrently. - -since 4.14 -``` -exception Forced_twice -``` -This exception is raised when a sequence returned by [`once`](./#val-once) (or a suffix of it) is queried more than once. - -since 4.14 -``` -val once : 'a t -> 'a t -``` -The sequence `once xs` has the same elements as the sequence `xs`. - -Regardless of whether `xs` is ephemeral or persistent, `once xs` is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception `Forced_twice` is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once. - -raises [`Forced_twice`](./#exception-Forced_twice) if once xs, or a suffix of it, is queried more than once. -since 4.14 -``` -val transpose : 'a t t -> 'a t t -``` -If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`. - -The rows of the matrix `xss` are not required to have the same length. - -The matrix `xss` is not required to be finite (in either direction). - -The matrix `xss` must be persistent. - -since 4.14 - -## Combining sequences - -``` -val append : 'a t -> 'a t -> 'a t -``` -`append xs ys` is the concatenation of the sequences `xs` and `ys`. - -Its elements are the elements of `xs`, followed by the elements of `ys`. - -since 4.11 -``` -val concat : 'a t t -> 'a t -``` -If `xss` is a sequence of sequences, then `concat xss` is its concatenation. - -If `xss` is the sequence `xs0; xs1; ...` then `concat xss` is the sequence `xs0 @ xs1 @ ...`. - -since 4.13 -``` -val flat_map : ('a -> 'b t) -> 'a t -> 'b t -``` -`flat_map f xs` is equivalent to `concat (map f xs)`. - -``` -val concat_map : ('a -> 'b t) -> 'a t -> 'b t -``` -`concat_map f xs` is equivalent to `concat (map f xs)`. - -`concat_map` is an alias for `flat_map`. - -since 4.13 -``` -val zip : 'a t -> 'b t -> ('a * 'b) t -``` -`zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`. - -If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -`zip xs ys` is equivalent to `map2 (fun a b -> (a, b)) xs ys`. - -since 4.14 -``` -val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t -``` -`map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`. - -If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -`map2 f xs ys` is equivalent to `map (fun (x, y) -> f x y) (zip xs ys)`. - -since 4.14 -``` -val interleave : 'a t -> 'a t -> 'a t -``` -`interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on. - -When one of the sequences `xs` and `ys` is exhausted, `interleave xs ys` continues with the rest of the other sequence. - -since 4.14 -``` -val sorted_merge : ('a -> 'a -> int) -> 'a t -> 'a t -> 'a t -``` -If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`. - -For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). - -since 4.14 -``` -val product : 'a t -> 'b t -> ('a * 'b) t -``` -`product xs ys` is the Cartesian product of the sequences `xs` and `ys`. - -For every element `x` of `xs` and for every element `y` of `ys`, the pair `(x, y)` appears once as an element of `product xs ys`. - -The order in which the pairs appear is unspecified. - -The sequences `xs` and `ys` are not required to be finite. - -The sequences `xs` and `ys` must be persistent. - -since 4.14 -``` -val map_product : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t -``` -The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`. - -For every element `x` of `xs` and for every element `y` of `ys`, the element `f x y` appears once as an element of `map_product f xs ys`. - -The order in which these elements appear is unspecified. - -The sequences `xs` and `ys` are not required to be finite. - -The sequences `xs` and `ys` must be persistent. - -`map_product f xs ys` is equivalent to `map (fun (x, y) -> f x y) (product xs ys)`. - -since 4.14 - -## Splitting a sequence into two sequences - -``` -val unzip : ('a * 'b) t -> 'a t * 'b t -``` -`unzip` transforms a sequence of pairs into a pair of sequences. - -`unzip xs` is equivalent to `(map fst xs, map snd xs)`. - -Querying either of the sequences returned by `unzip xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `unzip (memoize xs)`. - -since 4.14 -``` -val split : ('a * 'b) t -> 'a t * 'b t -``` -`split` is an alias for `unzip`. - -since 4.14 -``` -val partition_map : ('a -> ('b, 'c) Either.t) -> 'a t -> 'b t * 'c t -``` -`partition_map f xs` returns a pair of sequences `(ys, zs)`, where: - -- `ys` is the sequence of the elements `y` such that `f x = Left y`, where `x` ranges over `xs`; -- `zs` is the sequence of the elements `z` such that `f x = Right z`, where `x` ranges over `xs`. -`partition_map f xs` is equivalent to a pair of `filter_map Either.find_left (map f xs)` and `filter_map Either.find_right (map f xs)`. - -Querying either of the sequences returned by `partition_map f xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `partition_map f (memoize xs)`. - -since 4.14 -``` -val partition : ('a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition p xs` returns a pair of the subsequence of the elements of `xs` that satisfy `p` and the subsequence of the elements of `xs` that do not satisfy `p`. - -`partition p xs` is equivalent to `filter p xs, filter (fun x -> not (p x)) xs`. - -Consuming both of the sequences returned by `partition p xs` causes `xs` to be consumed twice and causes the function `f` to be applied twice to each element of the list. Therefore, `f` should be pure and cheap. Furthermore, `xs` should be persistent and cheap. If that is not the case, use `partition p (memoize xs)`. - -since 4.14 - -## Converting between sequences and dispensers - -A dispenser is a representation of a sequence as a function of type `unit -> 'a option`. Every time this function is invoked, it returns the next element of the sequence. When there are no more elements, it returns `None`. A dispenser has mutable internal state, therefore is ephemeral: the sequence that it represents can be consumed at most once. - -``` -val of_dispenser : (unit -> 'a option) -> 'a t -``` -`of_dispenser it` is the sequence of the elements produced by the dispenser `it`. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use `memoize (of_dispenser it)`. - -since 4.14 -``` -val to_dispenser : 'a t -> unit -> 'a option -``` -`to_dispenser xs` is a fresh dispenser on the sequence `xs`. - -This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently. - -since 4.14 - -## Sequences of integers - -``` -val ints : int -> int t -``` -`ints i` is the infinite sequence of the integers beginning at `i` and counting up. - -since 4.14 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Set-Make-argument-1-Ord.md b/docs/api/ml/melange/Stdlib-Set-Make-argument-1-Ord.md deleted file mode 100644 index 3abdead73..000000000 --- a/docs/api/ml/melange/Stdlib-Set-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-Set-Make.md b/docs/api/ml/melange/Stdlib-Set-Make.md deleted file mode 100644 index 93d2962e8..000000000 --- a/docs/api/ml/melange/Stdlib-Set-Make.md +++ /dev/null @@ -1,297 +0,0 @@ - -# Module `Set.Make` - -Functor building an implementation of the set structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Sets - -``` -type elt = Ord.t -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : (elt -> bool) -> t -> elt -``` -`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : (elt -> bool) -> t -> elt option -``` -`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : (elt -> bool) -> t -> elt -``` -`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : (elt -> bool) -> t -> elt option -``` -`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : (elt -> unit) -> t -> unit -``` -`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : (elt -> elt) -> t -> t -``` -`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : (elt -> bool) -> t -> t -``` -`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : (elt -> elt option) -> t -> t -``` -`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : (elt -> bool) -> t -> t * t -``` -`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : (elt -> bool) -> t -> bool -``` -`for_all f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : (elt -> bool) -> t -> bool -``` -`exists f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Set-module-type-OrderedType.md b/docs/api/ml/melange/Stdlib-Set-module-type-OrderedType.md deleted file mode 100644 index 11f9d9c0d..000000000 --- a/docs/api/ml/melange/Stdlib-Set-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Set.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-Set-Make.md). - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/ml/melange/Stdlib-Set-module-type-S.md b/docs/api/ml/melange/Stdlib-Set-module-type-S.md deleted file mode 100644 index 72db61d6a..000000000 --- a/docs/api/ml/melange/Stdlib-Set-module-type-S.md +++ /dev/null @@ -1,288 +0,0 @@ - -# Module type `Set.S` - -Output signature of the functor [`Make`](./Stdlib-Set-Make.md). - - -## Sets - -``` -type elt -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-Set-Make.md). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : (elt -> bool) -> t -> elt -``` -`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : (elt -> bool) -> t -> elt option -``` -`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : (elt -> bool) -> t -> elt -``` -`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : (elt -> bool) -> t -> elt option -``` -`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : (elt -> unit) -> t -> unit -``` -`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : (elt -> elt) -> t -> t -``` -`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : (elt -> bool) -> t -> t -``` -`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : (elt -> elt option) -> t -> t -``` -`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : (elt -> bool) -> t -> t * t -``` -`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : (elt -> bool) -> t -> bool -``` -`for_all f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : (elt -> bool) -> t -> bool -``` -`exists f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Set.md b/docs/api/ml/melange/Stdlib-Set.md deleted file mode 100644 index f961f9b00..000000000 --- a/docs/api/ml/melange/Stdlib-Set.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `Stdlib.Set` - -Sets over ordered types. - -This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. - -The [`Make`](./Stdlib-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: - -```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 PairsSet = Set.Make(IntPairs) - - let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) -``` -This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-Set-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-Set-Make.md). - -``` -module Make (Ord : OrderedType) : S with type elt = Ord.t -``` -Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/ml/melange/Stdlib-Stack.md b/docs/api/ml/melange/Stdlib-Stack.md deleted file mode 100644 index e02894994..000000000 --- a/docs/api/ml/melange/Stdlib-Stack.md +++ /dev/null @@ -1,111 +0,0 @@ - -# Module `Stdlib.Stack` - -Last-in first-out stacks. - -This module implements stacks (LIFOs), with in-place modification. - -**Unsynchronized accesses** - -Unsynchronized accesses to a stack may lead to an invalid queue state. Thus, concurrent accesses to stacks must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -type !'a t -``` -The type of stacks containing elements of type `'a`. - -``` -exception Empty -``` -Raised when [`Stack.pop`](./#val-pop) or [`Stack.top`](./#val-top) is applied to an empty stack. - -``` -val create : unit -> 'a t -``` -Return a new stack, initially empty. - -``` -val push : 'a -> 'a t -> unit -``` -`push x s` adds the element `x` at the top of stack `s`. - -``` -val pop : 'a t -> 'a -``` -`pop s` removes and returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. - -``` -val pop_opt : 'a t -> 'a option -``` -`pop_opt s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty. - -since 4.08 -``` -val drop : 'a t -> unit -``` -`drop s` removes the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. - -since 5.1 -``` -val top : 'a t -> 'a -``` -`top s` returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. - -``` -val top_opt : 'a t -> 'a option -``` -`top_opt s` returns the topmost element in stack `s`, or `None` if the stack is empty. - -since 4.08 -``` -val clear : 'a t -> unit -``` -Discard all elements from a stack. - -``` -val copy : 'a t -> 'a t -``` -Return a copy of the given stack. - -``` -val is_empty : 'a t -> bool -``` -Return `true` if the given stack is empty, `false` otherwise. - -``` -val length : 'a t -> int -``` -Return the number of elements in a stack. Time complexity O(1) - -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f s` applies `f` in turn to all elements of `s`, from the element at the top of the stack to the element at the bottom of the stack. The stack itself is unchanged. - -``` -val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold f accu s` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1` is the top of the stack, `x2` the second element, and `xn` the bottom element. The stack is unchanged. - -since 4.03 - -## Stacks and Sequences - -``` -val to_seq : 'a t -> 'a Seq.t -``` -Iterate on the stack, top to bottom. It is safe to modify the stack during iteration. - -since 4.07 -``` -val add_seq : 'a t -> 'a Seq.t -> unit -``` -Add the elements from the sequence on the top of the stack. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a t -``` -Create a stack from the sequence. - -since 4.07 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-StdLabels.md b/docs/api/ml/melange/Stdlib-StdLabels.md deleted file mode 100644 index e90ae87f6..000000000 --- a/docs/api/ml/melange/Stdlib-StdLabels.md +++ /dev/null @@ -1,26 +0,0 @@ - -# Module `Stdlib.StdLabels` - -Standard labeled libraries. - -This meta-module provides versions of the [`Array`](./Stdlib-ArrayLabels.md), [`Bytes`](./Stdlib-BytesLabels.md), [`List`](./Stdlib-ListLabels.md) and [`String`](./Stdlib-StringLabels.md) modules where function arguments are systematically labeled. It is intended to be opened at the top of source files, as shown below. - -```ocaml - open StdLabels - - let to_upper = String.map ~f:Char.uppercase_ascii - let seq len = List.init ~f:(fun i -> i) ~len - let everything = Array.create_matrix ~dimx:42 ~dimy:42 42 -``` -``` -module Array = ArrayLabels -``` -``` -module Bytes = BytesLabels -``` -``` -module List = ListLabels -``` -``` -module String = StringLabels -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-String.md b/docs/api/ml/melange/Stdlib-String.md deleted file mode 100644 index 063536325..000000000 --- a/docs/api/ml/melange/Stdlib-String.md +++ /dev/null @@ -1,480 +0,0 @@ - -# Module `Stdlib.String` - -Strings. - -A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. - -The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. - -``` -positions 0 1 2 3 4 n-1 n - +---+---+---+---+ +-----+ - indices | 0 | 1 | 2 | 3 | ... | n-1 | - +---+---+---+---+ +-----+ -``` -- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. -- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. -Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. - -**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. - -**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - - -## Strings - -``` -type t = string -``` -The type for strings. - -``` -val make : int -> char -> string -``` -`make n c` is a string of length `n` with each index holding the character `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> (int -> char) -> string -``` -`init n f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -since 4.02 -``` -val empty : string -``` -The empty string. - -since 4.13 -``` -val length : string -> int -``` -`length s` is the length (number of bytes/characters) of `s`. - -``` -val get : string -> int -> char -``` -`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. -``` -val of_bytes : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -since 4.13 -``` -val to_bytes : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -since 4.13 -``` -val blit : string -> int -> bytes -> int -> int -> unit -``` -Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. - - -## Concatenating - -**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. - -``` -val concat : string -> string list -> string -``` -`concat sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : string -> string -> string -``` -`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.13 - -## Predicates and comparisons - -``` -val equal : t -> t -> bool -``` -`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. - -since 4.03 (4.05 in StringLabels) -``` -val compare : t -> t -> int -``` -`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. - -``` -val starts_with : prefix:string -> string -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:string -> string -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 -``` -val contains_from : string -> int -> char -> bool -``` -`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : string -> int -> char -> bool -``` -`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val contains : string -> char -> bool -``` -`contains s c` is [`String.contains_from`](./#val-contains_from)` s 0 c`. - - -## Extracting substrings - -``` -val sub : string -> int -> int -> string -``` -`sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. -``` -val split_on_char : char -> string -> string list -``` -`split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. - -The function's result is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). -- No string in the result contains the `sep` character. -since 4.04 (4.05 in StringLabels) - -## Transforming - -``` -val map : (char -> char) -> string -> string -``` -`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. - -since 4.00 -``` -val mapi : (int -> char -> char) -> string -> string -``` -`mapi f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. - -since 4.02 -``` -val fold_left : ('acc -> char -> 'acc) -> 'acc -> string -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. - -since 4.13 -``` -val fold_right : (char -> 'acc -> 'acc) -> string -> 'acc -> 'acc -``` -`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. - -since 4.13 -``` -val for_all : (char -> bool) -> string -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : (char -> bool) -> string -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : string -> string -``` -`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. - -since 4.00 -``` -val escaped : string -> string -``` -`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. - -All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). - -The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val uppercase_ascii : string -> string -``` -`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val lowercase_ascii : string -> string -``` -`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val capitalize_ascii : string -> string -``` -`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val uncapitalize_ascii : string -> string -``` -`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) - -## Traversing - -``` -val iter : (char -> unit) -> string -> unit -``` -`iter f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. - -``` -val iteri : (int -> char -> unit) -> string -> unit -``` -`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. - -since 4.00 - -## Searching - -``` -val index_from : string -> int -> char -> int -``` -`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -``` -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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : string -> int -> char -> int -``` -`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -``` -val rindex_from_opt : string -> int -> char -> int option -``` -`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val index : string -> char -> int -``` -`index s c` is [`String.index_from`](./#val-index_from)` s 0 c`. - -``` -val index_opt : string -> char -> int option -``` -`index_opt s c` is [`String.index_from_opt`](./#val-index_from_opt)` s 0 c`. - -since 4.05 -``` -val rindex : string -> char -> int -``` -`rindex s c` is [`String.rindex_from`](./#val-rindex_from)` s (length s - 1) c`. - -``` -val rindex_opt : string -> char -> int option -``` -`rindex_opt s c` is [`String.rindex_from_opt`](./#val-rindex_from_opt)` s (length s - 1) c`. - -since 4.05 - -## Strings and Sequences - -``` -val to_seq : t -> char Seq.t -``` -`to_seq s` is a sequence made of the string's characters in increasing order. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -`of_seq s` is a string made of the sequence's characters. - -since 4.07 - -## UTF decoding and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary decoding of integers - -The functions in this section binary decode integers from strings. - -All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. - -``` -val get_uint8 : string -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int8 : string -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_ne : string -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_be : string -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_le : string -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_ne : string -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_be : string -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_le : string -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_ne : string -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val hash : t -> int -``` -An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.0 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.0 -``` -val get_int32_be : string -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_le : string -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_ne : string -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_be : string -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_le : string -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. - -since 4.13 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-StringLabels.md b/docs/api/ml/melange/Stdlib-StringLabels.md deleted file mode 100644 index c969a00a3..000000000 --- a/docs/api/ml/melange/Stdlib-StringLabels.md +++ /dev/null @@ -1,486 +0,0 @@ - -# Module `Stdlib.StringLabels` - -Strings. - -A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. - -The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. - -``` -positions 0 1 2 3 4 n-1 n - +---+---+---+---+ +-----+ - indices | 0 | 1 | 2 | 3 | ... | n-1 | - +---+---+---+---+ +-----+ -``` -- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. -- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. -Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. - -**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. - -**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - - -## Strings - -``` -type t = string -``` -The type for strings. - -``` -val make : int -> char -> string -``` -`make n c` is a string of length `n` with each index holding the character `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> f:(int -> char) -> string -``` -`init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -since 4.02 -``` -val empty : string -``` -The empty string. - -since 4.13 -``` -val length : string -> int -``` -`length s` is the length (number of bytes/characters) of `s`. - -``` -val get : string -> int -> char -``` -`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. -``` -val of_bytes : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -since 4.13 -``` -val to_bytes : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -since 4.13 -``` -val blit : - src:string -> - src_pos:int -> - dst:bytes -> - dst_pos:int -> - len:int -> - unit -``` -Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. - - -## Concatenating - -**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. - -``` -val concat : sep:string -> string list -> string -``` -`concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : string -> string -> string -``` -`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.13 - -## Predicates and comparisons - -``` -val equal : t -> t -> bool -``` -`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. - -since 4.03 (4.05 in StringLabels) -``` -val compare : t -> t -> int -``` -`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. - -``` -val starts_with : prefix:string -> string -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:string -> string -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 -``` -val contains_from : string -> int -> char -> bool -``` -`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : string -> int -> char -> bool -``` -`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val contains : string -> char -> bool -``` -`contains s c` is [`String.contains_from`](./Stdlib-String.md#val-contains_from)` s 0 c`. - - -## Extracting substrings - -``` -val sub : string -> pos:int -> len:int -> string -``` -`sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. -``` -val split_on_char : sep:char -> string -> string list -``` -`split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. - -The function's result is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). -- No string in the result contains the `sep` character. -since 4.04 (4.05 in StringLabels) - -## Transforming - -``` -val map : f:(char -> char) -> string -> string -``` -`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. - -since 4.00 -``` -val mapi : f:(int -> char -> char) -> string -> string -``` -`mapi ~f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. - -since 4.02 -``` -val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> string -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. - -since 4.13 -``` -val fold_right : f:(char -> 'acc -> 'acc) -> string -> init:'acc -> 'acc -``` -`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. - -since 4.13 -``` -val for_all : f:(char -> bool) -> string -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : f:(char -> bool) -> string -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : string -> string -``` -`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. - -since 4.00 -``` -val escaped : string -> string -``` -`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. - -All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). - -The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val uppercase_ascii : string -> string -``` -`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val lowercase_ascii : string -> string -``` -`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val capitalize_ascii : string -> string -``` -`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val uncapitalize_ascii : string -> string -``` -`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) - -## Traversing - -``` -val iter : f:(char -> unit) -> string -> unit -``` -`iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. - -``` -val iteri : f:(int -> char -> unit) -> string -> unit -``` -`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. - -since 4.00 - -## Searching - -``` -val index_from : string -> int -> char -> int -``` -`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -``` -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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : string -> int -> char -> int -``` -`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -``` -val rindex_from_opt : string -> int -> char -> int option -``` -`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val index : string -> char -> int -``` -`index s c` is [`String.index_from`](./Stdlib-String.md#val-index_from)` s 0 c`. - -``` -val index_opt : string -> char -> int option -``` -`index_opt s c` is [`String.index_from_opt`](./Stdlib-String.md#val-index_from_opt)` s 0 c`. - -since 4.05 -``` -val rindex : string -> char -> int -``` -`rindex s c` is [`String.rindex_from`](./Stdlib-String.md#val-rindex_from)` s (length s - 1) c`. - -``` -val rindex_opt : string -> char -> int option -``` -`rindex_opt s c` is [`String.rindex_from_opt`](./Stdlib-String.md#val-rindex_from_opt)` s (length s - 1) c`. - -since 4.05 - -## Strings and Sequences - -``` -val to_seq : t -> char Seq.t -``` -`to_seq s` is a sequence made of the string's characters in increasing order. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -`of_seq s` is a string made of the sequence's characters. - -since 4.07 - -## UTF decoding and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary decoding of integers - -The functions in this section binary decode integers from strings. - -All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. - -``` -val get_uint8 : string -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int8 : string -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_ne : string -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_be : string -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_le : string -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_ne : string -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_be : string -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_le : string -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_ne : string -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val hash : t -> int -``` -An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.0 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.0 -``` -val get_int32_be : string -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_le : string -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_ne : string -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_be : string -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_le : string -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. - -since 4.13 \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md deleted file mode 100644 index 8c2c620d7..000000000 --- a/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Parameter `Make.Immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md deleted file mode 100644 index 08e19ba97..000000000 --- a/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Parameter `Make.Non_immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make.md deleted file mode 100644 index deef830ee..000000000 --- a/docs/api/ml/melange/Stdlib-Sys-Immediate64-Make.md +++ /dev/null @@ -1,33 +0,0 @@ - -# Module `Immediate64.Make` - - -## Parameters - -``` -module Immediate : Immediate -``` -``` -module Non_immediate : Non_immediate -``` - -## Signature - -``` -type t -``` -``` -type 'a repr = -``` -``` -| Immediate : Immediate.t repr -``` -``` -| Non_immediate : Non_immediate.t repr -``` -``` - -``` -``` -val repr : t repr -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md deleted file mode 100644 index f63bbba0a..000000000 --- a/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Module type `Immediate64.Immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md deleted file mode 100644 index d4d3814fd..000000000 --- a/docs/api/ml/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Module type `Immediate64.Non_immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Sys-Immediate64.md b/docs/api/ml/melange/Stdlib-Sys-Immediate64.md deleted file mode 100644 index 79e8eb8ca..000000000 --- a/docs/api/ml/melange/Stdlib-Sys-Immediate64.md +++ /dev/null @@ -1,18 +0,0 @@ - -# Module `Sys.Immediate64` - -This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. - -since 4.10 -``` -module type Non_immediate = sig ... end -``` -``` -module type Immediate = sig ... end -``` -``` -module Make - (Immediate : Immediate) - (Non_immediate : Non_immediate) : - sig ... end -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Sys.md b/docs/api/ml/melange/Stdlib-Sys.md deleted file mode 100644 index af5584b69..000000000 --- a/docs/api/ml/melange/Stdlib-Sys.md +++ /dev/null @@ -1,476 +0,0 @@ - -# Module `Stdlib.Sys` - -System interface. - -Every function in this module raises `Sys_error` with an informative message when the underlying system call signal an error. - -``` -val argv : string array -``` -The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program. - -``` -val executable_name : string -``` -The name of the file containing the executable currently running. This name may be absolute or relative to the current directory, depending on the platform and whether the program was compiled to bytecode or a native executable. - -``` -val file_exists : string -> bool -``` -Test if a file with the given name exists. - -``` -val is_directory : string -> bool -``` -Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. -since 3.10 -``` -val is_regular_file : string -> bool -``` -Returns `true` if the given name refers to a regular file, `false` if it refers to another kind of file. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. -since 5.1 -``` -val remove : string -> unit -``` -Remove the given file name from the file system. - -``` -val rename : string -> string -> unit -``` -Rename a file or directory. `rename oldpath newpath` renames the file or directory called `oldpath`, giving it `newpath` as its new name, moving it between (parent) directories if needed. If a file named `newpath` already exists, its contents will be replaced with those of `oldpath`. Depending on the operating system, the metadata (permissions, owner, etc) of `newpath` can either be preserved or be replaced by those of `oldpath`. - -since 4.06 concerning the "replace existing file" behavior -``` -val getenv : string -> string -``` -Return the value associated to a variable in the process environment. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if the variable is unbound. -``` -val getenv_opt : string -> string option -``` -Return the value associated to a variable in the process environment or `None` if the variable is unbound. - -since 4.05 -``` -val command : string -> int -``` -Execute the given shell command and return its exit code. - -The argument of [`Sys.command`](./#val-command) is generally the name of a command followed by zero, one or several arguments, separated by whitespace. The given argument is interpreted by a shell: either the Windows shell `cmd.exe` for the Win32 ports of OCaml, or the POSIX shell `sh` for other ports. It can contain shell builtin commands such as `echo`, and also special characters such as file redirections `>` and `<`, which will be honored by the shell. - -Conversely, whitespace or special shell characters occurring in command names or in their arguments must be quoted or escaped so that the shell does not interpret them. The quoting rules vary between the POSIX shell and the Windows shell. The [`Filename.quote_command`](./Stdlib-Filename.md#val-quote_command) performs the appropriate quoting given a command name, a list of arguments, and optional file redirections. - -``` -val time : unit -> float -``` -Return the processor time, in seconds, used by the program since the beginning of execution. - -``` -val chdir : string -> unit -``` -Change the current working directory of the process. - -``` -val mkdir : string -> int -> unit -``` -Create a directory with the given permissions. - -since 4.12 -``` -val rmdir : string -> unit -``` -Remove an empty directory. - -since 4.12 -``` -val getcwd : unit -> string -``` -Return the current working directory of the process. - -``` -val readdir : string -> string array -``` -Return the names of all files present in the given directory. Names denoting the current directory and the parent directory (`"."` and `".."` in Unix) are not returned. Each string in the result is a file name rather than a complete path. There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order. - -``` -val interactive : bool ref -``` -This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`. - -alert unsynchronized\_access The interactive status is a mutable global state. -``` -val os_type : string -``` -Operating system currently executing the OCaml program. One of - -- `"Unix"` (for all Unix versions, including Linux and Mac OS X), -- `"Win32"` (for MS-Windows, OCaml compiled with MSVC++ or MinGW-w64), -- `"Cygwin"` (for MS-Windows, OCaml compiled with Cygwin). -``` -type backend_type = -``` -``` -| Native -``` -``` -| Bytecode -``` -``` -| Other of string -``` -``` - -``` -Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript. - -since 4.04 -``` -val backend_type : backend_type -``` -Backend type currently executing the OCaml program. - -since 4.04 -``` -val unix : bool -``` -True if `Sys.os_type = "Unix"`. - -since 4.01 -``` -val win32 : bool -``` -True if `Sys.os_type = "Win32"`. - -since 4.01 -``` -val cygwin : bool -``` -True if `Sys.os_type = "Cygwin"`. - -since 4.01 -``` -val word_size : int -``` -Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64. - -``` -val int_size : int -``` -Size of `int`, in bits. It is 31 (resp. 63) when using OCaml on a 32-bit (resp. 64-bit) platform. It may differ for other implementations, e.g. it can be 32 bits when compiling to JavaScript. - -since 4.03 -``` -val big_endian : bool -``` -Whether the machine currently executing the Caml program is big-endian. - -since 4.00 -``` -val max_string_length : int -``` -Maximum length of strings and byte sequences. - -``` -val max_array_length : int -``` -Maximum length of a normal array (i.e. any array whose elements are not of type `float`). The maximum length of a `float array` is `max_floatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with `--disable-flat-float-array`. - -``` -val max_floatarray_length : int -``` -Maximum length of a floatarray. This is also the maximum length of a `float array` when OCaml is configured with `--enable-flat-float-array`. - -``` -val runtime_variant : unit -> string -``` -Return the name of the runtime variant the program is running on. This is normally the argument given to `-runtime-variant` at compile time, but for byte-code it can be changed after compilation. - -since 4.03 -``` -val runtime_parameters : unit -> string -``` -Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable. - -since 4.03 - -## Signal handling - -``` -type signal_behavior = -``` -``` -| Signal_default -``` -``` -| Signal_ignore -``` -``` -| Signal_handle of int -> unit -``` -``` - -``` -What to do when receiving a signal: - -- `Signal_default`: take the default behavior (usually: abort the program) -- `Signal_ignore`: ignore the signal -- `Signal_handle f`: call function `f`, giving it the signal number as argument. -``` -val signal : int -> signal_behavior -> signal_behavior -``` -Set the behavior of the system on receipt of a given signal. The first argument is the signal number. Return the behavior previously associated with the signal. If the signal number is invalid (or not available on your system), an `Invalid_argument` exception is raised. - -``` -val set_signal : int -> signal_behavior -> unit -``` -Same as [`Sys.signal`](./#val-signal) but return value is ignored. - - -### Signal numbers for the standard POSIX signals. - -``` -val sigabrt : int -``` -Abnormal termination - -``` -val sigalrm : int -``` -Timeout - -``` -val sigfpe : int -``` -Arithmetic exception - -``` -val sighup : int -``` -Hangup on controlling terminal - -``` -val sigill : int -``` -Invalid hardware instruction - -``` -val sigint : int -``` -Interactive interrupt (ctrl-C) - -``` -val sigkill : int -``` -Termination (cannot be ignored) - -``` -val sigpipe : int -``` -Broken pipe - -``` -val sigquit : int -``` -Interactive termination - -``` -val sigsegv : int -``` -Invalid memory reference - -``` -val sigterm : int -``` -Termination - -``` -val sigusr1 : int -``` -Application-defined signal 1 - -``` -val sigusr2 : int -``` -Application-defined signal 2 - -``` -val sigchld : int -``` -Child process terminated - -``` -val sigcont : int -``` -Continue - -``` -val sigstop : int -``` -Stop - -``` -val sigtstp : int -``` -Interactive stop - -``` -val sigttin : int -``` -Terminal read from background process - -``` -val sigttou : int -``` -Terminal write from background process - -``` -val sigvtalrm : int -``` -Timeout in virtual time - -``` -val sigprof : int -``` -Profiling interrupt - -``` -val sigbus : int -``` -Bus error - -since 4.03 -``` -val sigpoll : int -``` -Pollable event - -since 4.03 -``` -val sigsys : int -``` -Bad argument to routine - -since 4.03 -``` -val sigtrap : int -``` -Trace/breakpoint trap - -since 4.03 -``` -val sigurg : int -``` -Urgent condition on socket - -since 4.03 -``` -val sigxcpu : int -``` -Timeout in cpu time - -since 4.03 -``` -val sigxfsz : int -``` -File size limit exceeded - -since 4.03 -``` -exception Break -``` -Exception raised on interactive interrupt if [`Sys.catch_break`](./#val-catch_break) is enabled. - -``` -val catch_break : bool -> unit -``` -`catch_break` governs whether interactive interrupt (ctrl-C) terminates the program or raises the `Break` exception. Call `catch_break true` to enable raising `Break`, and `catch_break false` to let the system terminate the program on user interrupt. - -Inside multi-threaded programs, the `Break` exception will arise in any one of the active threads, and will keep arising on further interactive interrupt until all threads are terminated. Use signal masks from `Thread.sigmask` to direct the interrupt towards a specific thread. - -``` -val ocaml_version : string -``` -`ocaml_version` is the version of OCaml. It is a string of the form `"major.minor[.patchlevel][(+|~)additional-info]"`, where `major`, `minor`, and `patchlevel` are integers, and `additional-info` is an arbitrary string. The `[.patchlevel]` part was absent before version 3.08.0 and became mandatory from 3.08.0 onwards. The `[(+|~)additional-info]` part may be absent. - -``` -val development_version : bool -``` -`true` if this is a development version, `false` otherwise. - -since 4.14 -``` -type extra_prefix = -``` -``` -| Plus -``` -``` -| Tilde -``` -since 4.14 -``` - -``` -``` -type extra_info = extra_prefix * string -``` -since 4.14 -``` -type ocaml_release_info = { -``` -`major : int;` -`minor : int;` -`patchlevel : int;` -`extra : extra_info option;` -``` -} -``` -since 4.14 -``` -val ocaml_release : ocaml_release_info -``` -`ocaml_release` is the version of OCaml. - -since 4.14 -``` -val enable_runtime_warnings : bool -> unit -``` -Control whether the OCaml runtime system can emit warnings on stderr. Currently, the only supported warning is triggered when a channel created by `open_*` functions is finalized without being closed. Runtime warnings are disabled by default. - -since 4.03 -alert unsynchronized\_access The status of runtime warnings is a mutable global state. -``` -val runtime_warnings_enabled : unit -> bool -``` -Return whether runtime warnings are currently enabled. - -since 4.03 -alert unsynchronized\_access The status of runtime warnings is a mutable global state. - -## Optimization - -``` -val opaque_identity : 'a -> 'a -``` -For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function. - -At runtime, `opaque_identity` disappears altogether. However, it does prevent the argument from being garbage collected until the location where the call would have occurred. - -A typical use of this function is to prevent pure computations from being optimized away in benchmarking loops. For example: - -```ocaml - for _round = 1 to 100_000 do - ignore (Sys.opaque_identity (my_pure_computation ())) - done -``` -since 4.03 -``` -module Immediate64 : sig ... end -``` -This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. diff --git a/docs/api/ml/melange/Stdlib-Type-Id.md b/docs/api/ml/melange/Stdlib-Type-Id.md deleted file mode 100644 index 39402a663..000000000 --- a/docs/api/ml/melange/Stdlib-Type-Id.md +++ /dev/null @@ -1,80 +0,0 @@ - -# Module `Type.Id` - -Type identifiers. - -A type identifier is a value that denotes a type. Given two type identifiers, they can be tested for [equality](./#val-provably_equal) to prove they denote the same type. Note that: - -- Unequal identifiers do not imply unequal types: a given type can be denoted by more than one identifier. -- Type identifiers can be marshalled, but they get a new, distinct, identity on unmarshalling, so the equalities are lost. -See an [example](./#example) of use. - - -## Type identifiers - -``` -type !'a t -``` -The type for identifiers for type `'a`. - -``` -val make : unit -> 'a t -``` -`make ()` is a new type identifier. - -``` -val uid : 'a t -> int -``` -`uid id` is a runtime unique identifier for `id`. - -``` -val provably_equal : 'a t -> 'b t -> ('a, 'b) eq option -``` -`provably_equal i0 i1` is `Some Equal` if identifier `i0` is equal to `i1` and `None` otherwise. - - -## Example - -The following shows how type identifiers can be used to implement a simple heterogeneous key-value dictionary. In contrast to [`Stdlib.Map`](./Stdlib-Map.md) values whose keys map to a single, homogeneous type of values, this dictionary can associate a different type of value to each key. - -```ocaml -(** Heterogeneous dictionaries. *) -module Dict : sig - type t - (** The type for dictionaries. *) - - type 'a key - (** The type for keys binding values of type ['a]. *) - - val key : unit -> 'a key - (** [key ()] is a new dictionary key. *) - - val empty : t - (** [empty] is the empty dictionary. *) - - val add : 'a key -> 'a -> t -> t - (** [add k v d] is [d] with [k] bound to [v]. *) - - val remove : 'a key -> t -> t - (** [remove k d] is [d] with the last binding of [k] removed. *) - - val find : 'a key -> t -> 'a option - (** [find k d] is the binding of [k] in [d], if any. *) -end = struct - type 'a key = 'a Type.Id.t - type binding = B : 'a key * 'a -> binding - type t = (int * binding) list - - let key () = Type.Id.make () - let empty = [] - let add k v d = (Type.Id.uid k, B (k, v)) :: d - let remove k d = List.remove_assoc (Type.Id.uid k) d - let find : type a. a key -> t -> a option = fun k d -> - match List.assoc_opt (Type.Id.uid k) d with - | None -> None - | Some (B (k', v)) -> - match Type.Id.provably_equal k k' with - | Some Type.Equal -> Some v - | None -> assert false -end -``` \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Type.md b/docs/api/ml/melange/Stdlib-Type.md deleted file mode 100644 index 0a071fda8..000000000 --- a/docs/api/ml/melange/Stdlib-Type.md +++ /dev/null @@ -1,36 +0,0 @@ - -# Module `Stdlib.Type` - -Type introspection. - -since 5.1 - -## Type equality witness - -``` -type (_, _) eq = -``` -``` -| Equal : ('a, 'a) eq -``` -``` - -``` -The purpose of `eq` is to represent type equalities that may not otherwise be known by the type checker (e.g. because they may depend on dynamic data). - -A value of type `(a, b) eq` represents the fact that types `a` and `b` are equal. - -If one has a value `eq : (a, b) eq` that proves types `a` and `b` are equal, one can use it to convert a value of type `a` to a value of type `b` by pattern matching on `Equal`: - -```ocaml - let cast (type a) (type b) (Equal : (a, b) Type.eq) (a : a) : b = a -``` -At runtime, this function simply returns its second argument unchanged. - - -## Type identifiers - -``` -module Id : sig ... end -``` -Type identifiers. diff --git a/docs/api/ml/melange/Stdlib-Uchar.md b/docs/api/ml/melange/Stdlib-Uchar.md deleted file mode 100644 index a90cfee5e..000000000 --- a/docs/api/ml/melange/Stdlib-Uchar.md +++ /dev/null @@ -1,144 +0,0 @@ - -# Module `Stdlib.Uchar` - -Unicode characters. - -since 4.03 -``` -type t -``` -The type for Unicode characters. - -A value of this type represents a Unicode [scalar value](http://unicode.org/glossary/#unicode_scalar_value) which is an integer in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`. - -``` -val min : t -``` -`min` is U+0000. - -``` -val max : t -``` -`max` is U+10FFFF. - -``` -val bom : t -``` -`bom` is U+FEFF, the [byte order mark](http://unicode.org/glossary/#byte_order_mark) (BOM) character. - -since 4.06 -``` -val rep : t -``` -`rep` is U+FFFD, the [replacement](http://unicode.org/glossary/#replacement_character) character. - -since 4.06 -``` -val succ : t -> t -``` -`succ u` is the scalar value after `u` in the set of Unicode scalar values. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is max. -``` -val pred : t -> t -``` -`pred u` is the scalar value before `u` in the set of Unicode scalar values. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is min. -``` -val is_valid : int -> bool -``` -`is_valid n` is `true` if and only if `n` is a Unicode scalar value (i.e. in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`). - -``` -val of_int : int -> t -``` -`of_int i` is `i` as a Unicode character. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i does not satisfy is\_valid. -``` -val to_int : t -> int -``` -`to_int u` is `u` as an integer. - -``` -val is_char : t -> bool -``` -`is_char u` is `true` if and only if `u` is a latin1 OCaml character. - -``` -val of_char : char -> t -``` -`of_char c` is `c` as a Unicode character. - -``` -val to_char : t -> char -``` -`to_char u` is `u` as an OCaml latin1 character. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u does not satisfy is\_char. -``` -val equal : t -> t -> bool -``` -`equal u u'` is `u = u'`. - -``` -val compare : t -> t -> int -``` -`compare u u'` is `Stdlib.compare u u'`. - -``` -val seeded_hash : int -> t -> int -``` -`seeded_hash seed u` A seeded hash function with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.3 -``` -val hash : t -> int -``` -An unseeded hash function with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.3 - -## UTF codecs tools - -since 4.14 -``` -type utf_decode -``` -The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt. - -``` -val utf_decode_is_valid : utf_decode -> bool -``` -`utf_decode_is_valid d` is `true` if and only if `d` holds a valid decode. - -``` -val utf_decode_uchar : utf_decode -> t -``` -`utf_decode_uchar d` is the Unicode character decoded by `d` if `utf_decode_is_valid d` is `true` and [`Uchar.rep`](./#val-rep) otherwise. - -``` -val utf_decode_length : utf_decode -> int -``` -`utf_decode_length d` is the number of elements from the source that were consumed by the decode `d`. This is always strictly positive and smaller or equal to `4`. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes. - -``` -val utf_decode : int -> t -> utf_decode -``` -`utf_decode n u` is a valid UTF decode for `u` that consumed `n` elements from the source for decoding. `n` must be positive and smaller or equal to `4` (this is not checked by the module). - -``` -val utf_decode_invalid : int -> utf_decode -``` -`utf_decode_invalid n` is an invalid UTF decode that consumed `n` elements from the source to error. `n` must be positive and smaller or equal to `4` (this is not checked by the module). The resulting decode has [`rep`](./#val-rep) as the decoded Unicode character. - -``` -val utf_8_byte_length : t -> int -``` -`utf_8_byte_length u` is the number of bytes needed to encode `u` in UTF-8. - -``` -val utf_16_byte_length : t -> int -``` -`utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16. diff --git a/docs/api/ml/melange/Stdlib-Unit.md b/docs/api/ml/melange/Stdlib-Unit.md deleted file mode 100644 index 50428889e..000000000 --- a/docs/api/ml/melange/Stdlib-Unit.md +++ /dev/null @@ -1,36 +0,0 @@ - -# Module `Stdlib.Unit` - -Unit values. - -since 4.08 - -## The unit type - -``` -type t = unit = -``` -``` -| () -``` -``` - -``` -The unit type. - -The constructor `()` is included here so that it has a path, but it is not intended to be used in user-defined data types. - -``` -val equal : t -> t -> bool -``` -`equal u1 u2` is `true`. - -``` -val compare : t -> t -> int -``` -`compare u1 u2` is `0`. - -``` -val to_string : t -> string -``` -`to_string b` is `"()"`. diff --git a/docs/api/ml/melange/Stdlib-Weak-Make-argument-1-H.md b/docs/api/ml/melange/Stdlib-Weak-Make-argument-1-H.md deleted file mode 100644 index 80efdc53c..000000000 --- a/docs/api/ml/melange/Stdlib-Weak-Make-argument-1-H.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Parameter `Make.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/ml/melange/Stdlib-Weak-Make.md b/docs/api/ml/melange/Stdlib-Weak-Make.md deleted file mode 100644 index a9786f098..000000000 --- a/docs/api/ml/melange/Stdlib-Weak-Make.md +++ /dev/null @@ -1,90 +0,0 @@ - -# Module `Weak.Make` - -Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. - - -## Parameters - -``` -module H : Hashtbl.HashedType -``` - -## Signature - -``` -type data = H.t -``` -The type of the elements stored in the table. - -``` -type t -``` -The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. - -``` -val create : int -> t -``` -`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. - -``` -val clear : t -> unit -``` -Remove all elements from the table. - -``` -val merge : t -> data -> data -``` -`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. - -``` -val add : t -> data -> unit -``` -`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. - -``` -val remove : t -> data -> unit -``` -`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. - -``` -val find : t -> data -> data -``` -`find t x` returns an instance of `x` found in `t`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. -``` -val find_opt : t -> data -> data option -``` -`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. - -since 4.05 -``` -val find_all : t -> data -> data list -``` -`find_all t x` returns a list of all the instances of `x` found in `t`. - -``` -val mem : t -> data -> bool -``` -`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. - -``` -val iter : (data -> unit) -> t -> unit -``` -`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val count : t -> int -``` -Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. - -``` -val stats : t -> int * int * int * int * int * int -``` -Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/ml/melange/Stdlib-Weak-module-type-S.md b/docs/api/ml/melange/Stdlib-Weak-module-type-S.md deleted file mode 100644 index 22f814459..000000000 --- a/docs/api/ml/melange/Stdlib-Weak-module-type-S.md +++ /dev/null @@ -1,81 +0,0 @@ - -# Module type `Weak.S` - -The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). - -``` -type data -``` -The type of the elements stored in the table. - -``` -type t -``` -The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. - -``` -val create : int -> t -``` -`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. - -``` -val clear : t -> unit -``` -Remove all elements from the table. - -``` -val merge : t -> data -> data -``` -`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. - -``` -val add : t -> data -> unit -``` -`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. - -``` -val remove : t -> data -> unit -``` -`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. - -``` -val find : t -> data -> data -``` -`find t x` returns an instance of `x` found in `t`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. -``` -val find_opt : t -> data -> data option -``` -`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. - -since 4.05 -``` -val find_all : t -> data -> data list -``` -`find_all t x` returns a list of all the instances of `x` found in `t`. - -``` -val mem : t -> data -> bool -``` -`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. - -``` -val iter : (data -> unit) -> t -> unit -``` -`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val count : t -> int -``` -Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. - -``` -val stats : t -> int * int * int * int * int * int -``` -Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/ml/melange/Stdlib-Weak.md b/docs/api/ml/melange/Stdlib-Weak.md deleted file mode 100644 index 98afcfae4..000000000 --- a/docs/api/ml/melange/Stdlib-Weak.md +++ /dev/null @@ -1,88 +0,0 @@ - -# Module `Stdlib.Weak` - -Arrays of weak pointers and hash sets of weak pointers. - - -## Low-level functions - -``` -type !'a t -``` -The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program. Note that finalisation functions are run before the weak pointers are erased, because the finalisation functions can make values alive again (before 4.03 the finalisation functions were run after). - -A weak pointer is said to be full if it points to a value, empty if the value was erased by the GC. - -Notes: - -- Integers are not allocated and cannot be stored in weak arrays. -- Weak arrays cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) nor the functions of the [`Marshal`](./Stdlib-Marshal.md) module. -``` -val create : int -> 'a t -``` -`Weak.create n` returns a new weak array of length `n`. All the pointers are initially empty. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not comprised between zero and Obj.Ephemeron.max\_ephe\_length (limits included). -``` -val length : 'a t -> int -``` -`Weak.length ar` returns the length (number of elements) of `ar`. - -``` -val set : 'a t -> int -> 'a option -> unit -``` -`Weak.set ar n (Some el)` sets the `n`th cell of `ar` to be a (full) pointer to `el`; `Weak.set ar n None` sets the `n`th cell of `ar` to empty. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -``` -val get : 'a t -> int -> 'a option -``` -`Weak.get ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is the value) if it is full. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -``` -val get_copy : 'a t -> int -> 'a option -``` -`Weak.get_copy ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is a (shallow) copy of the value) if it is full. In addition to pitfalls with mutable values, the interesting difference with `get` is that `get_copy` does not prevent the incremental GC from erasing the value in its current cycle (`get` may delay the erasure to the next GC cycle). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -If the element is a custom block it is not copied. - -``` -val check : 'a t -> int -> bool -``` -`Weak.check ar n` returns `true` if the `n`th cell of `ar` is full, `false` if it is empty. Note that even if `Weak.check ar n` returns `true`, a subsequent [`Weak.get`](./#val-get)` ar n` can return `None`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -``` -val fill : 'a t -> int -> int -> 'a option -> unit -``` -`Weak.fill ar ofs len el` sets to `el` all pointers of `ar` from `ofs` to `ofs + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid subarray of ar. -``` -val blit : 'a t -> int -> 'a t -> int -> int -> unit -``` -`Weak.blit ar1 off1 ar2 off2 len` copies `len` weak pointers from `ar1` (starting at `off1`) to `ar2` (starting at `off2`). It works correctly even if `ar1` and `ar2` are the same. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off1 and len do not designate a valid subarray of ar1, or if off2 and len do not designate a valid subarray of ar2. - -## Weak hash sets - -A weak hash set is a hashed set of values. Each value may magically disappear from the set when it is not used by the rest of the program any more. This is normally used to share data structures without inducing memory leaks. Weak hash sets are defined on values from a [`Hashtbl.HashedType`](./Stdlib-Hashtbl-module-type-HashedType.md) module; the `equal` relation and `hash` function are taken from that module. We will say that `v` is an instance of `x` if `equal x v` is `true`. - -The `equal` relation must be able to work on a shallow copy of the values and give the same result as with the values themselves. - -**Unsynchronized accesses** - -Unsynchronized accesses to weak hash sets are a programming error. Unsynchronized accesses to a weak hash set may lead to an invalid weak hash set state. Thus, concurrent accesses to weak hash sets must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -module type S = sig ... end -``` -The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). - -``` -module Make (H : Hashtbl.HashedType) : S with type data = H.t -``` -Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. diff --git a/docs/api/ml/melange/Stdlib.md b/docs/api/ml/melange/Stdlib.md deleted file mode 100644 index ba13a16e8..000000000 --- a/docs/api/ml/melange/Stdlib.md +++ /dev/null @@ -1,1565 +0,0 @@ - -# Module `Stdlib` - -The OCaml Standard library. - -This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by `Stdlib`. - -In particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the [standard library modules](./#modules). - - -## Exceptions - -``` -val raise : exn -> 'a -``` -Raise the given exception value - -``` -val raise_notrace : exn -> 'a -``` -A faster version `raise` which does not record the backtrace. - -since 4.02 -``` -val invalid_arg : string -> 'a -``` -Raise exception `Invalid_argument` with the given string. - -``` -val failwith : string -> 'a -``` -Raise exception `Failure` with the given string. - -``` -exception Exit -``` -The `Exit` exception is not raised by any library function. It is provided for use in your programs. - -``` -exception Match_failure of string * int * int -``` -Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number). - -``` -exception Assert_failure of string * int * int -``` -Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number). - -``` -exception Invalid_argument of string -``` -Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it. - -``` -exception Failure of string -``` -Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure \_ instead). - -``` -exception Not_found -``` -Exception raised by search functions when the desired object could not be found. - -``` -exception Out_of_memory -``` -Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.) - -``` -exception Stack_overflow -``` -Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program. - -Before 4.10, it was not fully implemented by the native-code compiler. - -``` -exception Sys_error of string -``` -Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys\_error \_ instead). - -``` -exception End_of_file -``` -Exception raised by input functions to signal that the end of file has been reached. - -``` -exception Division_by_zero -``` -Exception raised by integer division and remainder operations when their second argument is zero. - -``` -exception Sys_blocked_io -``` -A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel. - -``` -exception Undefined_recursive_module of string * int * int -``` -Exception raised when an ill-founded recursive module definition is evaluated. The arguments are the location of the definition in the source code (file name, line number, column number). - - -## Comparisons - -``` -val (=) : 'a -> 'a -> bool -``` -`e1 = e2` tests for structural equality of `e1` and `e2`. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises `Invalid_argument`. Equality between cyclic data structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (<>) : 'a -> 'a -> bool -``` -Negation of [`Stdlib.(=)`](./#val-\(=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (<) : 'a -> 'a -> bool -``` -See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (>) : 'a -> 'a -> bool -``` -See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (<=) : 'a -> 'a -> bool -``` -See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (>=) : 'a -> 'a -> bool -``` -Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with `( = )`. As in the case of `( = )`, mutable structures are compared by contents. Comparison between functional values raises `Invalid_argument`. Comparison between cyclic structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val compare : 'a -> 'a -> int -``` -`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. The ordering implemented by `compare` is compatible with the comparison predicates `=`, `<` and `>` defined above, with one difference on the treatment of the float value [`Stdlib.nan`](./#val-nan). Namely, the comparison predicates treat `nan` as different from any other float value, including itself; while `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. - -`compare` applied to functional values may raise `Invalid_argument`. `compare` applied to cyclic structures may not terminate. - -The `compare` function can be used as the comparison function required by the [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md) functors, as well as the [`List.sort`](./Stdlib-List.md#val-sort) and [`Array.sort`](./Stdlib-Array.md#val-sort) functions. - -``` -val min : 'a -> 'a -> 'a -``` -``` -val max : 'a -> 'a -> 'a -``` -``` -val (==) : 'a -> 'a -> bool -``` -`e1 == e2` tests for physical equality of `e1` and `e2`. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, `e1 == e2` is true if and only if physical modification of `e1` also affects `e2`. On non-mutable types, the behavior of `( == )` is implementation-dependent; however, it is guaranteed that `e1 == e2` implies `compare e1 e2 = 0`. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (!=) : 'a -> 'a -> bool -``` -Negation of [`Stdlib.(==)`](./#val-\(==\)). Left-associative operator, see `Ocaml_operators` for more information. - - -## Boolean operations - -``` -val not : bool -> bool -``` -The boolean negation. - -``` -val (&&) : bool -> bool -> bool -``` -The boolean 'and'. Evaluation is sequential, left-to-right: in `e1 && e2`, `e1` is evaluated first, and if it returns `false`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val (||) : bool -> bool -> bool -``` -The boolean 'or'. Evaluation is sequential, left-to-right: in `e1 || e2`, `e1` is evaluated first, and if it returns `true`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. - - -## Debugging - -``` -val __LOC__ : string -``` -`__LOC__` returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". - -since 4.02 -``` -val __FILE__ : string -``` -`__FILE__` returns the name of the file currently being parsed by the compiler. - -since 4.02 -``` -val __LINE__ : int -``` -`__LINE__` returns the line number at which this expression appears in the file currently being parsed by the compiler. - -since 4.02 -``` -val __MODULE__ : string -``` -`__MODULE__` returns the module name of the file being parsed by the compiler. - -since 4.02 -``` -val __POS__ : string * int * int * int -``` -`__POS__` returns a tuple `(file,lnum,cnum,enum)`, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. - -since 4.02 -``` -val __FUNCTION__ : string -``` -`__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes. - -since 4.12 -``` -val __LOC_OF__ : 'a -> string * 'a -``` -`__LOC_OF__ expr` returns a pair `(loc, expr)` where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". - -since 4.02 -``` -val __LINE_OF__ : 'a -> int * 'a -``` -`__LINE_OF__ expr` returns a pair `(line, expr)`, where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler. - -since 4.02 -``` -val __POS_OF__ : 'a -> (string * int * int * int) * 'a -``` -`__POS_OF__ expr` returns a pair `(loc,expr)`, where `loc` is a tuple `(file,lnum,cnum,enum)` corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. - -since 4.02 - -## Composition operators - -``` -val (|>) : 'a -> ('a -> 'b) -> 'b -``` -Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. Left-associative operator, see `Ocaml_operators` for more information. - -since 4.01 -``` -val (@@) : ('a -> 'b) -> 'a -> 'b -``` -Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. Right-associative operator, see `Ocaml_operators` for more information. - -since 4.01 - -## Integer arithmetic - -Integers are `Sys.int_size` bits wide. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. - -``` -val (~-) : int -> int -``` -Unary negation. You can also write `- e` instead of `~- e`. Unary operator, see `Ocaml_operators` for more information. - -``` -val (~+) : int -> int -``` -Unary addition. You can also write `+ e` instead of `~+ e`. Unary operator, see `Ocaml_operators` for more information. - -since 3.12 -``` -val succ : int -> int -``` -`succ x` is `x + 1`. - -``` -val pred : int -> int -``` -`pred x` is `x - 1`. - -``` -val (+) : int -> int -> int -``` -Integer addition. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (-) : int -> int -> int -``` -Integer subtraction. Left-associative operator, , see `Ocaml_operators` for more information. - -``` -val (*) : int -> int -> int -``` -Integer multiplication. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (/) : int -> int -> int -``` -Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if `x >= 0` and `y > 0`, `x / y` is the greatest integer less than or equal to the real quotient of `x` by `y`. Moreover, `(- x) / y = x / (- y) = - (x / y)`. Left-associative operator, see `Ocaml_operators` for more information. - -raises [`Division_by_zero`](./#exception-Division_by_zero) if the second argument is 0. -``` -val (mod) : int -> int -> int -``` -Integer remainder. If `y` is not zero, the result of `x mod y` satisfies the following properties: `x = (x / y) * y + x mod y` and `abs(x mod y) <= abs(y) - 1`. If `y = 0`, `x mod y` raises `Division_by_zero`. Note that `x mod y` is negative only if `x < 0`. Left-associative operator, see `Ocaml_operators` for more information. - -raises [`Division_by_zero`](./#exception-Division_by_zero) if y is zero. -``` -val abs : int -> int -``` -`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. - -``` -val max_int : int -``` -The greatest representable integer. - -``` -val min_int : int -``` -The smallest representable integer. - - -### Bitwise operations - -``` -val (land) : int -> int -> int -``` -Bitwise logical and. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (lor) : int -> int -> int -``` -Bitwise logical or. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (lxor) : int -> int -> int -``` -Bitwise logical exclusive or. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val lnot : int -> int -``` -Bitwise logical negation. - -``` -val (lsl) : int -> int -> int -``` -`n lsl m` shifts `n` to the left by `m` bits. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val (lsr) : int -> int -> int -``` -`n lsr m` shifts `n` to the right by `m` bits. This is a logical shift: zeroes are inserted regardless of the sign of `n`. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val (asr) : int -> int -> int -``` -`n asr m` shifts `n` to the right by `m` bits. This is an arithmetic shift: the sign bit of `n` is replicated. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. - - -## Floating-point arithmetic - -OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... - -``` -val (~-.) : float -> float -``` -Unary negation. You can also write `-. e` instead of `~-. e`. Unary operator, see `Ocaml_operators` for more information. - -``` -val (~+.) : float -> float -``` -Unary addition. You can also write `+. e` instead of `~+. e`. Unary operator, see `Ocaml_operators` for more information. - -since 3.12 -``` -val (+.) : float -> float -> float -``` -Floating-point addition. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (-.) : float -> float -> float -``` -Floating-point subtraction. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (*.) : float -> float -> float -``` -Floating-point multiplication. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (/.) : float -> float -> float -``` -Floating-point division. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (**) : float -> float -> float -``` -Exponentiation. - -``` -val sqrt : float -> float -``` -Square root. - -``` -val exp : float -> float -``` -Exponential. - -``` -val log : float -> float -``` -Natural logarithm. - -``` -val log10 : float -> float -``` -Base 10 logarithm. - -``` -val expm1 : float -> float -``` -`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. - -since 3.12.0 -``` -val log1p : float -> float -``` -`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. - -since 3.12.0 -``` -val cos : float -> float -``` -Cosine. Argument is in radians. - -``` -val sin : float -> float -``` -Sine. Argument is in radians. - -``` -val tan : float -> float -``` -Tangent. Argument is in radians. - -``` -val acos : float -> float -``` -Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. - -``` -val asin : float -> float -``` -Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan : float -> float -``` -Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan2 : float -> float -> float -``` -`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. - -``` -val hypot : float -> float -> float -``` -`hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. - -since 4.00.0 -``` -val cosh : float -> float -``` -Hyperbolic cosine. Argument is in radians. - -``` -val sinh : float -> float -``` -Hyperbolic sine. Argument is in radians. - -``` -val tanh : float -> float -``` -Hyperbolic tangent. Argument is in radians. - -``` -val acosh : float -> float -``` -Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. - -since 4.13.0 -``` -val asinh : float -> float -``` -Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. - -since 4.13.0 -``` -val atanh : float -> float -``` -Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. - -since 4.13.0 -``` -val ceil : float -> float -``` -Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. - -``` -val floor : float -> float -``` -Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. - -``` -val abs_float : float -> float -``` -`abs_float f` returns the absolute value of `f`. - -``` -val copysign : float -> float -> float -``` -`copysign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. - -since 4.00 -``` -val mod_float : float -> float -> float -``` -`mod_float a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. - -``` -val frexp : float -> float * int -``` -`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. - -``` -val ldexp : float -> int -> float -``` -`ldexp x n` returns `x *. 2 ** n`. - -``` -val modf : float -> float * float -``` -`modf f` returns the pair of the fractional and integral part of `f`. - -``` -val float : int -> float -``` -Same as [`Stdlib.float_of_int`](./#val-float_of_int). - -``` -val float_of_int : int -> float -``` -Convert an integer to floating-point. - -``` -val truncate : float -> int -``` -Same as [`Stdlib.int_of_float`](./#val-int_of_float). - -``` -val int_of_float : float -> int -``` -Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. - -``` -val infinity : float -``` -Positive infinity. - -``` -val neg_infinity : float -``` -Negative infinity. - -``` -val nan : float -``` -``` -val max_float : float -``` -The largest positive finite value of type `float`. - -``` -val min_float : float -``` -The smallest positive, non-zero, non-denormalized value of type `float`. - -``` -val epsilon_float : float -``` -The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. - -``` -type fpclass = -``` -``` -| FP_normal -``` -Normal number, none of the below - -``` -| FP_subnormal -``` -Number very close to 0.0, has reduced precision - -``` -| FP_zero -``` -Number is 0.0 or \-0.0 - -``` -| FP_infinite -``` -Number is positive or negative infinity - -``` -| FP_nan -``` -Not a number: result of an undefined operation - -``` - -``` -The five classes of floating-point numbers, as determined by the [`Stdlib.classify_float`](./#val-classify_float) function. - -``` -val classify_float : float -> fpclass -``` - -## String operations - -More string operations are provided in module [`String`](./Stdlib-String.md). - -``` -val (^) : string -> string -> string -``` -String concatenation. Right-associative operator, see `Ocaml_operators` for more information. - -raises [`Invalid_argument`](./#exception-Invalid_argument) if the result is longer then than Sys.max\_string\_length bytes. - -## Character operations - -More character operations are provided in module [`Char`](./Stdlib-Char.md). - -``` -val int_of_char : char -> int -``` -Return the ASCII code of the argument. - -``` -val char_of_int : int -> char -``` -Return the character with the given ASCII code. - -raises [`Invalid_argument`](./#exception-Invalid_argument) if the argument is outside the range 0--255. - -## Unit operations - -``` -val ignore : 'a -> unit -``` -Discard the value of its argument and return `()`. For instance, `ignore(f x)` discards the result of the side-effecting function `f`. It is equivalent to `f x; ()`, except that the latter may generate a compiler warning; writing `ignore(f x)` instead avoids the warning. - - -## String conversion functions - -``` -val string_of_bool : bool -> string -``` -Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly. - -``` -val bool_of_string_opt : string -> bool option -``` -Convert the given string to a boolean. - -Return `None` if the string is not `"true"` or `"false"`. - -since 4.05 -``` -val bool_of_string : string -> bool -``` -Same as [`Stdlib.bool_of_string_opt`](./#val-bool_of_string_opt), but raise `Invalid_argument "bool_of_string"` instead of returning `None`. - -``` -val string_of_int : int -> string -``` -Return the string representation of an integer, in decimal. - -``` -val int_of_string_opt : string -> int option -``` -Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with `0u`), in hexadecimal (if it begins with `0x` or `0X`), in octal (if it begins with `0o` or `0O`), or in binary (if it begins with `0b` or `0B`). - -The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*max_int+1]`. If the input exceeds [`max_int`](./#val-max_int) it is converted to the signed integer `min_int + input - max_int - 1`. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -Return `None` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int`. - -since 4.05 -``` -val int_of_string : string -> int -``` -Same as [`Stdlib.int_of_string_opt`](./#val-int_of_string_opt), but raise `Failure "int_of_string"` instead of returning `None`. - -``` -val string_of_float : float -> string -``` -Return a string representation of a floating-point number. - -This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). - -``` -val float_of_string_opt : string -> float option -``` -Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). - -The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. - -The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. - -In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. - -Return `None` if the given string is not a valid representation of a float. - -since 4.05 -``` -val float_of_string : string -> float -``` -Same as [`Stdlib.float_of_string_opt`](./#val-float_of_string_opt), but raise `Failure "float_of_string"` instead of returning `None`. - - -## Pair operations - -``` -val fst : ('a * 'b) -> 'a -``` -Return the first component of a pair. - -``` -val snd : ('a * 'b) -> 'b -``` -Return the second component of a pair. - - -## List operations - -More list operations are provided in module [`List`](./Stdlib-List.md). - -``` -val (@) : 'a list -> 'a list -> 'a list -``` -`l0 @ l1` appends `l1` to `l0`. Same function as [`List.append`](./Stdlib-List.md#val-append). Right-associative operator, see `Ocaml_operators` for more information. - -since 5.1 this function is tail-recursive. - -## Input/output - -Note: all input/output functions can raise `Sys_error` when the system calls they invoke fail. - -``` -type in_channel -``` -The type of input channel. - -``` -type out_channel -``` -The type of output channel. - -``` -val stdin : in_channel -``` -The standard input for the process. - -``` -val stdout : out_channel -``` -The standard output for the process. - -``` -val stderr : out_channel -``` -The standard error output for the process. - - -### Output functions on standard output - -``` -val print_char : char -> unit -``` -Print a character on standard output. - -``` -val print_string : string -> unit -``` -Print a string on standard output. - -``` -val print_bytes : bytes -> unit -``` -Print a byte sequence on standard output. - -since 4.02 -``` -val print_int : int -> unit -``` -Print an integer, in decimal, on standard output. - -``` -val print_float : float -> unit -``` -Print a floating-point number, in decimal, on standard output. - -The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. - -``` -val print_endline : string -> unit -``` -Print a string, followed by a newline character, on standard output and flush standard output. - -``` -val print_newline : unit -> unit -``` -Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. - - -### Output functions on standard error - -``` -val prerr_char : char -> unit -``` -Print a character on standard error. - -``` -val prerr_string : string -> unit -``` -Print a string on standard error. - -``` -val prerr_bytes : bytes -> unit -``` -Print a byte sequence on standard error. - -since 4.02 -``` -val prerr_int : int -> unit -``` -Print an integer, in decimal, on standard error. - -``` -val prerr_float : float -> unit -``` -Print a floating-point number, in decimal, on standard error. - -The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. - -``` -val prerr_endline : string -> unit -``` -Print a string, followed by a newline character on standard error and flush standard error. - -``` -val prerr_newline : unit -> unit -``` -Print a newline character on standard error, and flush standard error. - - -### Input functions on standard input - -``` -val read_line : unit -> string -``` -Flush standard output, then read characters from standard input until a newline character is encountered. - -Return the string of all characters read, without the newline character at the end. - -raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. -``` -val read_int_opt : unit -> int option -``` -Flush standard output, then read one line from standard input and convert it to an integer. - -Return `None` if the line read is not a valid representation of an integer. - -since 4.05 -``` -val read_int : unit -> int -``` -Same as [`Stdlib.read_int_opt`](./#val-read_int_opt), but raise `Failure "int_of_string"` instead of returning `None`. - -``` -val read_float_opt : unit -> float option -``` -Flush standard output, then read one line from standard input and convert it to a floating-point number. - -Return `None` if the line read is not a valid representation of a floating-point number. - -since 4.05 -``` -val read_float : unit -> float -``` -Same as [`Stdlib.read_float_opt`](./#val-read_float_opt), but raise `Failure "float_of_string"` instead of returning `None`. - - -### General output functions - -``` -type open_flag = -``` -``` -| Open_rdonly -``` -open for reading. - -``` -| Open_wronly -``` -open for writing. - -``` -| Open_append -``` -open for appending: always write at end of file. - -``` -| Open_creat -``` -create the file if it does not exist. - -``` -| Open_trunc -``` -empty the file if it already exists. - -``` -| Open_excl -``` -fail if Open\_creat and the file already exists. - -``` -| Open_binary -``` -open in binary mode (no conversion). - -``` -| Open_text -``` -open in text mode (may perform conversions). - -``` -| Open_nonblock -``` -open in non-blocking mode. - -``` - -``` -Opening modes for [`Stdlib.open_out_gen`](./#val-open_out_gen) and [`Stdlib.open_in_gen`](./#val-open_in_gen). - -``` -val open_out : string -> out_channel -``` -Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. - -``` -val open_out_bin : string -> out_channel -``` -Same as [`Stdlib.open_out`](./#val-open_out), but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_out`](./#val-open_out). - -``` -val open_out_gen : open_flag list -> int -> string -> out_channel -``` -`open_out_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`Stdlib.open_out`](./#val-open_out) and [`Stdlib.open_out_bin`](./#val-open_out_bin) are special cases of this function. - -``` -val flush : out_channel -> unit -``` -Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. - -``` -val flush_all : unit -> unit -``` -Flush all open output channels; ignore errors. - -``` -val output_char : out_channel -> char -> unit -``` -Write the character on the given output channel. - -``` -val output_string : out_channel -> string -> unit -``` -Write the string on the given output channel. - -``` -val output_bytes : out_channel -> bytes -> unit -``` -Write the byte sequence on the given output channel. - -since 4.02 -``` -val output : out_channel -> bytes -> int -> int -> unit -``` -`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. - -raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val output_substring : out_channel -> string -> int -> int -> unit -``` -Same as `output` but take a string as argument instead of a byte sequence. - -since 4.02 -``` -val output_byte : out_channel -> int -> unit -``` -Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. - -``` -val output_binary_int : out_channel -> int -> unit -``` -Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the [`Stdlib.input_binary_int`](./#val-input_binary_int) function. The format is compatible across all machines for a given version of OCaml. - -``` -val output_value : out_channel -> 'a -> unit -``` -Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function [`Stdlib.input_value`](./#val-input_value). See the description of module [`Marshal`](./Stdlib-Marshal.md) for more information. [`Stdlib.output_value`](./#val-output_value) is equivalent to [`Marshal.to_channel`](./Stdlib-Marshal.md#val-to_channel) with an empty list of flags. - -``` -val seek_out : out_channel -> int -> unit -``` -`seek_out chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. - -``` -val pos_out : out_channel -> int -``` -Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_out`, then going back to this position using `seek_out` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - -``` -val out_channel_length : out_channel -> int -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. - -``` -val close_out : out_channel -> unit -``` -Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except `close_out` and `flush`, which do nothing when applied to an already closed channel. Note that `close_out` may raise `Sys_error` if the operating system signals an error when flushing or closing. - -``` -val close_out_noerr : out_channel -> unit -``` -Same as `close_out`, but ignore all errors. - -``` -val set_binary_mode_out : out_channel -> bool -> unit -``` -`set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. `set_binary_mode_out oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. - - -### General input functions - -``` -val open_in : string -> in_channel -``` -Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. - -``` -val open_in_bin : string -> in_channel -``` -Same as [`Stdlib.open_in`](./#val-open_in), but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_in`](./#val-open_in). - -``` -val open_in_gen : open_flag list -> int -> string -> in_channel -``` -`open_in_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`Stdlib.open_in`](./#val-open_in) and [`Stdlib.open_in_bin`](./#val-open_in_bin) are special cases of this function. - -``` -val input_char : in_channel -> char -``` -Read one character from the given input channel. - -raises [`End_of_file`](./#exception-End_of_file) if there are no more characters to read. -``` -val input_line : in_channel -> string -``` -Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. - -raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. -``` -val input : in_channel -> bytes -> int -> int -> int -``` -`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and `len` exclusive means that not all requested `len` characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; `input` must be called again to read the remaining characters, if desired. (See also [`Stdlib.really_input`](./#val-really_input) for reading exactly `len` characters.) Exception `Invalid_argument "input"` is raised if `pos` and `len` do not designate a valid range of `buf`. - -``` -val really_input : in_channel -> bytes -> int -> int -> unit -``` -`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. - -raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. -raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val really_input_string : in_channel -> int -> string -``` -`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. - -raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. -since 4.02 -``` -val input_byte : in_channel -> int -``` -Same as [`Stdlib.input_char`](./#val-input_char), but return the 8-bit integer representing the character. - -raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached. -``` -val input_binary_int : in_channel -> int -``` -Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See [`Stdlib.output_binary_int`](./#val-output_binary_int). - -raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached while reading the integer. -``` -val input_value : in_channel -> 'a -``` -Read the representation of a structured value, as produced by [`Stdlib.output_value`](./#val-output_value), and return the corresponding value. This function is identical to [`Marshal.from_channel`](./Stdlib-Marshal.md#val-from_channel); see the description of module [`Marshal`](./Stdlib-Marshal.md) for more information, in particular concerning the lack of type safety. - -``` -val seek_in : in_channel -> int -> unit -``` -`seek_in chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. - -``` -val pos_in : in_channel -> int -``` -Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_in`, then going back to this position using `seek_in` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - -``` -val in_channel_length : in_channel -> int -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. - -``` -val close_in : in_channel -> unit -``` -Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except `close_in`, which does nothing when applied to an already closed channel. - -``` -val close_in_noerr : in_channel -> unit -``` -Same as `close_in`, but ignore all errors. - -``` -val set_binary_mode_in : in_channel -> bool -> unit -``` -`set_binary_mode_in ic true` sets the channel `ic` to binary mode: no translations take place during input. `set_binary_mode_out ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. - - -### Operations on large files - -``` -module LargeFile : sig ... end -``` -Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. - - -## References - -``` -type 'a ref = { -``` -`mutable contents : 'a;` -``` -} -``` -The type of references (mutable indirection cells) containing a value of type `'a`. - -``` -val ref : 'a -> 'a ref -``` -Return a fresh reference containing the given value. - -``` -val (!) : 'a ref -> 'a -``` -`!r` returns the current contents of reference `r`. Equivalent to `fun r -> r.contents`. Unary operator, see `Ocaml_operators` for more information. - -``` -val (:=) : 'a ref -> 'a -> unit -``` -`r := a` stores the value of `a` in reference `r`. Equivalent to `fun r v -> r.contents <- v`. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val incr : int ref -> unit -``` -Increment the integer contained in the given reference. Equivalent to `fun r -> r := succ !r`. - -``` -val decr : int ref -> unit -``` -Decrement the integer contained in the given reference. Equivalent to `fun r -> r := pred !r`. - - -## Result type - -``` -type ('a, 'b) result = -``` -``` -| Ok of 'a -``` -``` -| Error of 'b -``` -``` - -``` -since 4.03 - -## Operations on format strings - -Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module [`Scanf`](./Stdlib-Scanf.md) and to print data with formatted output functions from modules [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). - -Format strings are made of three kinds of entities: - -- *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print, -- *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument, -- *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output. -There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`. - -For more information about conversion specifications and formatting indications available, read the documentation of modules [`Scanf`](./Stdlib-Scanf.md), [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). - -Format strings have a general and highly polymorphic type `('a, 'b, 'c, 'd, 'e, 'f) format6`. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml. - -The meaning of format string type parameters is as follows: - -- `'a` is the type of the parameters of the format for formatted output functions (`printf`\-style functions); `'a` is the type of the values read by the format for formatted input functions (`scanf`\-style functions). -- `'b` is the type of input source for formatted input functions and the type of output target for formatted output functions. For `printf`\-style functions from module [`Printf`](./Stdlib-Printf.md), `'b` is typically `out_channel`; for `printf`\-style functions from module [`Format`](./Stdlib-Format.md), `'b` is typically [`Format.formatter`](./Stdlib-Format.md#type-formatter); for `scanf`\-style functions from module [`Scanf`](./Stdlib-Scanf.md), `'b` is typically [`Scanf.Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). -Type argument `'b` is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion. - -- `'c` is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf`\-style functions or to the `kscanf`\-style functions. -- `'d` is the type of parameters for the `scanf`\-style functions. -- `'e` is the type of the receiver function for the `scanf`\-style functions. -- `'f` is the final result type of a formatted input/output function invocation: for the `printf`\-style functions, it is typically `unit`; for the `scanf`\-style functions, it is typically the result type of the receiver function. -``` -type ('a, 'b, 'c, 'd, 'e, 'f) format6 = - ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 -``` -``` -type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 -``` -``` -type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 -``` -``` -val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string -``` -Converts a format string into a string. - -``` -val format_of_string : - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -``` -`format_of_string s` returns a format string read from the string literal `s`. Note: `format_of_string` can not convert a string argument that is not a literal. If you need this functionality, use the more general [`Scanf.format_from_string`](./Stdlib-Scanf.md#val-format_from_string) function. - -``` -val (^^) : - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - ('f, 'b, 'c, 'e, 'g, 'h) format6 -> - ('a, 'b, 'c, 'd, 'g, 'h) format6 -``` -`f1 ^^ f2` catenates format strings `f1` and `f2`. The result is a format string that behaves as the concatenation of format strings `f1` and `f2`: in case of formatted output, it accepts arguments from `f1`, then arguments from `f2`; in case of formatted input, it returns results from `f1`, then results from `f2`. Right-associative operator, see `Ocaml_operators` for more information. - - -## Program termination - -``` -val exit : int -> 'a -``` -Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with [`Domain.at_exit`](./Stdlib-Domain.md#val-at_exit) are called followed by those registered with [`Stdlib.at_exit`](./#val-at_exit). - -An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception. - -``` -val at_exit : (unit -> unit) -> unit -``` -Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following: - -- executes [`Stdlib.exit`](./#val-exit) -- terminates, either normally or because of an uncaught exception -- executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. - -## Standard library modules - -``` -module Arg : sig ... end -``` -Parsing of command line arguments. - -``` -module Array : sig ... end -``` -Array operations. - -``` -module ArrayLabels : sig ... end -``` -Array operations. - -``` -module Atomic : sig ... end -``` -Atomic references. - -``` -module Bool : sig ... end -``` -Boolean values. - -``` -module Buffer : sig ... end -``` -Extensible buffers. - -``` -module Bytes : sig ... end -``` -Byte sequence operations. - -``` -module BytesLabels : sig ... end -``` -Byte sequence operations. - -``` -module Char : sig ... end -``` -Character operations. - -``` -module Complex : sig ... end -``` -Complex numbers. - -``` -module Digest : sig ... end -``` -Message digest. - -``` -module Domain : sig ... end -``` -``` -module Dynarray : sig ... end -``` -Dynamic arrays. - -``` -module Effect : sig ... end -``` -``` -module Either : sig ... end -``` -Either type. - -``` -module Filename : sig ... end -``` -Operations on file names. - -``` -module Float : sig ... end -``` -Floating-point arithmetic. - -``` -module Format : sig ... end -``` -Pretty-printing. - -``` -module Fun : sig ... end -``` -Function manipulation. - -``` -module Gc : sig ... end -``` -Memory management control and statistics; finalised values. - -``` -module Hashtbl : sig ... end -``` -Hash tables and hash functions. - -``` -module In_channel : sig ... end -``` -Input channels. - -``` -module Int : sig ... end -``` -Integer values. - -``` -module Int32 : sig ... end -``` -32-bit integers. - -``` -module Int64 : sig ... end -``` -64-bit integers. - -``` -module Lazy : sig ... end -``` -Deferred computations. - -``` -module Lexing : sig ... end -``` -The run-time library for lexers generated by `ocamllex`. - -``` -module List : sig ... end -``` -List operations. - -``` -module ListLabels : sig ... end -``` -List operations. - -``` -module Map : sig ... end -``` -Association tables over ordered types. - -``` -module Marshal : sig ... end -``` -Marshaling of data structures. - -``` -module MoreLabels : sig ... end -``` -Extra labeled libraries. - -``` -module Mutex : sig ... end -``` -Locks for mutual exclusion. - -``` -module Obj : sig ... end -``` -Operations on internal representations of values. - -``` -module Oo : sig ... end -``` -Operations on objects - -``` -module Option : sig ... end -``` -Option values. - -``` -module Out_channel : sig ... end -``` -Output channels. - -``` -module Parsing : sig ... end -``` -The run-time library for parsers generated by `ocamlyacc`. - -``` -module Printexc : sig ... end -``` -Facilities for printing exceptions and inspecting current call stack. - -``` -module Printf : sig ... end -``` -Formatted output functions. - -``` -module Queue : sig ... end -``` -First-in first-out queues. - -``` -module Random : sig ... end -``` -Pseudo-random number generators (PRNG). - -``` -module Result : sig ... end -``` -Result values. - -``` -module Scanf : sig ... end -``` -Formatted input functions. - -``` -module Seq : sig ... end -``` -Sequences. - -``` -module Set : sig ... end -``` -Sets over ordered types. - -``` -module Stack : sig ... end -``` -Last-in first-out stacks. - -``` -module StdLabels : sig ... end -``` -Standard labeled libraries. - -``` -module String : sig ... end -``` -Strings. - -``` -module StringLabels : sig ... end -``` -Strings. - -``` -module Sys : sig ... end -``` -System interface. - -``` -module Type : sig ... end -``` -Type introspection. - -``` -module Uchar : sig ... end -``` -Unicode characters. - -``` -module Unit : sig ... end -``` -Unit values. - -``` -module Weak : sig ... end -``` -Arrays of weak pointers and hash sets of weak pointers. diff --git a/docs/api/re/melange/Belt-Array.md b/docs/api/re/melange/Belt-Array.md deleted file mode 100644 index 31970e565..000000000 --- a/docs/api/re/melange/Belt-Array.md +++ /dev/null @@ -1,654 +0,0 @@ - -# Module `Belt.Array` - -[`Belt.Array`](#) - -**mutable array**: Utilities functions - -[`Belt.Array`](#) Utililites for Array functions - -``` -type 'a t = 'a array -``` -``` -val length : 'a t -> int -``` -`length xs` return the size of the array - -``` -val size : 'a t -> int -``` -**See** [`length`](./#val-length) - -``` -val get : 'a t -> int -> 'a option -``` -`get arr i` - -If `i <= 0 <= length arr`;returns `Some value` where `value` is the item at index `i` If `i` is out of range;returns `None` - -```ocaml - Belt.Array.get [|"a";"b";"c"|] 0 = Some "a";; - Belt.Array.get [|"a";"b";"c"|] 3 = None;; - Belt.Array.get [|"a";"b";"c"|] (-1) = None;; -``` -``` -val getExn : 'a t -> int -> 'a -``` -`getExn arr i` - -**raise** an exception if `i` is out of range;otherwise return the value at index `i` in `arr` - -``` -val getUnsafe : 'a t -> int -> 'a -``` -`getUnsafe arr i` - -**Unsafe** - -no bounds checking;this would cause type error if `i` does not stay within range - -``` -val getUndefined : 'a t -> int -> 'a Js.undefined -``` -`getUndefined arr i` - -It does the samething in the runtime as [`getUnsafe`](./#val-getUnsafe); it is *type safe* since the return type still track whether it is in range or not - -``` -val set : 'a t -> int -> 'a -> bool -``` -`set arr n x` modifies `arr` in place; it replaces the nth element of `arr` with `x` - -returns false means not updated due to out of range -``` -val setExn : 'a t -> int -> 'a -> unit -``` -`setExn arr i x` **raise** an exception if `i` is out of range - -``` -val setUnsafe : 'a t -> int -> 'a -> unit -``` -``` -val shuffleInPlace : 'a t -> unit -``` -`shuffleInPlace arr` randomly re-orders the items in `arr` - -``` -val shuffle : 'a t -> 'a t -``` -`shuffle xs` - -returns a fresh array with items in original array randomly shuffled -``` -val reverseInPlace : 'a t -> unit -``` -`reverseInPlace arr` reverses items in `arr` in place - -```ocaml - let arr = [|10;11;12;13;14|];; - let () = reverseInPlace arr;; - arr = [|14;13;12;11;10|];; -``` -``` -val reverse : 'a t -> 'a t -``` -`reverse arr` - -returns a fresh array with items in arr in reverse order -```ocaml - reverse [|10;11;12;13;14|] = [|14;13;12;11;10|];; -``` -``` -val makeUninitialized : int -> 'a Js.undefined array -``` -`makeUninitialized n` creates an array of length `n` filled with the undefined value. You must specify the type of data that will eventually fill the array. - -```ocaml - let arr: string Js.undefined array = makeUninitialized 5;; - getExn arr 0 = Js.undefined;; -``` -``` -val makeUninitializedUnsafe : int -> 'a t -``` -\`makeUninitializedUnsafe n\` - -**Unsafe** - -```ocaml -let arr = Belt.Array.makeUninitializedUnsafe 5;; -let () = Js.log(Belt.Array.getExn arr 0);; (* undefined *) -Belt.Array.setExn arr 0 "example";; -let () = Js.log(Belt.Array.getExn arr 0 = "example");; -``` -``` -val make : int -> 'a -> 'a t -``` -`make n e` return an array of size `n` filled with value `e` - -returns an empty array when n is negative. -``` -val range : int -> int -> int t -``` -`range start finish` create an inclusive array - -```ocaml - range 0 3 = [|0;1;2;3|];; - range 3 0 = [||] ;; - range 3 3 = [|3|];; -``` -``` -val rangeBy : int -> int -> step:int -> int t -``` -`rangeBy start finish ~step` - -returns empty array when step is 0 or negative it also return empty array when start \> finish -```ocaml - rangeBy 0 10 ~step:3 = [|0;3;6;9|];; - rangeBy 0 12 ~step:3 = [|0;3;6;9;12|];; - rangeBy 33 0 ~step:1 = [||];; - rangeBy 33 0 ~step:(-1) = [||];; - rangeBy 3 12 ~step:(-1) = [||];; - rangeBy 3 3 ~step:0 = [||] ;; - rangeBy 3 3 ~step:(1) = [|3|] ;; -``` -``` -val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val makeBy : int -> (int -> 'a) -> 'a t -``` -`makeBy n f` - -return an empty array when `n` is negative return an array of size `n` populated by `f i` start from `0` to `n - 1` - -```ocaml - makeBy 5 (fun i -> i) = [|0;1;2;3;4|];; - makeBy 5 (fun i -> i * i) = [|0;1;4;9;16|] -``` -``` -val makeByAndShuffleU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val makeByAndShuffle : int -> (int -> 'a) -> 'a t -``` -`makeByAndShuffle n f` - -Equivalent to `shuffle (makeBy n f)` - -``` -val zip : 'a t -> 'b array -> ('a * 'b) array -``` -`zip a b` - -Create an array of pairs from corresponding elements of `a` and `b`. Stop with the shorter array - -```ocaml - zip [|1;2|] [|3;4;5|] = [|(1, 3);(2, 4)|] -``` -``` -val zipByU : 'a t -> 'b array -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c array -``` -``` -val zipBy : 'a t -> 'b array -> ('a -> 'b -> 'c) -> 'c array -``` -`zipBy xs ys f` - -Create an array by applying `f` to corresponding elements of `xs` and `ys` Stops with shorter array - -Equivalent to `map (zip xs ys) (fun (a,b) -> f a b) ` - -```ocaml - zipBy [|1;2;3|] [|4;5|] (fun a b -> 2 * a + b) = [|6;9|];; -``` -``` -val unzip : ('a * 'b) array -> 'a t * 'b array -``` -`unzip a` takes an array of pairs and creates a pair of arrays. The first array contains all the first items of the pairs; the second array contains all the second items. - -```ocaml - unzip [|(1,2) ; (3,4)|] = ([|1;3|], [|2;4|]);; - unzip [|(1,2) ; (3,4) ; (5,6) ; (7,8)|] = ([|1;3;5;7|], [|2;4;6;8|]);; -``` -``` -val concat : 'a t -> 'a t -> 'a t -``` -`concat xs ys` - -returns a fresh array containing the concatenation of the arrays v1 and v2;so even if v1 or v2 is empty;it can not be shared -```ocaml - concat [|1;2;3|] [|4;5|] = [|1;2;3;4;5|];; - concat [| |] [|"a";"b";"c"|] = [|"a";"b";"c"|];; -``` -``` -val concatMany : 'a t t -> 'a t -``` -`concatMany xss` - -returns a fresh array as the concatenation of xss (an array of arrays) -```ocaml - concatMany [| [|1;2;3|]; [|4;5;6|]; [|7;8|] |] = [|1;2;3;4;5;6;7;8|];; -``` -``` -val slice : 'a t -> offset:int -> len:int -> 'a t -``` -`slice xs offset len` creates a new array with the `len` elements of `xs` starting at `offset` for - -`offset` can be negative;and is evaluated as `length xs - offset` `slice xs -1 1` means get the last element as a singleton array - -`slice xs (-len) len` will return a copy of the array - -if the array does not have enough data;`slice` extracts through the end of sequence. - -if `len` is negative;returns the empty array. - -```ocaml - slice [|10;11;12;13;14;15;16|] ~offset: 2 ~len: 3 = [|12;13;14|];; - slice [|10;11;12;13;14;15;16|] ~offset: (-4) ~len: 3 = [|13;14;15|];; - slice [|10;11;12;13;14;15;16|] ~offset:4 ~len:9 = [|14;15;16|];; -``` -``` -val sliceToEnd : 'a t -> int -> 'a t -``` -`sliceToEnd xs offset` creates a new array with the elements of `xs` starting at `offset` - -`offset` can be negative;and is evaluated as `length xs - offset` `sliceToEnd xs -1` means get the last element as a singleton array - -`sliceToEnd xs 0` will return a copy of the array - -```ocaml - sliceToEnd [|10;11;12;13;14;15;16|] 2 = [|12;13;14;15;16|];; - sliceToEnd [|10;11;12;13;14;15;16|] (-4) = [|13;14;15;16|];; -``` -``` -val copy : 'a t -> 'a t -``` -`copy a` - -returns a copy of a;that is;a fresh array containing the same elements as a. -``` -val fill : 'a t -> offset:int -> len:int -> 'a -> unit -``` -`fill arr ~offset ~len x` - -Modifies `arr` in place, storing `x` in elements number `offset` to `offset + len - 1`. - -`offset` can be negative;and is evaluated as `length arr - offset` - -`fill arr ~offset:(-1) ~len:1` means fill the last element, if the array does not have enough data;`fill` will ignore it - -```ocaml - - let arr = makeBy 5 (fun i -> i) ;; - fill arr ~offset:2 ~len:2 9 ;; - arr = [|0;1;9;9;4|];; - fill arr ~offset:7 ~len:2 8;; - arr = [|0;1;9;9;4|];; -``` -``` -val blit : - src:'a t -> - srcOffset:int -> - dst:'a t -> - dstOffset:int -> - len:int -> - unit -``` -`blit ~src:v1 ~srcOffset:o1 ~dst:v2 ~dstOffset:o2 ~len` - -copies `len` elements from array `v1`;starting at element number `o1`;to array `v2`, starting at element number `o2`. - -It works correctly even if `v1` and `v2` are the same array;and the source and destination chunks overlap. - -`offset` can be negative;`-1` means `len - 1`;if `len + offset` is still negative;it will be set as 0 - -For each of the examples;presume that `v1 = [|10;11;12;13;14;15;16;17|]` and `v2 = [|20;21;22;23;24;25;26;27|]`. The result shown is the content of the destination array. - -```ocaml - Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v2 ~dstOffset: 2 ~len: 3 |. - [|20;21;14;15;16;25;26;27|] - Belt.Array.blit ~src: v1 ~srcOffset: 4 ~dst: v1 ~dstOffset: 2 ~len: 3 |. - [|10;11;14;15;16;15;16;17|] -``` -``` -val blitUnsafe : - src:'a t -> - srcOffset:int -> - dst:'a t -> - dstOffset:int -> - len:int -> - unit -``` -**Unsafe** blit without bounds checking - -``` -val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> unit) -> unit -``` -`forEach xs f` - -Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`;so no new array is created. Use `forEach` when you are primarily concerned with repetitively creating side effects. - -```ocaml - forEach [|"a";"b";"c"|] (fun x -> Js.log("Item: " ^ x));; - (* prints: - Item: a - Item: b - Item: c - *) - - let total = ref 0;; - forEach [|1;2;3;4|] (fun x -> total := !total + x);; - !total = 1 + 2 + 3 + 4;; - -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b array -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b array -``` -`map xs f ` - -returns a new array by calling f for each element of xs from the beginning to end -```ocaml - map [|1;2|] (fun x-> x + 10) = [|11;12|] -``` -``` -val flatMapU : 'a t -> ('a -> 'b t) Js.Fn.arity1 -> 'b t -``` -``` -val flatMap : 'a t -> ('a -> 'b t) -> 'b t -``` -`flatMap xs f` \*\*return\*\* a new array by calling \`f\` for each element of \`xs\` from the beginning to end, and then concatenating the results \``` flatMap `|1;2|` (fun x-\> `|x + 10;x + 20|`) \= `|11;21;12;22|` \``` - -``` -val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option -``` -``` -val getBy : 'a t -> ('a -> bool) -> 'a option -``` -`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. - -```ocaml - getBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 4 - getBy [|15;13;11|] (fun x -> x mod 2 = 0) = None -``` -``` -val getIndexByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> int option -``` -``` -val getIndexBy : 'a t -> ('a -> bool) -> int option -``` -`getIndexBy xs p` returns `Some index` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. - -```ocaml - getIndexBy [|1;4;3;2|] (fun x -> x mod 2 = 0) = Some 1 - getIndexBy [|15;13;11|] (fun x -> x mod 2 = 0) = None -``` -``` -val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t -``` -``` -val keep : 'a t -> ('a -> bool) -> 'a t -``` -`keep xs p ` - -returns a new array that keeps all elements satisfying p -```ocaml - keep [|1;2;3|] (fun x -> x mod 2 = 0) = [|2|] -``` -``` -val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t -``` -``` -val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t -``` -`keepWithIndex xs p ` - -returns a new array that keeps all elements satisfying p. The predicate p takes two arguments: the element from xs and the index starting from 0. -```ocaml - keepWithIndex [|1;2;3|] (fun _x i -> i = 1) = [|2|] -``` -``` -val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b array -``` -``` -val keepMap : 'a t -> ('a -> 'b option) -> 'b array -``` -`keepMap xs p` - -returns a new array that keeps all elements that return a non-None when applied to p -```ocaml - keepMap [|1;2;3|] (fun x -> if x mod 2 = 0 then Some x else None) - = [| 2 |] -``` -``` -val forEachWithIndexU : 'a t -> (int -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEachWithIndex : 'a t -> (int -> 'a -> unit) -> unit -``` -`forEachWithIndex xs f` - -The same as [`forEach`](./#val-forEach); except that `f` is supplied with two arguments: the index starting from 0 and the element from `xs` - -```ocaml - - forEachWithIndex [|"a";"b";"c"|] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; - (* prints: - Item 0 is a - Item 1 is b - Item 2 is c - *) - - let total = ref 0 ;; - forEachWithIndex [|10;11;12;13|] (fun i x -> total := !total + x + i);; - !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; -``` -``` -val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t -``` -`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. - -```ocaml - mapWithIndex [|1;2;3|] (fun i x -> i + x) = - [|0 + 1; 1 + 2; 2 + 3|] -``` -``` -val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t -``` -``` -val partition : 'a t -> ('a -> bool) -> 'a t * 'a t -``` -`partition f a` split array into tuple of two arrays based on predicate f; first of tuple where predicate cause true, second where predicate cause false - -```ocaml - partition [|1;2;3;4;5|] (fun x -> x mod 2 = 0 ) = ([|2;4|], [|1;2;3|]);; - partition [|1;2;3;4;5|] (fun x -> x mod 2 <> 0 ) = ([|1;2;3|], [|2;4|]);; -``` -``` -val reduceU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a -``` -`reduce xs init f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”;which starts with a value of `init`. `reduce` returns the final value of the accumulator. - -```ocaml - reduce [|2;3;4|] 1 (+) = 10;; - reduce [|"a";"b";"c";"d"|] "" (^) = "abcd";; -``` -``` -val reduceReverseU : 'b array -> 'a -> ('a -> 'b -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduceReverse : 'b array -> 'a -> ('a -> 'b -> 'a) -> 'a -``` -`reduceReverse xs init f` - -Works like [`reduce`](./#val-reduce);except that function `f` is applied to each item of `xs` from the last back to the first. - -```ocaml - reduceReverse [|"a";"b";"c";"d"|] "" (^) = "dcba";; -``` -``` -val reduceReverse2U : - 'a t -> - 'b array -> - 'c -> - ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> - 'c -``` -``` -val reduceReverse2 : 'a t -> 'b array -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c -``` -`reduceReverse2 xs ys init f` Reduces two arrays `xs` and `ys`;taking items starting at `min (length xs) (length ys)` down to and including zero. - -```ocaml - reduceReverse2 [|1;2;3|] [|1;2|] 0 (fun acc x y -> acc + x + y) = 6 -``` -``` -val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b -``` -`reduceWithIndex xs f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the array and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. - -```ocaml - reduceWithIndex [|1;2;3;4|] 0 (fun acc x i -> acc + x + i) = 16; -``` -``` -val joinWithU : 'a t -> string -> ('a -> string) Js.Fn.arity1 -> string -``` -``` -val joinWith : 'a t -> string -> ('a -> string) -> string -``` -`joinWith xs sep toString` - -Concatenates all the elements of `xs` converted to string with `toString`, each separated by `sep`, the string given as the second argument, into a single string. If the array has only one element, then that element will be returned without using the separator. If the array is empty, the empty string will be returned. - -```ocaml - joinWith [|0; 1|] ", " string_of_int = "0, 1" - joinWith [||] " " string_of_int = "" - joinWith [|1|] " " string_of_int = "1" -``` -``` -val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : 'a t -> ('a -> bool) -> bool -``` -`some xs p` - -returns true if at least one of the elements in xs satifies p;where p is a predicate: a function taking an element and returning a bool. -```ocaml - some [|2; 3; 4|] (fun x -> x mod 2 = 1) = true;; - some [|-1; -3; -5|] (fun x -> x > 0) = false;; -``` -``` -val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : 'a t -> ('a -> bool) -> bool -``` -`every xs p` - -returns true if all elements satisfy p;where p is a predicate: a function taking an element and returning a bool. -```ocaml - every [|1; 3; 5|] (fun x -> x mod 2 = 1) = true;; - every [|1; -3; 5|] (fun x -> x > 0) = false;; -``` -``` -val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`every2 xs ys p` returns true if `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - every2 [|1;2;3|] [|0;1|] (>) = true;; - every2 [||] [|1|] (fun x y -> x > y) = true;; - every2 [|2;3|] [|1|] (fun x y -> x > y) = true;; - every2 [|0;1|] [|5;0|] (fun x y -> x > y) = false; -``` -``` -val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - some2 [|0;2|] [|1;0;3|] (>) = true ;; - (some2 [||] [|1|] (fun x y -> x > y)) = false;; - (some2 [|2;3|] [|1;4|] (fun x y -> x > y)) = true;; -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -`cmp xs ys f` - -- Compared by length if `length xs <> length ys`;returning \-1 if`length xs < length ys` or 1 if `length xs > length ys` -- Otherwise compare one by one `f x y`. `f` returns -- a negative number if `x` is “less than” `y` -- zero if `x` is “equal to” `y` -- a positive number if `x` is “greater than” `y` -- The comparison returns the first non-zero result of `f`;or zero if `f` returns zero for all `x` and `y`. -```ocaml - cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; - cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; - cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; -``` -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq xs ys` - -- return false if length is not the same -- otherwise compare items one by one using `f xi yi`;and return true if all results are true;false otherwise -```ocaml - eq [|1; 2; 3|] [|-1; -2; -3|] (fun a b -> abs a = abs b) = true -``` -``` -val truncateToLengthUnsafe : 'a t -> int -> unit -``` -**Unsafe** `truncateToLengthUnsafe xs n` sets length of array `xs` to `n`. - -If `n` is greater than the length of `xs`;the extra elements are set to `Js.Null_undefined.null` - -If `n` is less than zero;raises a `RangeError`. - -```ocaml - let arr = [|"ant";"bee";"cat";"dog";"elk"|];; - let () = truncateToLengthUnsafe arr 3;; - arr = [|"ant";"bee";"cat"|];; -``` -``` -val initU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val init : int -> (int -> 'a) -> 'a t -``` -``` -val push : 'a t -> 'a -> unit -``` -`arr->push(item)` push element \`item\` into the array diff --git a/docs/api/re/melange/Belt-Float.md b/docs/api/re/melange/Belt-Float.md deleted file mode 100644 index a05b382d7..000000000 --- a/docs/api/re/melange/Belt-Float.md +++ /dev/null @@ -1,29 +0,0 @@ - -# Module `Belt.Float` - -[`Belt.Float`](#) Utililites for Float - -``` -val toInt : float -> int -``` -``` -val fromInt : int -> float -``` -``` -val fromString : string -> float option -``` -``` -val toString : float -> string -``` -``` -val (+) : float -> float -> float -``` -``` -val (-) : float -> float -> float -``` -``` -val (*) : float -> float -> float -``` -``` -val (/) : float -> float -> float -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashMap-Int.md b/docs/api/re/melange/Belt-HashMap-Int.md deleted file mode 100644 index 46c1f54f7..000000000 --- a/docs/api/re/melange/Belt-HashMap-Int.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `HashMap.Int` - -Specalized when key type is `int`, more efficient than the generic type - -``` -type key = int -``` -``` -type 'b t -``` -``` -val make : hintSize:int -> 'b t -``` -``` -val clear : 'b t -> unit -``` -``` -val isEmpty : _ t -> bool -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` - -``` -val copy : 'a t -> 'a t -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val has : 'b t -> key -> bool -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'b t -> (key -> 'b -> unit) -> unit -``` -``` -val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c -``` -``` -val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c -``` -``` -val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit -``` -``` -val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit -``` -``` -val size : _ t -> int -``` -``` -val toArray : 'a t -> (key * 'a) array -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val mergeMany : 'a t -> (key * 'a) array -> unit -``` -``` -val getBucketHistogram : _ t -> int array -``` -``` -val logStats : _ t -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashMap-String.md b/docs/api/re/melange/Belt-HashMap-String.md deleted file mode 100644 index dc5e0eab3..000000000 --- a/docs/api/re/melange/Belt-HashMap-String.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `HashMap.String` - -Specalized when key type is `string`, more efficient than the generic type - -``` -type key = string -``` -``` -type 'b t -``` -``` -val make : hintSize:int -> 'b t -``` -``` -val clear : 'b t -> unit -``` -``` -val isEmpty : _ t -> bool -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`setDone tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` - -``` -val copy : 'a t -> 'a t -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val has : 'b t -> key -> bool -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val forEachU : 'b t -> (key -> 'b -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'b t -> (key -> 'b -> unit) -> unit -``` -``` -val reduceU : 'b t -> 'c -> ('c -> key -> 'b -> 'c) Js.Fn.arity3 -> 'c -``` -``` -val reduce : 'b t -> 'c -> ('c -> key -> 'b -> 'c) -> 'c -``` -``` -val keepMapInPlaceU : 'a t -> (key -> 'a -> 'a option) Js.Fn.arity2 -> unit -``` -``` -val keepMapInPlace : 'a t -> (key -> 'a -> 'a option) -> unit -``` -``` -val size : _ t -> int -``` -``` -val toArray : 'a t -> (key * 'a) array -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val mergeMany : 'a t -> (key * 'a) array -> unit -``` -``` -val getBucketHistogram : _ t -> int array -``` -``` -val logStats : _ t -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashMap.md b/docs/api/re/melange/Belt-HashMap.md deleted file mode 100644 index 0c0c8533e..000000000 --- a/docs/api/re/melange/Belt-HashMap.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Belt.HashMap` - -[`Belt.HashMap`](#) - -The top level provides generic **mutable** hash map operations. - -It also has two specialized inner modules [`Belt.HashMap.Int`](./Belt-HashMap-Int.md) and [`Belt.HashMap.String`](./Belt-HashMap-String.md) - -A **mutable** Hash map which allows customized hash behavior. - -All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashMaps of ints* initialized with different *hash* functions will have different type. - -For example: - -```ocaml - type t = int - module I0 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s0 : (_, string,_) t = make ~hintSize:40 ~id:(module I0) - module I1 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s1 : (_, string,_) t = make ~hintSize:40 ~id:(module I1) -``` -The invariant must be held: for two elements who are *equal*, their hashed value should be the same - -Here the compiler would infer `s0` and `s1` having different type so that it would not mix. - -```ocaml - val s0 : (int, I0.identity) t - val s1 : (int, I1.identity) t -``` -We can add elements to the collection: - -```ocaml - - let () = - add s1 0 "3"; - add s1 1 "3" -``` -Since this is an mutable data strucure, `s1` will contain two pairs. - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -type ('key, 'value, 'id) t -``` -The type of hash tables from type `'key` to type `'value`. - -``` -type ('a, 'id) id = - (module Belt__.Belt_Id.Hashable - with type identity = 'id - and type t = 'a) -``` -``` -val make : hintSize:int -> id:('key, 'id) id -> ('key, 'value, 'id) t -``` -``` -val clear : ('key, 'value, 'id) t -> unit -``` -Empty a hash table. - -``` -val isEmpty : (_, _, _) t -> bool -``` -``` -val set : ('key, 'value, 'id) t -> 'key -> 'value -> unit -``` -`set tbl k v` if `k` does not exist, add the binding `k,v`, otherwise, update the old value with the new `v` - -``` -val copy : ('key, 'value, 'id) t -> ('key, 'value, 'id) t -``` -``` -val get : ('key, 'value, 'id) t -> 'key -> 'value option -``` -``` -val has : ('key, 'value, 'id) t -> 'key -> bool -``` -`has tbl x` checks if `x` is bound in `tbl`. - -``` -val remove : ('key, 'value, 'id) t -> 'key -> unit -``` -``` -val forEachU : - ('key, 'value, 'id) t -> - ('key -> 'value -> unit) Js.Fn.arity2 -> - unit -``` -``` -val forEach : ('key, 'value, 'id) t -> ('key -> 'value -> unit) -> unit -``` -`forEach tbl f` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. - -``` -val reduceU : - ('key, 'value, 'id) t -> - 'c -> - ('c -> 'key -> 'value -> 'c) Js.Fn.arity3 -> - 'c -``` -``` -val reduce : ('key, 'value, 'id) t -> 'c -> ('c -> 'key -> 'value -> 'c) -> 'c -``` -`reduce tbl init f` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -``` -val keepMapInPlaceU : - ('key, 'value, 'id) t -> - ('key -> 'value -> 'value option) Js.Fn.arity2 -> - unit -``` -``` -val keepMapInPlace : - ('key, 'value, 'id) t -> - ('key -> 'value -> 'value option) -> - unit -``` -``` -val size : (_, _, _) t -> int -``` -`size tbl` returns the number of bindings in `tbl`. It takes constant time. - -``` -val toArray : ('key, 'value, 'id) t -> ('key * 'value) array -``` -``` -val keysToArray : ('key, _, _) t -> 'key array -``` -``` -val valuesToArray : (_, 'value, _) t -> 'value array -``` -``` -val fromArray : - ('key * 'value) array -> - id:('key, 'id) id -> - ('key, 'value, 'id) t -``` -``` -val mergeMany : ('key, 'value, 'id) t -> ('key * 'value) array -> unit -``` -``` -val getBucketHistogram : (_, _, _) t -> int array -``` -``` -val logStats : (_, _, _) t -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashSet-Int.md b/docs/api/re/melange/Belt-HashSet-Int.md deleted file mode 100644 index e674b95e9..000000000 --- a/docs/api/re/melange/Belt-HashSet-Int.md +++ /dev/null @@ -1,68 +0,0 @@ - -# Module `HashSet.Int` - -Specalized when key type is `int`, more efficient than the generic type - -This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.HashSet`](./Belt-HashSet.md) - -``` -type key = int -``` -``` -type t -``` -``` -val make : hintSize:int -> t -``` -``` -val clear : t -> unit -``` -``` -val isEmpty : t -> bool -``` -``` -val add : t -> key -> unit -``` -``` -val copy : t -> t -``` -``` -val has : t -> key -> bool -``` -``` -val remove : t -> key -> unit -``` -``` -val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (key -> unit) -> unit -``` -``` -val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c -``` -``` -val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c -``` -``` -val size : t -> int -``` -``` -val logStats : t -> unit -``` -``` -val toArray : t -> key array -``` -``` -val fromArray : key array -> t -``` -``` -val mergeMany : t -> key array -> unit -``` -``` -val getBucketHistogram : t -> int array -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashSet-String.md b/docs/api/re/melange/Belt-HashSet-String.md deleted file mode 100644 index 299cc480d..000000000 --- a/docs/api/re/melange/Belt-HashSet-String.md +++ /dev/null @@ -1,68 +0,0 @@ - -# Module `HashSet.String` - -Specalized when key type is `string`, more efficient than the generic type - -This module is [`Belt.HashSet`](./Belt-HashSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.HashSet`](./Belt-HashSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.HashSet`](./Belt-HashSet.md) - -``` -type key = string -``` -``` -type t -``` -``` -val make : hintSize:int -> t -``` -``` -val clear : t -> unit -``` -``` -val isEmpty : t -> bool -``` -``` -val add : t -> key -> unit -``` -``` -val copy : t -> t -``` -``` -val has : t -> key -> bool -``` -``` -val remove : t -> key -> unit -``` -``` -val forEachU : t -> (key -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (key -> unit) -> unit -``` -``` -val reduceU : t -> 'c -> ('c -> key -> 'c) Js.Fn.arity2 -> 'c -``` -``` -val reduce : t -> 'c -> ('c -> key -> 'c) -> 'c -``` -``` -val size : t -> int -``` -``` -val logStats : t -> unit -``` -``` -val toArray : t -> key array -``` -``` -val fromArray : key array -> t -``` -``` -val mergeMany : t -> key array -> unit -``` -``` -val getBucketHistogram : t -> int array -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-HashSet.md b/docs/api/re/melange/Belt-HashSet.md deleted file mode 100644 index 1f8647d50..000000000 --- a/docs/api/re/melange/Belt-HashSet.md +++ /dev/null @@ -1,124 +0,0 @@ - -# Module `Belt.HashSet` - -[`Belt.HashSet`](#) - -The top level provides generic **mutable** hash set operations. - -It also has two specialized inner modules [`Belt.HashSet.Int`](./Belt-HashSet-Int.md) and [`Belt.HashSet.String`](./Belt-HashSet-String.md) - -A **mutable** Hash set which allows customized hash behavior. - -All data are parameterized by not its only type but also a unique identity in the time of initialization, so that two *HashSets of ints* initialized with different *hash* functions will have different type. - -For example: - -```ocaml - type t = int - module I0 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff_ff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s0 = make ~id:(module I0) ~hintSize:40 - module I1 = - (val Belt.Id.hashableU - ~hash:(fun[\@u] (a : t) -> a & 0xff) - ~eq:(fun[\@u] a b -> a = b) - ) - let s1 = make ~id:(module I1) ~hintSize:40 -``` -The invariant must be held: for two elements who are *equal*, their hashed value should be the same - -Here the compiler would infer `s0` and `s1` having different type so that it would not mix. - -```ocaml - val s0 : (int, I0.identity) t - val s1 : (int, I1.identity) t -``` -We can add elements to the collection: - -```ocaml - - let () = - add s1 0; - add s1 1 -``` -Since this is an mutable data strucure, `s1` will contain two pairs. - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -type ('a, 'id) t -``` -The type of hash tables from type `'a` to type `'b`. - -``` -type ('a, 'id) id = - (module Belt__.Belt_Id.Hashable - with type identity = 'id - and type t = 'a) -``` -``` -val make : hintSize:int -> id:('a, 'id) id -> ('a, 'id) t -``` -``` -val clear : ('a, 'id) t -> unit -``` -``` -val isEmpty : (_, _) t -> bool -``` -``` -val add : ('a, 'id) t -> 'a -> unit -``` -``` -val copy : ('a, 'id) t -> ('a, 'id) t -``` -``` -val has : ('a, 'id) t -> 'a -> bool -``` -``` -val remove : ('a, 'id) t -> 'a -> unit -``` -``` -val forEachU : ('a, 'id) t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('a, 'id) t -> ('a -> unit) -> unit -``` -Order unspecified. - -``` -val reduceU : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) Js.Fn.arity2 -> 'c -``` -``` -val reduce : ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) -> 'c -``` -Order unspecified. - -``` -val size : ('a, 'id) t -> int -``` -``` -val logStats : (_, _) t -> unit -``` -``` -val toArray : ('a, 'id) t -> 'a array -``` -``` -val fromArray : 'a array -> id:('a, 'id) id -> ('a, 'id) t -``` -``` -val mergeMany : ('a, 'id) t -> 'a array -> unit -``` -``` -val getBucketHistogram : (_, _) t -> int array -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md deleted file mode 100644 index 7cdbeba8e..000000000 --- a/docs/api/re/melange/Belt-Id-MakeComparable-argument-1-M.md +++ /dev/null @@ -1,9 +0,0 @@ - -# Parameter `MakeComparable.M` - -``` -type t -``` -``` -val cmp : t -> t -> int -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparable.md b/docs/api/re/melange/Belt-Id-MakeComparable.md deleted file mode 100644 index a4e124a8e..000000000 --- a/docs/api/re/melange/Belt-Id-MakeComparable.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Module `Id.MakeComparable` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val cmp : (t, identity) cmp -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md deleted file mode 100644 index 94b48d88a..000000000 --- a/docs/api/re/melange/Belt-Id-MakeComparableU-argument-1-M.md +++ /dev/null @@ -1,9 +0,0 @@ - -# Parameter `MakeComparableU.M` - -``` -type t -``` -``` -val cmp : (t -> t -> int) Js.Fn.arity2 -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeComparableU.md b/docs/api/re/melange/Belt-Id-MakeComparableU.md deleted file mode 100644 index 6ade5dd1d..000000000 --- a/docs/api/re/melange/Belt-Id-MakeComparableU.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Module `Id.MakeComparableU` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val cmp : (t, identity) cmp -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md deleted file mode 100644 index 2ad08437b..000000000 --- a/docs/api/re/melange/Belt-Id-MakeHashable-argument-1-M.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `MakeHashable.M` - -``` -type t -``` -``` -val hash : t -> int -``` -``` -val eq : t -> t -> bool -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashable.md b/docs/api/re/melange/Belt-Id-MakeHashable.md deleted file mode 100644 index 15f31e6d6..000000000 --- a/docs/api/re/melange/Belt-Id-MakeHashable.md +++ /dev/null @@ -1,24 +0,0 @@ - -# Module `Id.MakeHashable` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val hash : (t, identity) hash -``` -``` -val eq : (t, identity) eq -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md b/docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md deleted file mode 100644 index eb5a430a2..000000000 --- a/docs/api/re/melange/Belt-Id-MakeHashableU-argument-1-M.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `MakeHashableU.M` - -``` -type t -``` -``` -val hash : (t -> int) Js.Fn.arity1 -``` -``` -val eq : (t -> t -> bool) Js.Fn.arity2 -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-MakeHashableU.md b/docs/api/re/melange/Belt-Id-MakeHashableU.md deleted file mode 100644 index a8834245f..000000000 --- a/docs/api/re/melange/Belt-Id-MakeHashableU.md +++ /dev/null @@ -1,24 +0,0 @@ - -# Module `Id.MakeHashableU` - - -## Parameters - -``` -module M : sig ... end -``` - -## Signature - -``` -type identity -``` -``` -type t = M.t -``` -``` -val hash : (t, identity) hash -``` -``` -val eq : (t, identity) eq -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-module-type-Comparable.md b/docs/api/re/melange/Belt-Id-module-type-Comparable.md deleted file mode 100644 index 8f8f4244d..000000000 --- a/docs/api/re/melange/Belt-Id-module-type-Comparable.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Module type `Id.Comparable` - -``` -type identity -``` -``` -type t -``` -``` -val cmp : (t, identity) cmp -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id-module-type-Hashable.md b/docs/api/re/melange/Belt-Id-module-type-Hashable.md deleted file mode 100644 index 9758efeeb..000000000 --- a/docs/api/re/melange/Belt-Id-module-type-Hashable.md +++ /dev/null @@ -1,15 +0,0 @@ - -# Module type `Id.Hashable` - -``` -type identity -``` -``` -type t -``` -``` -val hash : (t, identity) hash -``` -``` -val eq : (t, identity) eq -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Id.md b/docs/api/re/melange/Belt-Id.md deleted file mode 100644 index d9072b719..000000000 --- a/docs/api/re/melange/Belt-Id.md +++ /dev/null @@ -1,113 +0,0 @@ - -# Module `Belt.Id` - -[`Belt.Id`](#) - -Provide utilities to create identified comparators or hashes for data structures used below. - -It create a unique identifier per module of functions so that different data structures with slightly different comparison functions won't mix - -[`Belt.Id`](#) - -Provide utiliites to create identified comparators or hashes for data structures used below. - -It create a unique identifer per module of functions so that different data structures with slightly different comparison functions won't mix. - -``` -type ('a, 'id) hash -``` -`('a, 'id) hash` - -Its runtime represenation is a `hash` function, but signed with a type parameter, so that different hash functions type mismatch - -``` -type ('a, 'id) eq -``` -`('a, 'id) eq` - -Its runtime represenation is an `eq` function, but signed with a type parameter, so that different hash functions type mismatch - -``` -type ('a, 'id) cmp -``` -`('a,'id) cmp` - -Its runtime representation is a `cmp` function, but signed with a type parameter, so that different hash functions type mismatch - -``` -module type Comparable = sig ... end -``` -``` -type ('key, 'id) comparable = - (module Comparable - with type identity = 'id - and type t = 'key) -``` -`('key, 'id) cmparable` is a module of functions, here it only includes `cmp`. - -Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). - -It can be created using function [`comparableU`](./#val-comparableU) or [`comparable`](./#val-comparable). - -The idea of a unique identity when created is that it makes sure two sets would type mismatch if they use different comparison function - -``` -module MakeComparableU (M : sig ... end) : Comparable with type t = M.t -``` -``` -module MakeComparable (M : sig ... end) : Comparable with type t = M.t -``` -``` -val comparableU : - cmp:('a -> 'a -> int) Js.Fn.arity2 -> - (module Comparable - with type t = 'a) -``` -``` -val comparable : cmp:('a -> 'a -> int) -> (module Comparable with type t = 'a) -``` -```ocaml - module C = ( - val Belt.Id.comparable ~cmp:(compare : int -> int -> int) - ) - let m = Belt.Set.make(module C) -``` -Note that the name of C can not be ignored - -``` -module type Hashable = sig ... end -``` -``` -type ('key, 'id) hashable = - (module Hashable - with type identity = 'id - and type t = 'key) -``` -`('key, 'id) hashable` is a module of functions, here it only includes `hash`, `eq`. - -Unlike normal functions, when created, it comes with a unique identity (guaranteed by the type system). - -It can be created using function [`hashableU`](./#val-hashableU) or [`hashable`](./#val-hashable). - -The idea of a unique identity when created is that it makes sure two hash sets would type mismatch if they use different comparison function - -``` -module MakeHashableU (M : sig ... end) : Hashable with type t = M.t -``` -``` -module MakeHashable (M : sig ... end) : Hashable with type t = M.t -``` -``` -val hashableU : - hash:('a -> int) Js.Fn.arity1 -> - eq:('a -> 'a -> bool) Js.Fn.arity2 -> - (module Hashable - with type t = 'a) -``` -``` -val hashable : - hash:('a -> int) -> - eq:('a -> 'a -> bool) -> - (module Hashable - with type t = 'a) -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Int.md b/docs/api/re/melange/Belt-Int.md deleted file mode 100644 index e16080186..000000000 --- a/docs/api/re/melange/Belt-Int.md +++ /dev/null @@ -1,29 +0,0 @@ - -# Module `Belt.Int` - -[`Belt.Int`](#) Utililites for Int - -``` -val toFloat : int -> float -``` -``` -val fromFloat : float -> int -``` -``` -val fromString : string -> int option -``` -``` -val toString : int -> string -``` -``` -val (+) : int -> int -> int -``` -``` -val (-) : int -> int -> int -``` -``` -val (*) : int -> int -> int -``` -``` -val (/) : int -> int -> int -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-List.md b/docs/api/re/melange/Belt-List.md deleted file mode 100644 index eb9dee2fd..000000000 --- a/docs/api/re/melange/Belt-List.md +++ /dev/null @@ -1,680 +0,0 @@ - -# Module `Belt.List` - -[`Belt.List`](#) - -Utilities for List data type - -[`Belt.List`](#) - -Utilities for List data type. - -This module is compatible with original ocaml stdlib. In general, all functions comes with the original stdlib also applies to this collection, however, this module provides faster and stack safer utilities - -``` -type 'a t = 'a list -``` -`'a t` is compatible with built-in `list` type - -``` -val length : 'a t -> int -``` -`length xs` - -returns the length of the list xs -``` -val size : 'a t -> int -``` -**See** [`length`](./#val-length) - -``` -val head : 'a t -> 'a option -``` -`head xs` returns `None` if `xs` is the empty list, otherwise it returns `Some value` where `value` is the first element in the list. - -```ocaml - head [] = None ;; - head [1;2;3] = Some 1 ;; -``` -``` -val headExn : 'a t -> 'a -``` -`headExn xs` - -**See** [`head`](./#val-head) - -**raise** an exception if `xs` is empty - -``` -val tail : 'a t -> 'a t option -``` -`tail xs` returns `None` if `xs` is empty; otherwise it returns `Some xs2` where `xs2` is everything except the first element of `xs`; - -```ocaml - tail [] = None;; - tail [1;2;3;4] = Some [2;3;4];; -``` -``` -val tailExn : 'a t -> 'a t -``` -`tailExn xs` - -**See** [`tail`](./#val-tail) - -**raise** an exception if `xs` is empty - -``` -val add : 'a t -> 'a -> 'a t -``` -`add xs y` adds `y` to the beginning of list `xs` - -```ocaml - add [1] 3 = [3;1];; -``` -``` -val get : 'a t -> int -> 'a option -``` -`get xs n` - -return the nth element in `xs`, or `None` if `n` is larger than the length - -```ocaml - get [0;3;32] 2 = Some 32 ;; - get [0;3;32] 3 = None;; -``` -``` -val getExn : 'a t -> int -> 'a -``` -`getExn xs n` - -**See** [`get`](./#val-get) - -**raise** an exception if `n` is larger than the length - -``` -val make : int -> 'a -> 'a t -``` -`make n v` - -- return a list of length `n` with each element filled with value `v` -- return the empty list if `n` is negative -```ocaml - make 3 1 = [1;1;1] -``` -``` -val makeByU : int -> (int -> 'a) Js.Fn.arity1 -> 'a t -``` -``` -val makeBy : int -> (int -> 'a) -> 'a t -``` -`makeBy n f` - -- return a list of length `n` with element `i` initialized with `f i` -- return the empty list if `n` is negative -```ocaml - makeBy 5 (fun i -> i) = [0;1;2;3;4];; - makeBy 5 (fun i -> i * i) = [0;1;4;9;16];; -``` -``` -val shuffle : 'a t -> 'a t -``` -`shuffle xs` - -returns a new list in random order -``` -val drop : 'a t -> int -> 'a t option -``` -`drop xs n` - -return the list obtained by dropping the first `n` elements, or `None` if `xs` has fewer than `n` elements - -```ocaml - drop [1;2;3] 2 = Some [3];; - drop [1;2;3] 3 = Some [];; - drop [1;2;3] 4 = None;; -``` -``` -val take : 'a t -> int -> 'a t option -``` -`take xs n` - -return a list with the first `n` elements from `xs`, or `None` if `xs` has fewer than `n` elements - -```ocaml - take [1;2;3] 1 = Some [1];; - take [1;2;3] 2 = Some [1;2];; - take [1;2;3] 4 = None;; -``` -``` -val splitAt : 'a t -> int -> ('a list * 'a list) option -``` -`splitAt xs n` split the list `xs` at position `n` return None when the length of `xs` is less than `n` - -```ocaml - splitAt [0;1;2;3;4] 2 = Some ([0;1], [2;3;4]) -``` -``` -val concat : 'a t -> 'a t -> 'a t -``` -`concat xs ys` - -returns the list obtained by adding ys after xs -```ocaml - concat [1;2;3] [4;5] = [1;2;3;4;5] -``` -``` -val concatMany : 'a t array -> 'a t -``` -`concatMany a` return the list obtained by concatenating in order all the lists in array `a` - -```ocaml - concatMany [| [1;2;3] ; []; [3]; [4] |] = [1;2;3;3;4] -``` -``` -val reverseConcat : 'a t -> 'a t -> 'a t -``` -`reverseConcat xs ys` is equivalent to `concat (reverse xs) ys` - -```ocaml - reverseConcat [1;2] [3;4] = [2;1;3;4] -``` -``` -val flatten : 'a t t -> 'a t -``` -`flatten ls` return the list obtained by concatenating in order all the lists in list `ls` - -```ocaml - flatten [ [1;2;3] ; []; [3]; [4] ] = [1;2;3;3;4] -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -`map xs f` - -return the list obtained by applying `f` to each element of `xs` - -```ocaml - map [1;2] (fun x-> x + 1) = [3;4] -``` -``` -val zip : 'a t -> 'b t -> ('a * 'b) t -``` -`zip xs ys` - -returns a list of pairs from the two lists with the length of the shorter list -```ocaml - zip [1;2] [3;4;5] = [(1,3); (2,4)] -``` -``` -val zipByU : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t -``` -``` -val zipBy : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t -``` -`zipBy xs ys f` - -**See** [`zip`](./#val-zip) - -Equivalent to `zip xs ys |> List.map (fun (x,y) -> f x y)` - -```ocaml - zipBy [1;2;3] [4;5] (fun a b -> 2 * a + b) = [6;9];; -``` -``` -val mapWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithIndex : 'a t -> (int -> 'a -> 'b) -> 'b t -``` -`mapWithIndex xs f` applies `f` to each element of `xs`. Function `f` takes two arguments: the index starting from 0 and the element from `xs`. - -```ocaml - mapWithIndex [1;2;3] (fun i x -> i + x) = - [0 + 1; 1 + 2; 2 + 3 ] -``` -``` -val fromArray : 'a array -> 'a t -``` -`fromArray arr` converts the given array to a list - -```ocaml - fromArray [|1;2;3|] = [1;2;3] -``` -``` -val toArray : 'a t -> 'a array -``` -`toArray xs` converts the given list to an array - -```ocaml - toArray [1;2;3] = [|1;2;3|] -``` -``` -val reverse : 'a t -> 'a t -``` -`reverse xs` returns a new list whose elements are those of `xs` in reverse order. - -```ocaml - reverse [1;2;3] = [3;2;1] -``` -``` -val mapReverseU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val mapReverse : 'a t -> ('a -> 'b) -> 'b t -``` -`mapReverse xs f` - -Equivalent to `reverse (map xs f)` - -```ocaml - mapReverse [3;4;5] (fun x -> x * x) = [25;16;9];; -``` -``` -val forEachU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> 'b) -> unit -``` -`forEach xs f ` Call `f` on each element of `xs` from the beginning to end. `f` returns `unit`, so no new array is created. Use `foreach` when you are primarily concerned with repetitively creating side effects. - -```ocaml - forEach ["a";"b";"c"] (fun x -> Js.log("Item: " ^ x));; - (* prints: - Item: a - Item: b - Item: c - *) - - let us = ref 0;; - forEach [1;2;3;4] (fun x -> us := !us + x);; - !us = 1 + 2 + 3 + 4;; -``` -``` -val forEachWithIndexU : 'a t -> (int -> 'a -> 'b) Js.Fn.arity2 -> unit -``` -``` -val forEachWithIndex : 'a t -> (int -> 'a -> 'b) -> unit -``` -`forEachWithIndex xs f` - -```ocaml - - forEach ["a";"b";"c"] (fun i x -> Js.log("Item " ^ (string_of_int i) ^ " is " ^ x));; - (* prints: - Item 0 is a - Item 1 is b - Item 2 is cc - *) - - let total = ref 0 ;; - forEachWithIndex [10;11;12;13] (fun i x -> total := !total + x + i);; - !total = 0 + 10 + 1 + 11 + 2 + 12 + 3 + 13;; -``` -``` -val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b -``` -`reduce xs f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has two parameters: the item from the list and an “accumulator”, which starts with a value of `init`. `reduce` returns the final value of the accumulator. - -```ocaml - reduce [1;2;3;4] 0 (+) = 10;; - reduce [1;2;3;4] 10 (-) = 0;; - reduce [1;2;3;4] [] add = [4;3;2;1]; -``` -``` -val reduceWithIndexU : 'a t -> 'b -> ('b -> 'a -> int -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduceWithIndex : 'a t -> 'b -> ('b -> 'a -> int -> 'b) -> 'b -``` -`reduceWithIndex xs f` - -Applies `f` to each element of `xs` from beginning to end. Function `f` has three parameters: the item from the list and an “accumulator”, which starts with a value of `init` and the index of each element. `reduceWithIndex` returns the final value of the accumulator. - -```ocaml - reduceWithIndex [1;2;3;4] 0 (fun acc x i -> acc + x + i) = 16;; -``` -``` -val reduceReverseU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b -``` -``` -val reduceReverse : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b -``` -`reduceReverse xs f` - -Works like [`reduce`](./#val-reduce), except that function `f` is applied to each item of `xs` from the last back to the first. - -```ocaml - reduceReverse [1;2;3;4] 0 (+) = 10;; - reduceReverse [1;2;3;4] 10 (-) = 0;; - reduceReverse [1;2;3;4] [] add = [1;2;3;4];; -``` -``` -val mapReverse2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> 'c t -``` -``` -val mapReverse2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> 'c t -``` -`mapReverse2 xs ys f` - -equivalent to `reverse (zipBy xs ys f)` - -```ocaml - mapReverse2 [1;2;3] [1;2] (+) = [4;2] -``` -``` -val forEach2U : 'a t -> 'b t -> ('a -> 'b -> 'c) Js.Fn.arity2 -> unit -``` -``` -val forEach2 : 'a t -> 'b t -> ('a -> 'b -> 'c) -> unit -``` -`forEach2 xs ys f` stop with the shorter list - -``` -val reduce2U : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) Js.Fn.arity3 -> 'a -``` -``` -val reduce2 : 'b t -> 'c t -> 'a -> ('a -> 'b -> 'c -> 'a) -> 'a -``` -`reduce2 xs ys init f ` - -Applies `f` to each element of `xs` and `ys` from beginning to end. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. - -```ocaml - reduce2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; - reduce2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [2 +5;1 + 4 ];; (*add appends at end *) -``` -``` -val reduceReverse2U : - 'a t -> - 'b t -> - 'c -> - ('c -> 'a -> 'b -> 'c) Js.Fn.arity3 -> - 'c -``` -``` -val reduceReverse2 : 'a t -> 'b t -> 'c -> ('c -> 'a -> 'b -> 'c) -> 'c -``` -`reduceReverse2 xs ys init f ` - -Applies `f` to each element of `xs` and `ys` from end to beginning. Stops with the shorter list. Function `f` has three parameters: an “accumulator” which starts with a value of `init`, an item from `xs`, and an item from `ys`. `reduce2` returns the final value of the accumulator. - -```ocaml - reduceReverse2 [1;2;3] [4;5] 0 (fun acc x y -> acc + x * x + y) = 0 + (1 * 1 + 4) + (2 * 2 + 5);; - reduceReverse2 [1;2;3] [4;5] [] (fun acc x y -> add acc (x + y) = [1 + 4;2 + 5];; (*add appends at end *) -``` -``` -val everyU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : 'a t -> ('a -> bool) -> bool -``` -`every xs p` - -returns true if all elements satisfy p, where p is a predicate: a function taking an element and returning a bool. -```ocaml - every [] (fun x -> x mod 2 = 0) = true;; - every [2;4;6] (fun x -> x mod 2 = 0 ) = true;; - every [1;-3;5] (fun x -> x > 0) = false;; -``` -``` -val someU : 'a t -> ('a -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : 'a t -> ('a -> bool) -> bool -``` -`some xs p` - -returns true if at least one of the elements in xs satifies p, where p is a predicate: a function taking an element and returning a bool. -```ocaml - some [] (fun x -> x mod 2 = 0) = false ;; - some [1;2;4] (fun x -> x mod 2 = 0) = true;; - some [-1;-3;-5] (fun x -> x > 0) = false;; -``` -``` -val every2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val every2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`every2 xs ys p` returns true if predicate `p xi yi` is true for all pairs of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - every2 [1;2;3] [0;1] (>) = true;; - every2 [] [1] (fun x y -> x > y) = true;; - every2 [2;3] [1] (fun x y -> x > y) = true;; - every2 [0;1] [5;0] (fun x y -> x > y) = false; -``` -``` -val some2U : 'a t -> 'b t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val some2 : 'a t -> 'b t -> ('a -> 'b -> bool) -> bool -``` -`some2 xs ys p` returns true if `p xi yi` is true for any pair of elements up to the shorter length (i.e. `min (length xs) (length ys)`) - -```ocaml - some2 [0;2] [1;0;3] (>) = true ;; - some2 [] [1] (fun x y -> x > y) = false;; - some2 [2;3] [1;4] (fun x y -> x > y) = true;; -``` -``` -val cmpByLength : 'a t -> 'a t -> int -``` -`cmpByLength l1 l2` - -Compare two lists solely by length. Returns \-1 if `length l1` is less than `length l2`, 0 if `length l1` equals `length l2`, and 1 if `length l1` is greater than `length l2`. - -```ocaml -cmpByLength [1;2] [3;4;5;6] = -1;; -cmpByLength [1;2;3] [4;5;6] = 0;; -cmpByLength [1;2;3;4] [5;6] = 1;; -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -Compare elements one by one `f x y`. `f` returns - -- a negative number if `x` is “less than” `y` -- zero if `x` is “equal to” `y` -- a positive number if `x` is “greater than” `y` The comparison returns the first non-zero result of `f`, or zero if `f` returns zero for all `x` and `y`. If all items have compared equal, but `xs` is exhausted first, return \-1. (`xs` is shorter) If all items have compared equal, but `ys` is exhausted first, return 1 (`xs` is longer) -```ocaml - cmp [3] [3;7] (fun a b -> compare a b) = -1 - cmp [5;3] [5] (fun a b -> compare a b) = 1 - cmp [|1; 3; 5|] [|1; 4; 2|] (fun a b -> compare a b) = -1;; - cmp [|1; 3; 5|] [|1; 2; 3|] (fun a b -> compare a b) = 1;; - cmp [|1; 3; 5|] [|1; 3; 5|] (fun a b -> compare a b) = 0;; -``` -**Attention**: The total ordering of List is different from Array, for Array, we compare the length first and, only if the lengths are equal, elements one by one. For lists, we just compare elements one by one - -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq xs ys eqElem` check equality of `xs` and `ys` using `eqElem` for equality on elements, where `eqElem` is a function that returns true if items `x` and `y` meet some criterion for equality, false otherwise. `eq` false if length of `xs` and `ys` are not the same. - -```ocaml - eq [1;2;3] [1;2] (=) = false ;; - eq [1;2] [1;2] (=) = true;; - eq [1; 2; 3] [-1; -2; -3] (fun a b -> abs a = abs b) = true;; -``` -``` -val hasU : 'a t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val has : 'a t -> 'b -> ('a -> 'b -> bool) -> bool -``` -`has xs eqFcn` returns true if the list contains at least one element for which `eqFcn x` returns true - -```ocaml - has [1;2;3] 2 (=) = true;; - has [1;2;3] 4 (=) = false;; - has [-1;-2;-3] 2 (fun a b -> abs a = abs b) = true;; -``` -``` -val getByU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a option -``` -``` -val getBy : 'a t -> ('a -> bool) -> 'a option -``` -`getBy xs p` returns `Some value` for the first value in `xs` that satisifies the predicate function `p`; returns `None` if no element satisifies the function. - -```ocaml - getBy [1;4;3;2] (fun x -> x mod 2 = 0) = Some 4 - getBy [15;13;11] (fun x -> x mod 2 = 0) = None -``` -``` -val keepU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t -``` -``` -val keep : 'a t -> ('a -> bool) -> 'a t -``` -`keep xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` - -```ocaml - keep [1;2;3;4] (fun x -> x mod 2 = 0) = - [2;4] -``` -``` -val keepWithIndexU : 'a t -> ('a -> int -> bool) Js.Fn.arity2 -> 'a t -``` -``` -val keepWithIndex : 'a t -> ('a -> int -> bool) -> 'a t -``` -`keepWithIndex xs p` returns a list of all elements in `xs` which satisfy the predicate function `p` - -```ocaml - keepWithIndex [1;2;3;4] (fun _x i -> i mod 2 = 0) - = - [1;3] -``` -``` -val keepMapU : 'a t -> ('a -> 'b option) Js.Fn.arity1 -> 'b t -``` -``` -val keepMap : 'a t -> ('a -> 'b option) -> 'b t -``` -`keepMap xs f` applies `f` to each element of `xs`. If `f xi` returns `Some value`, then `value` is kept in the resulting list; if `f xi` returns `None`, the element is not retained in the result. - -```ocaml - keepMap [1;2;3;4] (fun x -> if x mod 2 = 0 then Some (-x ) else None) - = - [-2;-4] -``` -``` -val partitionU : 'a t -> ('a -> bool) Js.Fn.arity1 -> 'a t * 'a t -``` -``` -val partition : 'a t -> ('a -> bool) -> 'a t * 'a t -``` -`partition xs p` creates a pair of lists; the first list consists of all elements of `xs` that satisfy the predicate function `p`; the second list consists of all elements of `xs` that do not satisfy `p` - -```ocaml - partition [1;2;3;4] (fun x -> x mod 2 = 0) = - ([2;4], [1;3]) -``` -``` -val unzip : ('a * 'b) t -> 'a t * 'b t -``` -`unzip xs` takes a list of pairs and creates a pair of lists. The first list contains all the first items of the pairs; the second list contains all the second items. - -```ocaml - unzip [(1,2) ; (3,4)] = ([1;3], [2;4]);; - unzip [(1,2) ; (3,4) ; (5,6) ; (7,8)] = ([1;3;5;7], [2;4;6;8]);; -``` -``` -val getAssocU : - ('a * 'c) t -> - 'b -> - ('a -> 'b -> bool) Js.Fn.arity2 -> - 'c option -``` -``` -val getAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> 'c option -``` -`getAssoc xs k eq` - -return the second element of a pair in `xs` where the first element equals `x` as per the predicate function `eq`, or `None` if not found - -```ocaml - getAssoc [ 1, "a"; 2, "b"; 3, "c"] 2 (=) = Some "b" - getAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = Some "afternoon" -``` -``` -val hasAssocU : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val hasAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> bool -``` -`hasAssoc xs k eq` return true if there is a pair in `xs` where the first element equals `k` as per the predicate funtion `eq` - -```ocaml - hasAssoc [1, "a"; 2, "b"; 3,"c"] 1 (=) = true;; - hasAssoc [9, "morning"; 15, "afternoon"; 22, "night"] 3 (fun a b -> a mod 12 = b mod 12) = true;; -``` -``` -val removeAssocU : - ('a * 'c) t -> - 'b -> - ('a -> 'b -> bool) Js.Fn.arity2 -> - ('a * 'c) t -``` -``` -val removeAssoc : ('a * 'c) t -> 'b -> ('a -> 'b -> bool) -> ('a * 'c) t -``` -`removeAssoc xs k eq` Return a list after removing the first pair whose first value is `k` per the equality predicate `eq`; if not found, return a new list identical to `xs`. - -```ocaml - removeAssoc [1,"a"; 2, "b"; 3, "c" ] 1 (=) = - [2, "b"; 3, "c"] - removeAssoc [1,"a"; 2, "b"; 3, "c" ] 99 (=) = - [1, "a"; 2, "b"; 3, "c"] -``` -``` -val setAssocU : - ('a * 'c) t -> - 'a -> - 'c -> - ('a -> 'a -> bool) Js.Fn.arity2 -> - ('a * 'c) t -``` -``` -val setAssoc : ('a * 'c) t -> 'a -> 'c -> ('a -> 'a -> bool) -> ('a * 'c) t -``` -`setAssoc xs k v eq` if `k` exists in `xs` by satisfying the `eq` predicate, return a new list with the key and value replaced by the new `k` and `v`; otherwise, return a new list with the pair `k, v` added to the head of `xs`. - -```ocaml - setAssoc [1,"a"; 2, "b"; 3, "c"] 2 "x" (=) = - [1,"a"; 2, "x"; 3,"c"] ;; - - setAssoc [1,"a"; 3, "c"] 2 "b" (=) = - [2,"b"; 1,"a"; 3, "c"] - - setAssoc [9, "morning"; 3, "morning?!"; 22, "night"] 15 "afternoon" - (fun a b -> a mod 12 = b mod 12) = [9, "morning"; 15, "afternoon"; 22, "night"] -``` -Note carefully the last example\! Since `15 mod 12` equals `3 mod 12`, *both* the key and value are replaced in the list. - -``` -val sortU : 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a t -``` -``` -val sort : 'a t -> ('a -> 'a -> int) -> 'a t -``` -`sort xs` Returns a sorted list. - -```ocaml - sort [5; 4; 9; 3; 7] (fun a b -> a - b) = [3; 4; 5; 7; 9] -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map-Dict.md b/docs/api/re/melange/Belt-Map-Dict.md deleted file mode 100644 index 61b1e8167..000000000 --- a/docs/api/re/melange/Belt-Map-Dict.md +++ /dev/null @@ -1,281 +0,0 @@ - -# Module `Map.Dict` - -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -**Advanced usage only** - -``` -type ('key, 'value, 'id) t -``` -``` -type ('key, 'id) cmp -``` -``` -val empty : ('k, 'v, 'id) t -``` -``` -val isEmpty : ('k, 'v, 'id) t -> bool -``` -``` -val has : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> bool -``` -``` -val cmpU : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - kcmp:('k, 'id) cmp -> - vcmp:('v -> 'v -> int) Js.Fn.arity2 -> - int -``` -``` -val cmp : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - kcmp:('k, 'id) cmp -> - vcmp:('v -> 'v -> int) -> - int -``` -``` -val eqU : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - kcmp:('k, 'id) cmp -> - veq:('a -> 'a -> bool) Js.Fn.arity2 -> - bool -``` -``` -val eq : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - kcmp:('k, 'id) cmp -> - veq:('a -> 'a -> bool) -> - bool -``` -`eq m1 m2 cmp` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val findFirstByU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k * 'v) option -``` -``` -val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : - ('k, 'a, 'id) t -> - 'b -> - ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> - 'b -``` -``` -val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : ('k, 'a, 'id) t -> int -``` -``` -val toList : ('k, 'a, 'id) t -> ('k * 'a) list -``` -In increasing order. - -``` -val toArray : ('k, 'a, 'id) t -> ('k * 'a) array -``` -``` -val fromArray : ('k * 'a) array -> cmp:('k, 'id) cmp -> ('k, 'a, 'id) t -``` -``` -val keysToArray : ('k, 'a, 'id) t -> 'k array -``` -``` -val valuesToArray : ('k, 'a, 'id) t -> 'a array -``` -``` -val minKey : ('k, _, _) t -> 'k option -``` -``` -val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val maxKey : ('k, _, _) t -> 'k option -``` -``` -val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val minimum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val maximum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val get : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a option -``` -``` -val getUndefined : - ('k, 'a, 'id) t -> - 'k -> - cmp:('k, 'id) cmp -> - 'a Js.undefined -``` -``` -val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> cmp:('k, 'id) cmp -> 'a -``` -``` -val getExn : ('k, 'a, 'id) t -> 'k -> cmp:('k, 'id) cmp -> 'a -``` -``` -val checkInvariantInternal : (_, _, _) t -> unit -``` -**raise** when invariant is not held - -``` -val remove : ('a, 'b, 'id) t -> 'a -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t -``` -`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. - -``` -val removeMany : - ('a, 'b, 'id) t -> - 'a array -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val set : ('a, 'b, 'id) t -> 'a -> 'b -> cmp:('a, 'id) cmp -> ('a, 'b, 'id) t -``` -`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : - ('a, 'b, 'id) t -> - 'a -> - ('b option -> 'b option) Js.Fn.arity1 -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val update : - ('a, 'b, 'id) t -> - 'a -> - ('b option -> 'b option) -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val mergeU : - ('a, 'b, 'id) t -> - ('a, 'c, 'id) t -> - ('a -> 'b option -> 'c option -> 'd option) Js.Fn.arity3 -> - cmp:('a, 'id) cmp -> - ('a, 'd, 'id) t -``` -``` -val merge : - ('a, 'b, 'id) t -> - ('a, 'c, 'id) t -> - ('a -> 'b option -> 'c option -> 'd option) -> - cmp:('a, 'id) cmp -> - ('a, 'd, 'id) t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val mergeMany : - ('a, 'b, 'id) t -> - ('a * 'b) array -> - cmp:('a, 'id) cmp -> - ('a, 'b, 'id) t -``` -``` -val keepU : - ('k, 'a, 'id) t -> - ('k -> 'a -> bool) Js.Fn.arity2 -> - ('k, 'a, 'id) t -``` -``` -val keep : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> ('k, 'a, 'id) t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : - ('k, 'a, 'id) t -> - ('k -> 'a -> bool) Js.Fn.arity2 -> - ('k, 'a, 'id) t * ('k, 'a, 'id) t -``` -``` -val partition : - ('k, 'a, 'id) t -> - ('k -> 'a -> bool) -> - ('k, 'a, 'id) t * ('k, 'a, 'id) t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : - ('a, 'b, 'id) t -> - 'a -> - cmp:('a, 'id) cmp -> - (('a, 'b, 'id) t * ('a, 'b, 'id) t) * 'b option -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t -``` -``` -val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : - ('k, 'a, 'id) t -> - ('k -> 'a -> 'b) Js.Fn.arity2 -> - ('k, 'b, 'id) t -``` -``` -val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map-Int.md b/docs/api/re/melange/Belt-Map-Int.md deleted file mode 100644 index fe3ddaa90..000000000 --- a/docs/api/re/melange/Belt-Map-Int.md +++ /dev/null @@ -1,217 +0,0 @@ - -# Module `Map.Int` - -Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -type key = int -``` -``` -type 'value t -``` -The type of maps from type `key` to type `'value`. - -``` -val empty : 'v t -``` -``` -val isEmpty : 'v t -> bool -``` -``` -val has : 'v t -> key -> bool -``` -``` -val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int -``` -``` -val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool -``` -`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. - -``` -val findFirstByU : - 'v t -> - (key -> 'v -> bool) Js.Fn.arity2 -> - (key * 'v) option -``` -``` -val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'v t -> (key -> 'v -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 -``` -``` -val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'v t -> (key -> 'v -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'v t -> (key -> 'v -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : 'v t -> int -``` -``` -val toList : 'v t -> (key * 'v) list -``` -In increasing order. - -``` -val toArray : 'v t -> (key * 'v) array -``` -``` -val fromArray : (key * 'v) array -> 'v t -``` -``` -val keysToArray : 'v t -> key array -``` -``` -val valuesToArray : 'v t -> 'v array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'v t -> (key * 'v) option -``` -``` -val minUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val maximum : 'v t -> (key * 'v) option -``` -``` -val maxUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val get : 'v t -> key -> 'v option -``` -``` -val getUndefined : 'v t -> key -> 'v Js.undefined -``` -``` -val getWithDefault : 'v t -> key -> 'v -> 'v -``` -``` -val getExn : 'v t -> key -> 'v -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'v t -> key -> 'v t -``` -`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. - -``` -val removeMany : 'v t -> key array -> 'v t -``` -``` -val set : 'v t -> key -> 'v -> 'v t -``` -`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t -``` -``` -val update : 'v t -> key -> ('v option -> 'v option) -> 'v t -``` -``` -val mergeU : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> - 'c t -``` -``` -val merge : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) -> - 'c t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val mergeMany : 'v t -> (key * 'v) array -> 'v t -``` -``` -val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t -``` -``` -val keep : 'v t -> (key -> 'v -> bool) -> 'v t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t -``` -``` -val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : key -> 'v t -> 'v t * 'v option * 'v t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t -``` -``` -val map : 'v t -> ('v -> 'v2) -> 'v2 t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t -``` -``` -val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map-String.md b/docs/api/re/melange/Belt-Map-String.md deleted file mode 100644 index 1fa79b3e6..000000000 --- a/docs/api/re/melange/Belt-Map-String.md +++ /dev/null @@ -1,217 +0,0 @@ - -# Module `Map.String` - -specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -type key = string -``` -``` -type 'value t -``` -The type of maps from type `key` to type `'value`. - -``` -val empty : 'v t -``` -``` -val isEmpty : 'v t -> bool -``` -``` -val has : 'v t -> key -> bool -``` -``` -val cmpU : 'v t -> 'v t -> ('v -> 'v -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'v t -> 'v t -> ('v -> 'v -> int) -> int -``` -``` -val eqU : 'v t -> 'v t -> ('v -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'v t -> 'v t -> ('v -> 'v -> bool) -> bool -``` -`eq m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. - -``` -val findFirstByU : - 'v t -> - (key -> 'v -> bool) Js.Fn.arity2 -> - (key * 'v) option -``` -``` -val findFirstBy : 'v t -> (key -> 'v -> bool) -> (key * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : 'v t -> (key -> 'v -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'v t -> (key -> 'v -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) Js.Fn.arity3 -> 'v2 -``` -``` -val reduce : 'v t -> 'v2 -> ('v2 -> key -> 'v -> 'v2) -> 'v2 -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'v t -> (key -> 'v -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'v t -> (key -> 'v -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : 'v t -> int -``` -``` -val toList : 'v t -> (key * 'v) list -``` -In increasing order. - -``` -val toArray : 'v t -> (key * 'v) array -``` -``` -val fromArray : (key * 'v) array -> 'v t -``` -``` -val keysToArray : 'v t -> key array -``` -``` -val valuesToArray : 'v t -> 'v array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'v t -> (key * 'v) option -``` -``` -val minUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val maximum : 'v t -> (key * 'v) option -``` -``` -val maxUndefined : 'v t -> (key * 'v) Js.undefined -``` -``` -val get : 'v t -> key -> 'v option -``` -``` -val getUndefined : 'v t -> key -> 'v Js.undefined -``` -``` -val getWithDefault : 'v t -> key -> 'v -> 'v -``` -``` -val getExn : 'v t -> key -> 'v -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'v t -> key -> 'v t -``` -`remove m x` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. - -``` -val removeMany : 'v t -> key array -> 'v t -``` -``` -val set : 'v t -> key -> 'v -> 'v t -``` -`set m x y` returns a map containing the same bindings as `m`, plus a binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'v t -> key -> ('v option -> 'v option) Js.Fn.arity1 -> 'v t -``` -``` -val update : 'v t -> key -> ('v option -> 'v option) -> 'v t -``` -``` -val mergeU : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) Js.Fn.arity3 -> - 'c t -``` -``` -val merge : - 'v t -> - 'v2 t -> - (key -> 'v option -> 'v2 option -> 'c option) -> - 'c t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val mergeMany : 'v t -> (key * 'v) array -> 'v t -``` -``` -val keepU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t -``` -``` -val keep : 'v t -> (key -> 'v -> bool) -> 'v t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : 'v t -> (key -> 'v -> bool) Js.Fn.arity2 -> 'v t * 'v t -``` -``` -val partition : 'v t -> (key -> 'v -> bool) -> 'v t * 'v t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : key -> 'v t -> 'v t * 'v option * 'v t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : 'v t -> ('v -> 'v2) Js.Fn.arity1 -> 'v2 t -``` -``` -val map : 'v t -> ('v -> 'v2) -> 'v2 t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'v t -> (key -> 'v -> 'v2) Js.Fn.arity2 -> 'v2 t -``` -``` -val mapWithKey : 'v t -> (key -> 'v -> 'v2) -> 'v2 t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Map.md b/docs/api/re/melange/Belt-Map.md deleted file mode 100644 index 23dfe9607..000000000 --- a/docs/api/re/melange/Belt-Map.md +++ /dev/null @@ -1,460 +0,0 @@ - -# Module `Belt.Map` - -[`Belt.Map`](#), - -The top level provides generic **immutable** map operations. - -It also has three specialized inner modules [`Belt.Map.Int`](./Belt-Map-Int.md), [`Belt.Map.String`](./Belt-Map-String.md) and - -[`Belt.Map.Dict`](./Belt-Map-Dict.md): This module separates data from function which is more verbose but slightly more efficient - -A *immutable* sorted map module which allows customize *compare* behavior. - -The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. - -Example usage: - -```ocaml - module PairComparator = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c - end) - - let myMap = Belt.Map.make ~id:(module PairComparator) - let myMap2 = Belt.Map.set myMap (1, 2) "myValue" -``` -The API documentation below will assume a predeclared comparator module for integers, IntCmp - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module String : sig ... end -``` -specalized when key type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module Dict : sig ... end -``` -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -``` -type ('key, 'value, 'identity) t -``` -`('key, 'identity) t` - -`'key` is the field type - -`'value` is the element type - -`'identity` the identity of the collection - -``` -type ('key, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'key) -``` -The identity needed for making an empty map - -``` -val make : id:('k, 'id) id -> ('k, 'v, 'id) t -``` -`make ~id` creates a new map by taking in the comparator - -```ocaml - let m = Belt.Map.make ~id:(module IntCmp) -``` -``` -val isEmpty : (_, _, _) t -> bool -``` -`isEmpty m` checks whether a map m is empty - -```ocaml - isEmpty (fromArray [|1,"1"|] ~id:(module IntCmp)) = false -``` -``` -val has : ('k, 'v, 'id) t -> 'k -> bool -``` -`has m k` checks whether m has the key k - -```ocaml - has (fromArray [|1,"1"|] ~id:(module IntCmp)) 1 = true -``` -``` -val cmpU : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - ('v -> 'v -> int) Js.Fn.arity2 -> - int -``` -``` -val cmp : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> int) -> int -``` -`cmp m0 m1 vcmp` - -Total ordering of map given total ordering of value function. - -It will compare size first and each element following the order one by one. - -``` -val eqU : - ('k, 'v, 'id) t -> - ('k, 'v, 'id) t -> - ('v -> 'v -> bool) Js.Fn.arity2 -> - bool -``` -``` -val eq : ('k, 'v, 'id) t -> ('k, 'v, 'id) t -> ('v -> 'v -> bool) -> bool -``` -`eq m1 m2 veq` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `veq` is the equality predicate used to compare the data associated with the keys. - -``` -val findFirstByU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k * 'v) option -``` -``` -val findFirstBy : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k * 'v) option -``` -`findFirstBy m p` uses funcion `f` to find the first key value pair to match predicate `p`. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - findFirstBy s0 (fun k v -> k = 4 ) = option (4, "4");; -``` -``` -val forEachU : ('k, 'v, 'id) t -> ('k -> 'v -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : ('k, 'v, 'id) t -> ('k -> 'v -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - let acc = ref [] ;; - forEach s0 (fun k v -> acc := (k,v) :: !acc);; - - !acc = [4,"4"; 3,"3"; 2,"2"; 1,"1"] -``` -``` -val reduceU : - ('k, 'v, 'id) t -> - 'acc -> - ('acc -> 'k -> 'v -> 'acc) Js.Fn.arity3 -> - 'acc -``` -``` -val reduce : ('k, 'v, 'id) t -> 'acc -> ('acc -> 'k -> 'v -> 'acc) -> 'acc -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|4,"4";1,"1";2,"2,"3""|];; - reduce s0 [] (fun acc k v -> (k,v) acc ) = [4,"4";3,"3";2,"2";1,"1"];; -``` -``` -val everyU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. Order unspecified - -``` -val someU : ('k, 'v, 'id) t -> ('k -> 'v -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. Order unspecified - -``` -val size : ('k, 'v, 'id) t -> int -``` -`size s` - -```ocaml - size (fromArray [2,"2"; 2,"1"; 3,"3"] ~id:(module IntCmp)) = 2 ;; -``` -``` -val toArray : ('k, 'v, 'id) t -> ('k * 'v) array -``` -`toArray s` - -```ocaml - toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] -``` -``` -val toList : ('k, 'v, 'id) t -> ('k * 'v) list -``` -In increasing order - -**See** [`toArray`](./#val-toArray) - -``` -val fromArray : ('k * 'v) array -> id:('k, 'id) id -> ('k, 'v, 'id) t -``` -`fromArray kvs ~id` - -```ocaml - toArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = [1,"1";2,"2";3,"3"] -``` -``` -val keysToArray : ('k, 'v, 'id) t -> 'k array -``` -`keysToArray s` - -```ocaml - keysToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = - [|1;2;3|];; -``` -``` -val valuesToArray : ('k, 'v, 'id) t -> 'v array -``` -`valuesToArray s` - -```ocaml - valuesToArray (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) = - [|"1";"2";"3"|];; -``` -``` -val minKey : ('k, _, _) t -> 'k option -``` -`minKey s` - -returns the minimum key, None if not exist -``` -val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -**See** [`minKey`](./#val-minKey) - -``` -val maxKey : ('k, _, _) t -> 'k option -``` -`maxKey s` - -returns the maximum key, None if not exist -``` -val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -**See** [`maxKey`](./#val-maxKey) - -``` -val minimum : ('k, 'v, _) t -> ('k * 'v) option -``` -`minimum s` - -returns the minimum key value pair, None if not exist -``` -val minUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined -``` -**See** [`minimum`](./#val-minimum) - -``` -val maximum : ('k, 'v, _) t -> ('k * 'v) option -``` -`maximum s` - -returns the maximum key value pair, None if not exist -``` -val maxUndefined : ('k, 'v, _) t -> ('k * 'v) Js.undefined -``` -**See** [`maximum`](./#val-maximum) - -``` -val get : ('k, 'v, 'id) t -> 'k -> 'v option -``` -`get s k` - -```ocaml - get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = - Some "2";; - get (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp)) 2 = - None;; -``` -``` -val getUndefined : ('k, 'v, 'id) t -> 'k -> 'v Js.undefined -``` -**See** [`get`](./#val-get) - -returns undefined when not found -``` -val getWithDefault : ('k, 'v, 'id) t -> 'k -> 'v -> 'v -``` -`getWithDefault s k default` - -**See** [`get`](./#val-get) - -returns default when k is not found -``` -val getExn : ('k, 'v, 'id) t -> 'k -> 'v -``` -`getExn s k` - -**See** [`getExn`](./#val-getExn) - -**raise** when `k` not exist - -``` -val remove : ('k, 'v, 'id) t -> 'k -> ('k, 'v, 'id) t -``` -`remove m x` when `x` is not in `m`, `m` is returned reference unchanged. - -```ocaml - let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; - - let s1 = remove s0 1;; - let s2 = remove s1 1;; - s1 == s2 ;; - keysToArray s1 = [|2;3|];; -``` -``` -val removeMany : ('k, 'v, 'id) t -> 'k array -> ('k, 'v, 'id) t -``` -`removeMany s xs` - -Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` - -``` -val set : ('k, 'v, 'id) t -> 'k -> 'v -> ('k, 'v, 'id) t -``` -`set m x y ` returns a map containing the same bindings as `m`, with a new binding of `x` to `y`. If `x` was already bound in `m`, its previous binding disappears. - -```ocaml - let s0 = (fromArray [2,"2"; 1,"1"; 3,"3"] ~id:(module IntCmp));; - - let s1 = set s0 2 "3";; - - valuesToArray s1 = ["1";"3";"3"];; -``` -``` -val updateU : - ('k, 'v, 'id) t -> - 'k -> - ('v option -> 'v option) Js.Fn.arity1 -> - ('k, 'v, 'id) t -``` -``` -val update : - ('k, 'v, 'id) t -> - 'k -> - ('v option -> 'v option) -> - ('k, 'v, 'id) t -``` -`update m x f` returns a map containing the same bindings as `m`, except for the binding of `x`. Depending on the value of `y` where `y` is `f (get x m)`, the binding of `x` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `x` is associated to `z` in the resulting map. - -``` -val mergeMany : ('k, 'v, 'id) t -> ('k * 'v) array -> ('k, 'v, 'id) t -``` -`mergeMany s xs` - -Add each of `xs` to `s`, note unlike [`set`](./#val-set), the reference of return value might be changed even if all values in `xs` exist `s` - -``` -val mergeU : - ('k, 'v, 'id) t -> - ('k, 'v2, 'id) t -> - ('k -> 'v option -> 'v2 option -> 'v3 option) Js.Fn.arity3 -> - ('k, 'v3, 'id) t -``` -``` -val merge : - ('k, 'v, 'id) t -> - ('k, 'v2, 'id) t -> - ('k -> 'v option -> 'v2 option -> 'v3 option) -> - ('k, 'v3, 'id) t -``` -`merge m1 m2 f` computes a map whose keys is a subset of keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. - -``` -val keepU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k, 'v, 'id) t -``` -``` -val keep : ('k, 'v, 'id) t -> ('k -> 'v -> bool) -> ('k, 'v, 'id) t -``` -`keep m p` returns the map with all the bindings in `m` that satisfy predicate `p`. - -``` -val partitionU : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) Js.Fn.arity2 -> - ('k, 'v, 'id) t * ('k, 'v, 'id) t -``` -``` -val partition : - ('k, 'v, 'id) t -> - ('k -> 'v -> bool) -> - ('k, 'v, 'id) t * ('k, 'v, 'id) t -``` -`partition m p` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `s` that satisfy the predicate `p`, and `m2` is the map with all the bindings of `s` that do not satisfy `p`. - -``` -val split : - ('k, 'v, 'id) t -> - 'k -> - (('k, 'v, 'id) t * ('k, 'v, 'id) t) * 'v option -``` -`split x m` returns a tuple `(l r), data`, where `l` is the map with all the bindings of `m` whose 'k is strictly less than `x`; `r` is the map with all the bindings of `m` whose 'k is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -``` -val mapU : ('k, 'v, 'id) t -> ('v -> 'v2) Js.Fn.arity1 -> ('k, 'v2, 'id) t -``` -``` -val map : ('k, 'v, 'id) t -> ('v -> 'v2) -> ('k, 'v2, 'id) t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : - ('k, 'v, 'id) t -> - ('k -> 'v -> 'v2) Js.Fn.arity2 -> - ('k, 'v2, 'id) t -``` -``` -val mapWithKey : ('k, 'v, 'id) t -> ('k -> 'v -> 'v2) -> ('k, 'v2, 'id) t -``` -`mapWithKey m f` - -The same as [`map`](./#val-map) except that `f` is supplied with one more argument: the key - -``` -val getData : ('k, 'v, 'id) t -> ('k, 'v, 'id) Belt__.Belt_MapDict.t -``` -`getData s0` - -**Advanced usage only** - -returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing -``` -val getId : ('k, 'v, 'id) t -> ('k, 'id) id -``` -`getId s0` - -**Advanced usage only** - -returns the identity of s0 -``` -val packIdData : - id:('k, 'id) id -> - data:('k, 'v, 'id) Belt__.Belt_MapDict.t -> - ('k, 'v, 'id) t -``` -`packIdData ~id ~data` - -**Advanced usage only** - -returns the packed collection \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableMap-Int.md b/docs/api/re/melange/Belt-MutableMap-Int.md deleted file mode 100644 index 09b46fa13..000000000 --- a/docs/api/re/melange/Belt-MutableMap-Int.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `MutableMap.Int` - -``` -type key = int -``` -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val isEmpty : 'a t -> bool -``` -``` -val has : 'a t -> key -> bool -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair - -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq m1 m2 cmp` - -``` -val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'a t -> (key -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. - -``` -val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'a t -> (key -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'a t -> (key -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val size : 'a t -> int -``` -``` -val toList : 'a t -> (key * 'a) list -``` -In increasing order - -``` -val toArray : 'a t -> (key * 'a) array -``` -In increasing order - -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'a t -> (key * 'a) option -``` -``` -val minUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val maximum : 'a t -> (key * 'a) option -``` -``` -val maxUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val getUndefined : 'a t -> key -> 'a Js.undefined -``` -``` -val getWithDefault : 'a t -> key -> 'a -> 'a -``` -``` -val getExn : 'a t -> key -> 'a -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'a t -> key -> unit -``` -`remove m x` do the in-place modification - -``` -val removeMany : 'a t -> key array -> unit -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit -``` -``` -val update : 'a t -> key -> ('a option -> 'a option) -> unit -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableMap-String.md b/docs/api/re/melange/Belt-MutableMap-String.md deleted file mode 100644 index 8743e1b84..000000000 --- a/docs/api/re/melange/Belt-MutableMap-String.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `MutableMap.String` - -``` -type key = string -``` -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val isEmpty : 'a t -> bool -``` -``` -val has : 'a t -> key -> bool -``` -``` -val cmpU : 'a t -> 'a t -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : 'a t -> 'a t -> ('a -> 'a -> int) -> int -``` -`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair - -``` -val eqU : 'a t -> 'a t -> ('a -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : 'a t -> 'a t -> ('a -> 'a -> bool) -> bool -``` -`eq m1 m2 cmp` - -``` -val forEachU : 'a t -> (key -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : 'a t -> (key -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The application order of `f` is in increasing order. - -``` -val reduceU : 'a t -> 'b -> ('b -> key -> 'a -> 'b) Js.Fn.arity3 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> key -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : 'a t -> (key -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val someU : 'a t -> (key -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : 'a t -> (key -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. The application order of `p` is unspecified. - -``` -val size : 'a t -> int -``` -``` -val toList : 'a t -> (key * 'a) list -``` -In increasing order - -``` -val toArray : 'a t -> (key * 'a) array -``` -In increasing order - -``` -val fromArray : (key * 'a) array -> 'a t -``` -``` -val keysToArray : 'a t -> key array -``` -``` -val valuesToArray : 'a t -> 'a array -``` -``` -val minKey : _ t -> key option -``` -``` -val minKeyUndefined : _ t -> key Js.undefined -``` -``` -val maxKey : _ t -> key option -``` -``` -val maxKeyUndefined : _ t -> key Js.undefined -``` -``` -val minimum : 'a t -> (key * 'a) option -``` -``` -val minUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val maximum : 'a t -> (key * 'a) option -``` -``` -val maxUndefined : 'a t -> (key * 'a) Js.undefined -``` -``` -val get : 'a t -> key -> 'a option -``` -``` -val getUndefined : 'a t -> key -> 'a Js.undefined -``` -``` -val getWithDefault : 'a t -> key -> 'a -> 'a -``` -``` -val getExn : 'a t -> key -> 'a -``` -``` -val checkInvariantInternal : _ t -> unit -``` -**raise** when invariant is not held - -``` -val remove : 'a t -> key -> unit -``` -`remove m x` do the in-place modification - -``` -val removeMany : 'a t -> key array -> unit -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`set m x y` do the in-place modification, return `m` for chaining. If `x` was already bound in `m`, its previous binding disappears. - -``` -val updateU : 'a t -> key -> ('a option -> 'a option) Js.Fn.arity1 -> unit -``` -``` -val update : 'a t -> key -> ('a option -> 'a option) -> unit -``` -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : 'a t -> (key -> 'a -> 'b) Js.Fn.arity2 -> 'b t -``` -``` -val mapWithKey : 'a t -> (key -> 'a -> 'b) -> 'b t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableMap.md b/docs/api/re/melange/Belt-MutableMap.md deleted file mode 100644 index cf079ddd2..000000000 --- a/docs/api/re/melange/Belt-MutableMap.md +++ /dev/null @@ -1,206 +0,0 @@ - -# Module `Belt.MutableMap` - -[`Belt.MutableMap`](#) - -The top level provides generic **mutable** map operations. - -It also has two specialized inner modules [`Belt.MutableMap.Int`](./Belt-MutableMap-Int.md) and [`Belt.MutableMap.String`](./Belt-MutableMap-String.md) - -``` -module Int : sig ... end -``` -``` -module String : sig ... end -``` -A **mutable** sorted map module which allows customize *compare* behavior. - -Same as Belt.Map, but mutable. - -``` -type ('k, 'v, 'id) t -``` -``` -type ('key, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'key) -``` -``` -val make : id:('k, 'id) id -> ('k, 'a, 'id) t -``` -``` -val clear : (_, _, _) t -> unit -``` -``` -val isEmpty : (_, _, _) t -> bool -``` -``` -val has : ('k, _, _) t -> 'k -> bool -``` -``` -val cmpU : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - ('a -> 'a -> int) Js.Fn.arity2 -> - int -``` -``` -val cmp : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> int) -> int -``` -`cmp m1 m2 cmp` First compare by size, if size is the same, compare by key, value pair - -``` -val eqU : - ('k, 'a, 'id) t -> - ('k, 'a, 'id) t -> - ('a -> 'a -> bool) Js.Fn.arity2 -> - bool -``` -``` -val eq : ('k, 'a, 'id) t -> ('k, 'a, 'id) t -> ('a -> 'a -> bool) -> bool -``` -`eq m1 m2 eqf` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `eqf` is the equality predicate used to compare the data associated with the keys. - -``` -val forEachU : ('k, 'a, 'id) t -> ('k -> 'a -> unit) Js.Fn.arity2 -> unit -``` -``` -val forEach : ('k, 'a, 'id) t -> ('k -> 'a -> unit) -> unit -``` -`forEach m f` applies `f` to all bindings in map `m`. `f` receives the 'k as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val reduceU : - ('k, 'a, 'id) t -> - 'b -> - ('b -> 'k -> 'a -> 'b) Js.Fn.arity3 -> - 'b -``` -``` -val reduce : ('k, 'a, 'id) t -> 'b -> ('b -> 'k -> 'a -> 'b) -> 'b -``` -`reduce m a f` computes `(f kN dN ... (f k1 d1 a)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - -``` -val everyU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val every : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`every m p` checks if all the bindings of the map satisfy the predicate `p`. - -``` -val someU : ('k, 'a, 'id) t -> ('k -> 'a -> bool) Js.Fn.arity2 -> bool -``` -``` -val some : ('k, 'a, 'id) t -> ('k -> 'a -> bool) -> bool -``` -`some m p` checks if at least one binding of the map satisfy the predicate `p`. - -``` -val size : ('k, 'a, 'id) t -> int -``` -``` -val toList : ('k, 'a, 'id) t -> ('k * 'a) list -``` -In increasing order - -``` -val toArray : ('k, 'a, 'id) t -> ('k * 'a) array -``` -In increasing order - -``` -val fromArray : ('k * 'a) array -> id:('k, 'id) id -> ('k, 'a, 'id) t -``` -``` -val keysToArray : ('k, _, _) t -> 'k array -``` -``` -val valuesToArray : (_, 'a, _) t -> 'a array -``` -``` -val minKey : ('k, _, _) t -> 'k option -``` -``` -val minKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val maxKey : ('k, _, _) t -> 'k option -``` -``` -val maxKeyUndefined : ('k, _, _) t -> 'k Js.undefined -``` -``` -val minimum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val minUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val maximum : ('k, 'a, _) t -> ('k * 'a) option -``` -``` -val maxUndefined : ('k, 'a, _) t -> ('k * 'a) Js.undefined -``` -``` -val get : ('k, 'a, 'id) t -> 'k -> 'a option -``` -``` -val getUndefined : ('k, 'a, 'id) t -> 'k -> 'a Js.undefined -``` -``` -val getWithDefault : ('k, 'a, 'id) t -> 'k -> 'a -> 'a -``` -``` -val getExn : ('k, 'a, 'id) t -> 'k -> 'a -``` -``` -val checkInvariantInternal : (_, _, _) t -> unit -``` -**raise** when invariant is not held - -``` -val remove : ('k, 'a, 'id) t -> 'k -> unit -``` -`remove m x` do the in-place modification, - -``` -val removeMany : ('k, 'a, 'id) t -> 'k array -> unit -``` -``` -val set : ('k, 'a, 'id) t -> 'k -> 'a -> unit -``` -`set m x y ` do the in-place modification - -``` -val updateU : - ('k, 'a, 'id) t -> - 'k -> - ('a option -> 'a option) Js.Fn.arity1 -> - unit -``` -``` -val update : ('k, 'a, 'id) t -> 'k -> ('a option -> 'a option) -> unit -``` -``` -val mergeMany : ('k, 'a, 'id) t -> ('k * 'a) array -> unit -``` -``` -val mapU : ('k, 'a, 'id) t -> ('a -> 'b) Js.Fn.arity1 -> ('k, 'b, 'id) t -``` -``` -val map : ('k, 'a, 'id) t -> ('a -> 'b) -> ('k, 'b, 'id) t -``` -`map m f` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapWithKeyU : - ('k, 'a, 'id) t -> - ('k -> 'a -> 'b) Js.Fn.arity2 -> - ('k, 'b, 'id) t -``` -``` -val mapWithKey : ('k, 'a, 'id) t -> ('k -> 'a -> 'b) -> ('k, 'b, 'id) t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-MutableQueue.md b/docs/api/re/melange/Belt-MutableQueue.md deleted file mode 100644 index fcb94e0a5..000000000 --- a/docs/api/re/melange/Belt-MutableQueue.md +++ /dev/null @@ -1,114 +0,0 @@ - -# Module `Belt.MutableQueue` - -[`Belt.MutableQueue`](#) - -An FIFO(first in first out) queue data structure - -First-in first-out queues. - -This module implements queues (FIFOs), with in-place modification. - -``` -type 'a t -``` -The type of queues containing elements of type `'a`. - -``` -val make : unit -> 'a t -``` -returns a new queue, initially empty. -``` -val clear : 'a t -> unit -``` -Discard all elements from the queue. - -``` -val isEmpty : 'a t -> bool -``` -returns true if the given queue is empty, false otherwise. -``` -val fromArray : 'a array -> 'a t -``` -`fromArray a` is equivalent to `Array.forEach a (add q a)` - -``` -val add : 'a t -> 'a -> unit -``` -`add q x` adds the element `x` at the end of the queue `q`. - -``` -val peek : 'a t -> 'a option -``` -`peekOpt q` returns the first element in queue `q`, without removing it from the queue. - -``` -val peekUndefined : 'a t -> 'a Js.undefined -``` -`peekUndefined q` returns `undefined` if not found - -``` -val peekExn : 'a t -> 'a -``` -`peekExn q` - -**raise** an exception if `q` is empty - -``` -val pop : 'a t -> 'a option -``` -`pop q` removes and returns the first element in queue `q`. - -``` -val popUndefined : 'a t -> 'a Js.undefined -``` -`popUndefined q` removes and returns the first element in queue `q`. it will return undefined if it is already empty - -``` -val popExn : 'a t -> 'a -``` -`popExn q` - -**raise** an exception if `q` is empty - -``` -val copy : 'a t -> 'a t -``` -`copy q` - -returns a fresh queue -``` -val size : 'a t -> int -``` -returns the number of elements in a queue. -``` -val mapU : 'a t -> ('a -> 'b) Js.Fn.arity1 -> 'b t -``` -``` -val map : 'a t -> ('a -> 'b) -> 'b t -``` -``` -val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> unit) -> unit -``` -`forEach q f` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. - -``` -val reduceU : 'a t -> 'b -> ('b -> 'a -> 'b) Js.Fn.arity2 -> 'b -``` -``` -val reduce : 'a t -> 'b -> ('b -> 'a -> 'b) -> 'b -``` -`reduce q accu f` is equivalent to `List.reduce l accu f`, where `l` is the list of `q`'s elements. The queue remains unchanged. - -``` -val transfer : 'a t -> 'a t -> unit -``` -`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `forEach (fun x -> add x q2) q1; clear q1`, but runs in constant time. - -``` -val toArray : 'a t -> 'a array -``` -First added will be in the beginning of the array diff --git a/docs/api/re/melange/Belt-MutableSet-Int.md b/docs/api/re/melange/Belt-MutableSet-Int.md deleted file mode 100644 index 5c5d225e5..000000000 --- a/docs/api/re/melange/Belt-MutableSet-Int.md +++ /dev/null @@ -1,166 +0,0 @@ - -# Module `MutableSet.Int` - -Specalized when key type is `int`, more efficient than the generic type - -This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.MutableSet`](./Belt-MutableSet.md) - -``` -type value = int -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val make : unit -> t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val copy : t -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> unit -``` -``` -val addCheck : t -> value -> bool -``` -``` -val mergeMany : t -> value array -> unit -``` -``` -val remove : t -> value -> unit -``` -``` -val removeCheck : t -> value -> bool -``` -``` -val removeMany : t -> value array -> unit -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -``` -val cmp : t -> t -> int -``` -``` -val eq : t -> t -> bool -``` -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order with respect - -``` -val toArray : t -> value array -``` -In increasing order with respect - -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split s key` return a fresh copy of each - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-MutableSet-String.md b/docs/api/re/melange/Belt-MutableSet-String.md deleted file mode 100644 index df5e825f6..000000000 --- a/docs/api/re/melange/Belt-MutableSet-String.md +++ /dev/null @@ -1,166 +0,0 @@ - -# Module `MutableSet.String` - -Specalized when key type is `string`, more efficient than the generic type - -This module is [`Belt.MutableSet`](./Belt-MutableSet.md) specialized with key type to be a primitive type. - -It is more efficient in general, the API is the same with [`Belt.MutableSet`](./Belt-MutableSet.md) except its key type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.MutableSet`](./Belt-MutableSet.md) - -``` -type value = string -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val make : unit -> t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val copy : t -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> unit -``` -``` -val addCheck : t -> value -> bool -``` -``` -val mergeMany : t -> value array -> unit -``` -``` -val remove : t -> value -> unit -``` -``` -val removeCheck : t -> value -> bool -``` -``` -val removeMany : t -> value array -> unit -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -``` -val cmp : t -> t -> int -``` -``` -val eq : t -> t -> bool -``` -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep s p` returns a fresh copy of the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition s p` returns a fresh copy pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order with respect - -``` -val toArray : t -> value array -``` -In increasing order with respect - -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split s key` return a fresh copy of each - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-MutableSet.md b/docs/api/re/melange/Belt-MutableSet.md deleted file mode 100644 index ab101f1c9..000000000 --- a/docs/api/re/melange/Belt-MutableSet.md +++ /dev/null @@ -1,189 +0,0 @@ - -# Module `Belt.MutableSet` - -[`Belt.MutableSet`](#) - -The top level provides generic **mutable** set operations. - -It also has two specialized inner modules [`Belt.MutableSet.Int`](./Belt-MutableSet-Int.md) and [`Belt.MutableSet.String`](./Belt-MutableSet-String.md) - -A *mutable* sorted set module which allows customize *compare* behavior. - -Same as Belt.Set, but mutable. - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -type ('k, 'id) t -``` -``` -type ('k, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'k) -``` -``` -val make : id:('value, 'id) id -> ('value, 'id) t -``` -``` -val fromArray : 'k array -> id:('k, 'id) id -> ('k, 'id) t -``` -``` -val fromSortedArrayUnsafe : - 'value array -> - id:('value, 'id) id -> - ('value, 'id) t -``` -``` -val copy : ('k, 'id) t -> ('k, 'id) t -``` -``` -val isEmpty : (_, _) t -> bool -``` -``` -val has : ('value, _) t -> 'value -> bool -``` -``` -val add : ('value, 'id) t -> 'value -> unit -``` -``` -val addCheck : ('value, 'id) t -> 'value -> bool -``` -``` -val mergeMany : ('value, 'id) t -> 'value array -> unit -``` -``` -val remove : ('value, 'id) t -> 'value -> unit -``` -``` -val removeCheck : ('value, 'id) t -> 'value -> bool -``` -``` -val removeMany : ('value, 'id) t -> 'value array -> unit -``` -``` -val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -``` -val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -``` -val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -``` -val subset : ('value, 'id) t -> ('value, 'id) t -> bool -``` -``` -val cmp : ('value, 'id) t -> ('value, 'id) t -> int -``` -``` -val eq : ('value, 'id) t -> ('value, 'id) t -> bool -``` -``` -val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('value, 'id) t -> ('value -> unit) -> unit -``` -`forEach m f` applies `f` in turn to all elements of `m`. In increasing order - -``` -val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a -``` -In increasing order. - -``` -val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : ('value, 'id) t -> ('value -> bool) -> bool -``` -`every s p` checks if all elements of the set satisfy the predicate `p`. Order unspecified - -``` -val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : ('value, 'id) t -> ('value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. - -``` -val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t -``` -``` -val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t -``` -`keep s p` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : - ('value, 'id) t -> - ('value -> bool) Js.Fn.arity1 -> - ('value, 'id) t * ('value, 'id) t -``` -``` -val partition : - ('value, 'id) t -> - ('value -> bool) -> - ('value, 'id) t * ('value, 'id) t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : ('value, 'id) t -> int -``` -``` -val toList : ('value, 'id) t -> 'value list -``` -In increasing order - -``` -val toArray : ('value, 'id) t -> 'value array -``` -In increasing order - -``` -val minimum : ('value, 'id) t -> 'value option -``` -``` -val minUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val maximum : ('value, 'id) t -> 'value option -``` -``` -val maxUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val get : ('value, 'id) t -> 'value -> 'value option -``` -``` -val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined -``` -``` -val getExn : ('value, 'id) t -> 'value -> 'value -``` -``` -val split : - ('value, 'id) t -> - 'value -> - (('value, 'id) t * ('value, 'id) t) * bool -``` -`split s x` returns a triple `((l, r), present)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. `l,r` are freshly made, no sharing with `s` - -``` -val checkInvariantInternal : (_, _) t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-MutableStack.md b/docs/api/re/melange/Belt-MutableStack.md deleted file mode 100644 index 291f3caa3..000000000 --- a/docs/api/re/melange/Belt-MutableStack.md +++ /dev/null @@ -1,62 +0,0 @@ - -# Module `Belt.MutableStack` - -[`Belt.MutableStack`](#) - -An FILO(first in last out) stack data structure - -First in last out stack. - -This module implements stacks, with in-place modification. - -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -returns a new stack, initially empty. -``` -val clear : 'a t -> unit -``` -Discard all elements from the stack. - -``` -val copy : 'a t -> 'a t -``` -`copy x` O(1) operation, return a new stack - -``` -val push : 'a t -> 'a -> unit -``` -``` -val popUndefined : 'a t -> 'a Js.undefined -``` -``` -val pop : 'a t -> 'a option -``` -``` -val topUndefined : 'a t -> 'a Js.undefined -``` -``` -val top : 'a t -> 'a option -``` -``` -val isEmpty : 'a t -> bool -``` -``` -val size : 'a t -> int -``` -``` -val forEachU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : 'a t -> ('a -> unit) -> unit -``` -``` -val dynamicPopIterU : 'a t -> ('a -> unit) Js.Fn.arity1 -> unit -``` -``` -val dynamicPopIter : 'a t -> ('a -> unit) -> unit -``` -`dynamicPopIter s f ` apply `f` to each element of `s`. The item is poped before applying `f`, `s` will be empty after this opeartion. This function is useful for worklist algorithm diff --git a/docs/api/re/melange/Belt-Option.md b/docs/api/re/melange/Belt-Option.md deleted file mode 100644 index a13563de7..000000000 --- a/docs/api/re/melange/Belt-Option.md +++ /dev/null @@ -1,200 +0,0 @@ - -# Module `Belt.Option` - -[`Belt.Option`](#) - -Utilities for option data type. - -[`Belt.Option`](#) - -Utilities for option data type - -``` -val keepU : 'a option -> ('a -> bool) Js.Fn.arity1 -> 'a option -``` -Uncurried version of `keep` - -``` -val keep : 'a option -> ('a -> bool) -> 'a option -``` -`keep optionValue p` - -If `optionValue` is `Some value` and `p value = true`, it returns `Some value`; otherwise returns `None` - -```ocaml - keep (Some 10)(fun x -> x > 5);; (* returns [Some 10] *) - keep (Some 4)(fun x -> x > 5);; (* returns [None] *) - keep None (fun x -> x > 5);; (* returns [None] *) -``` -``` -val forEachU : 'a option -> ('a -> unit) Js.Fn.arity1 -> unit -``` -Uncurried version of `forEach` - -``` -val forEach : 'a option -> ('a -> unit) -> unit -``` -`forEach optionValue f` - -If `optionValue` is `Some value`, it calls `f value`; otherwise returns `()` - -```ocaml - forEach (Some "thing")(fun x -> Js.log x);; (* logs "thing" *) - forEach None (fun x -> Js.log x);; (* returns () *) -``` -``` -val getExn : 'a option -> 'a -``` -`getExn optionalValue` Returns `value` if `optionalValue` is `Some value`, otherwise raises `getExn` - -```ocaml - getExn (Some 3) = 3;; - getExn None (* Raises getExn error *) -``` -``` -val getUnsafe : 'a option -> 'a -``` -`getUnsafe x` returns x This is an unsafe operation, it assumes x is neither not None or (Some (None .. )) - -``` -val mapWithDefaultU : 'a option -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b -``` -Uncurried version of `mapWithDefault` - -``` -val mapWithDefault : 'a option -> 'b -> ('a -> 'b) -> 'b -``` -`mapWithDefault optionValue default f` - -If `optionValue` is `Some value`, returns `f value`; otherwise returns `default` - -```ocaml - mapWithDefault (Some 3) 0 (fun x -> x + 5) = 8;; - mapWithDefault None 0 (fun x -> x + 5) = 0;; -``` -``` -val mapU : 'a option -> ('a -> 'b) Js.Fn.arity1 -> 'b option -``` -Uncurried version of `map` - -``` -val map : 'a option -> ('a -> 'b) -> 'b option -``` -`map optionValue f` - -If `optionValue` is `Some value`, returns `Some (f value)`; otherwise returns `None` - -```ocaml - map (Some 3) (fun x -> x * x) = (Some 9);; - map None (fun x -> x * x) = None;; -``` -``` -val flatMapU : 'a option -> ('a -> 'b option) Js.Fn.arity1 -> 'b option -``` -Uncurried version of `flatMap` - -``` -val flatMap : 'a option -> ('a -> 'b option) -> 'b option -``` -`flatMap optionValue f` - -If `optionValue` is `Some value`, returns `f value`; otherwise returns `None` The function `f` must have a return type of `'a option` - -```ocaml - let f (x : float) = - if x >= 0.0 then - Some (sqrt x) - else - None;; - - flatMap (Some 4.0) f = Some 2.0;; - flatMap (Some (-4.0)) f = None;; - flatMap None f = None;; -``` -``` -val getWithDefault : 'a option -> 'a -> 'a -``` -`getWithDefault optionalValue default` - -If `optionalValue` is `Some value`, returns `value`, otherwise `default` - -```ocaml - getWithDefault (Some 1812) 1066 = 1812;; - getWithDefault None 1066 = 1066;; -``` -``` -val orElse : 'a option -> 'a option -> 'a option -``` -`orElse optionalValue otherOptional` - -If `optionalValue` is `Some value`, returns `Some value`, otherwise `otherOptional` - -```ocaml - orElse (Some 1812) (Some 1066) = Some 1812;; - orElse None (Some 1066) = Some 1066;; - orElse None None = None;; -``` -``` -val isSome : 'a option -> bool -``` -Returns `true` if the argument is `Some value`, `false` otherwise - -``` -val isNone : 'a option -> bool -``` -Returns `true` if the argument is `None`, `false` otherwise - -``` -val eqU : 'a option -> 'b option -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -Uncurried version of `eq` - -``` -val eq : 'a option -> 'b option -> ('a -> 'b -> bool) -> bool -``` -`eq optValue1 optvalue2 predicate` - -Evaluates two optional values for equality with respect to a predicate function. - -If both `optValue1` and `optValue2` are `None`, returns `true`. - -If one of the arguments is `Some value` and the other is `None`, returns `false` - -If arguments are `Some value1` and `Some value2`, returns the result of `predicate value1 value2`; the `predicate` function must return a `bool` - -```ocaml - let clockEqual = (fun a b -> a mod 12 = b mod 12);; - eq (Some 3) (Some 15) clockEqual = true;; - eq (Some 3) None clockEqual = false;; - eq None (Some 3) clockEqual = false;; - eq None None clockEqual = true;; -``` -``` -val cmpU : 'a option -> 'b option -> ('a -> 'b -> int) Js.Fn.arity2 -> int -``` -Uncurried version of `cmp` - -``` -val cmp : 'a option -> 'b option -> ('a -> 'b -> int) -> int -``` -`cmp optValue1 optvalue2 comparisonFcn` - -Compares two optional values with respect to a comparison function - -If both `optValue1` and `optValue2` are `None`, returns 0. - -If the first argument is `Some value1` and the second is `None`, returns 1 (something is greater than nothing) - -If the first argument is `None` and the second is `Some value2`, returns \-1 (nothing is less than something) - -If the arguments are `Some value1` and `Some value2`, returns the result of `comparisonFcn value1 value2`; `comparisonFcn` takes two arguments and returns \-1 if the first argument is less than the second, 0 if the arguments are equal, and 1 if the first argument is greater than the second. - -```ocaml - let clockCompare = fun a b -> compare (a mod 12) (b mod 12);; - cmp (Some 3) (Some 15) clockCompare = 0;; - cmp (Some 3) (Some 14) clockCompare = 1;; - cmp (Some 2) (Some 15) clockCompare = -1;; - cmp None (Some 15) clockCompare = -1;; - cmp (Some 14) None clockCompare = 1;; - cmp None None clockCompare = 0;; -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Range.md b/docs/api/re/melange/Belt-Range.md deleted file mode 100644 index fabb4625e..000000000 --- a/docs/api/re/melange/Belt-Range.md +++ /dev/null @@ -1,62 +0,0 @@ - -# Module `Belt.Range` - -[`Belt.Range`](#) - -Utilities for a closed range `(from, start)` - -A small module to provide a inclusive range operations `[start, finsish]`, it use a for-loop internally instead of creating an array - -``` -val forEachU : int -> int -> (int -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : int -> int -> (int -> unit) -> unit -``` -`forEach start finish action` - -equivalent to `Belt.Array.(forEach (range start finish) action)` - -``` -val everyU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : int -> int -> (int -> bool) -> bool -``` -`every start finish p` - -equivalent to `Belt.Array.(every (range start finish) p )` - -``` -val everyByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val everyBy : int -> int -> step:int -> (int -> bool) -> bool -``` -`everyBy start finish ~step p` - -**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) - -equivalent to `Belt.Array.(every (rangeBy start finish ~step) p)` - -``` -val someU : int -> int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : int -> int -> (int -> bool) -> bool -``` -`some start finish p` - -equivalent to `Belt.Array.(some (range start finish) p)` - -``` -val someByU : int -> int -> step:int -> (int -> bool) Js.Fn.arity1 -> bool -``` -``` -val someBy : int -> int -> step:int -> (int -> bool) -> bool -``` -`someBy start finish ~step p` - -**See** [`Belt.Array.rangeBy`](./Belt-Array.md#val-rangeBy) - -equivalent to `Belt.Array.(some (rangeBy start finish ~step) p)` diff --git a/docs/api/re/melange/Belt-Result.md b/docs/api/re/melange/Belt-Result.md deleted file mode 100644 index 093023ba0..000000000 --- a/docs/api/re/melange/Belt-Result.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Belt.Result` - -[`Belt.Result`](#) - -Utilities for result data type. - -`Belt.Result` is a data type with two variants: `Ok` and `Error`. Each of these variants can contain data, and those two pieces of data need not have the same data type. `Belt.Result` is useful when you need to not only determine whether some data is valid or not (use `Belt.Option` for that), but also keep information about the invalid data. - -In the examples, we presume the existence of two variables: - -```ocaml -let good = Ok 42 -let bad = Error "Invalid data" -``` -``` -type ('a, 'b) t = ('a, 'b) result = -``` -``` -| Ok of 'a -``` -``` -| Error of 'b -``` -``` - -``` -``` -val getExn : ('a, 'b) t -> 'a -``` -`getExn res` - -when `res` is `Ok n`, returns `n` when `res` is `Error m`, **raise** an exception - -```ocaml - getExn good = 42;; - getExn bad;; (* raises exception *) -``` -``` -val mapWithDefaultU : ('a, 'c) t -> 'b -> ('a -> 'b) Js.Fn.arity1 -> 'b -``` -``` -val mapWithDefault : ('a, 'c) t -> 'b -> ('a -> 'b) -> 'b -``` -`mapWithDefault res default f` - -When `res` is `Ok n`, returns `f n`, otherwise `default`. - -```ocaml - mapWithDefault good 0 (fun x -> x / 2) = 21 - mapWithDefault bad 0 (fun x -> x / 2) = 0 -``` -``` -val mapU : ('a, 'c) t -> ('a -> 'b) Js.Fn.arity1 -> ('b, 'c) t -``` -``` -val map : ('a, 'c) t -> ('a -> 'b) -> ('b, 'c) t -``` -`map res f` - -When `res` is `Ok n`, returns `Ok (f n)`. Otherwise returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns an ordinary value. - -```ocaml - let f x = sqrt (float_of_int x) - map (Ok 64) f = Ok 8.0 - map (Error "Invalid data") f = Error "Invalid data" -``` -``` -val flatMapU : ('a, 'c) t -> ('a -> ('b, 'c) t) Js.Fn.arity1 -> ('b, 'c) t -``` -``` -val flatMap : ('a, 'c) t -> ('a -> ('b, 'c) t) -> ('b, 'c) t -``` -`flatMap res f` - -When `res` is `Ok n`, returns `f n`. Otherwise, returns `res` unchanged. Function `f` takes a value of the same type as `n` and returns a `Belt.Result`. - -```ocaml -let recip x = - if x != 0.0 - then - Ok (1.0 /. x) - else - Error "Divide by zero" - - flatMap (Ok 2.0) recip = Ok 0.5 - flatMap (Ok 0.0) recip = Error "Divide by zero" - flatMap (Error "Already bad") recip = Error "Already bad" -``` -``` -val getWithDefault : ('a, 'b) t -> 'a -> 'a -``` -`getWithDefault res defaultValue` - -if `res` is `Ok n`, returns `n`, otherwise `default` - -```ocaml - getWithDefault (Ok 42) 0 = 42 - getWithDefault (Error "Invalid Data") = 0 -``` -``` -val isOk : ('a, 'b) t -> bool -``` -`isOk res` - -Returns `true` if `res` is of the form `Ok n`, `false` if it is the `Error e` variant. - -``` -val isError : ('a, 'b) t -> bool -``` -`isError res` - -Returns `true` if `res` is of the form `Error e`, `false` if it is the `Ok n` variant. - -``` -val eqU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) Js.Fn.arity2 -> bool -``` -``` -val eq : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> bool) -> bool -``` -`eq res1 res2 f` - -Determine if two `Belt.Result` variables are equal with respect to an equality function. If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If one of `res1` and `res2` are of the form `Error e`, return false If both `res1` and `res2` are of the form `Error e`, return true - -```ocaml - let good1 = Ok 42 - let good2 = Ok 32 - let bad1 = Error "invalid" - let bad2 = Error "really invalid" - - let mod10equal a b = - a mod 10 == b mod 10 - - eq good1 good2 mod10equal = true - eq good1 bad1 mod10equal = false - eq bad2 good2 mod10equal = false - eq bad1 bad2 mod10equal = true -``` -``` -val cmpU : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) Js.Fn.arity2 -> int -``` -``` -val cmp : ('a, 'c) t -> ('b, 'd) t -> ('a -> 'b -> int) -> int -``` -`cmp res1 res2 f` - -Compare two `Belt.Result` variables with respect to a comparison function. The comparison function returns \-1 if the first variable is "less than" the second, 0 if the two variables are equal, and 1 if the first is "greater than" the second. - -If `res1` and `res2` are of the form `Ok n` and `Ok m`, return the result of `f n m`. If `res1` is of the form `Error e` and `res2` of the form `Ok n`, return \-1 (nothing is less than something) If `res1` is of the form `Ok n` and `res2` of the form `Error e`, return 1 (something is greater than nothing) If both `res1` and `res2` are of the form `Error e`, return 0 (equal) - -```ocaml - let good1 = Ok 59 - let good2 = Ok 37 - let bad1 = Error "invalid" - let bad2 = Error "really invalid" - - let mod10cmp a b = - Pervasives.compare (a mod 10) (b mod 10) - - cmp (Ok 39) (Ok 57) mod10cmp = 1 - cmp (Ok 57) (Ok 39) mod10cmp = -1 - cmp (Ok 39) (Error "y") mod10cmp = 1 - cmp (Error "x") (Ok 57) mod10cmp = -1 - cmp (Error "x") (Error "y") mod10cmp = 0 -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt-Set-Dict.md b/docs/api/re/melange/Belt-Set-Dict.md deleted file mode 100644 index 249bfc951..000000000 --- a/docs/api/re/melange/Belt-Set-Dict.md +++ /dev/null @@ -1,197 +0,0 @@ - -# Module `Set.Dict` - -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -``` -type ('value, 'identity) t -``` -``` -type ('value, 'id) cmp -``` -``` -val empty : ('value, 'id) t -``` -``` -val fromArray : 'value array -> cmp:('value, 'id) cmp -> ('value, 'id) t -``` -``` -val fromSortedArrayUnsafe : 'value array -> ('value, 'id) t -``` -``` -val isEmpty : (_, _) t -> bool -``` -``` -val has : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> bool -``` -``` -val add : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> ('value, 'id) t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -``` -val mergeMany : - ('value, 'id) t -> - 'value array -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val remove : - ('value, 'id) t -> - 'value -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -``` -val removeMany : - ('value, 'id) t -> - 'value array -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val union : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val intersect : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val diff : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - ('value, 'id) t -``` -``` -val subset : - ('value, 'id) t -> - ('value, 'id) t -> - cmp:('value, 'id) cmp -> - bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val cmp : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val eq : ('value, 'id) t -> ('value, 'id) t -> cmp:('value, 'id) cmp -> bool -``` -`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('value, 'id) t -> ('value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -``` -val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : ('value, 'id) t -> ('value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : ('value, 'id) t -> ('value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t -``` -``` -val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t -``` -`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : - ('value, 'id) t -> - ('value -> bool) Js.Fn.arity1 -> - ('value, 'id) t * ('value, 'id) t -``` -``` -val partition : - ('value, 'id) t -> - ('value -> bool) -> - ('value, 'id) t * ('value, 'id) t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : ('value, 'id) t -> int -``` -``` -val toList : ('value, 'id) t -> 'value list -``` -In increasing order - -``` -val toArray : ('value, 'id) t -> 'value array -``` -``` -val minimum : ('value, 'id) t -> 'value option -``` -``` -val minUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val maximum : ('value, 'id) t -> 'value option -``` -``` -val maxUndefined : ('value, 'id) t -> 'value Js.undefined -``` -``` -val get : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value option -``` -``` -val getUndefined : - ('value, 'id) t -> - 'value -> - cmp:('value, 'id) cmp -> - 'value Js.undefined -``` -``` -val getExn : ('value, 'id) t -> 'value -> cmp:('value, 'id) cmp -> 'value -``` -``` -val split : - ('value, 'id) t -> - 'value -> - cmp:('value, 'id) cmp -> - (('value, 'id) t * ('value, 'id) t) * bool -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - -``` -val checkInvariantInternal : (_, _) t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-Set-Int.md b/docs/api/re/melange/Belt-Set-Int.md deleted file mode 100644 index 697d28cf4..000000000 --- a/docs/api/re/melange/Belt-Set-Int.md +++ /dev/null @@ -1,163 +0,0 @@ - -# Module `Set.Int` - -Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.Set`](./Belt-Set.md) - -``` -type value = int -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -``` -val mergeMany : t -> value array -> t -``` -``` -val remove : t -> value -> t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -``` -val removeMany : t -> value array -> t -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val cmp : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val eq : t -> t -> bool -``` -`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order - -``` -val toArray : t -> value array -``` -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-Set-String.md b/docs/api/re/melange/Belt-Set-String.md deleted file mode 100644 index cd17e0b37..000000000 --- a/docs/api/re/melange/Belt-Set-String.md +++ /dev/null @@ -1,163 +0,0 @@ - -# Module `Set.String` - -Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -This module is [`Belt.Set`](./Belt-Set.md) specialized with value type to be a primitive type. It is more efficient in general, the API is the same with [`Belt.Set`](./Belt-Set.md) except its value type is fixed, and identity is not needed(using the built-in one) - -**See** [`Belt.Set`](./Belt-Set.md) - -``` -type value = string -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -``` -val fromArray : value array -> t -``` -``` -val fromSortedArrayUnsafe : value array -> t -``` -``` -val isEmpty : t -> bool -``` -``` -val has : t -> value -> bool -``` -``` -val add : t -> value -> t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -``` -val mergeMany : t -> value array -> t -``` -``` -val remove : t -> value -> t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -``` -val removeMany : t -> value array -> t -``` -``` -val union : t -> t -> t -``` -``` -val intersect : t -> t -> t -``` -``` -val diff : t -> t -> t -``` -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val cmp : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val eq : t -> t -> bool -``` -`eq s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val forEachU : t -> (value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : t -> (value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -``` -val reduceU : t -> 'a -> ('a -> value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : t -> 'a -> ('a -> value -> 'a) -> 'a -``` -Iterate in increasing order. - -``` -val everyU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : t -> (value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : t -> (value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : t -> (value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. Oder unspecified. - -``` -val keepU : t -> (value -> bool) Js.Fn.arity1 -> t -``` -``` -val keep : t -> (value -> bool) -> t -``` -`keep p s` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : t -> (value -> bool) Js.Fn.arity1 -> t * t -``` -``` -val partition : t -> (value -> bool) -> t * t -``` -`partition p s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : t -> int -``` -``` -val toList : t -> value list -``` -In increasing order - -``` -val toArray : t -> value array -``` -``` -val minimum : t -> value option -``` -``` -val minUndefined : t -> value Js.undefined -``` -``` -val maximum : t -> value option -``` -``` -val maxUndefined : t -> value Js.undefined -``` -``` -val get : t -> value -> value option -``` -``` -val getUndefined : t -> value -> value Js.undefined -``` -``` -val getExn : t -> value -> value -``` -``` -val split : t -> value -> (t * t) * bool -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - -``` -val checkInvariantInternal : t -> unit -``` -**raise** when invariant is not held diff --git a/docs/api/re/melange/Belt-Set.md b/docs/api/re/melange/Belt-Set.md deleted file mode 100644 index d923eb6f2..000000000 --- a/docs/api/re/melange/Belt-Set.md +++ /dev/null @@ -1,377 +0,0 @@ - -# Module `Belt.Set` - -[`Belt.Set`](#) - -The top level provides generic **immutable** set operations. - -It also has three specialized inner modules [`Belt.Set.Int`](./Belt-Set-Int.md), [`Belt.Set.String`](./Belt-Set-String.md) and - -[`Belt.Set.Dict`](./Belt-Set-Dict.md): This module separates data from function which is more verbose but slightly more efficient - -A *immutable* sorted set module which allows customize *compare* behavior. - -The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For more info on this module's usage of identity, \`make\` and others, please see the top level documentation of Belt, **A special encoding for collection safety**. - -Example usage: - -```ocaml - module PairComparator = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c - end) - - let mySet = Belt.Set.make ~id:(module PairComparator) - let mySet2 = Belt.Set.add mySet (1, 2) -``` -The API documentation below will assume a predeclared comparator module for integers, IntCmp - -``` -module Int : sig ... end -``` -Specalized when value type is `int`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module String : sig ... end -``` -Specalized when value type is `string`, more efficient than the generic type, its compare behavior is fixed using the built-in comparison - -``` -module Dict : sig ... end -``` -This module seprate identity from data, it is a bit more verboe but slightly more efficient due to the fact that there is no need to pack identity and data back after each operation - -``` -type ('value, 'identity) t -``` -`('value, 'identity) t` - -`'value` is the element type - -`'identity` the identity of the collection - -``` -type ('value, 'id) id = - (module Belt__.Belt_Id.Comparable - with type identity = 'id - and type t = 'value) -``` -The identity needed for making a set from scratch - -``` -val make : id:('value, 'id) id -> ('value, 'id) t -``` -`make ~id` creates a new set by taking in the comparator - -```ocaml - let s = make ~id:(module IntCmp) -``` -``` -val fromArray : 'value array -> id:('value, 'id) id -> ('value, 'id) t -``` -`fromArray xs ~id` - -```ocaml - toArray (fromArray [1;3;2;4] (module IntCmp)) = [1;2;3;4] -``` -``` -val fromSortedArrayUnsafe : - 'value array -> - id:('value, 'id) id -> - ('value, 'id) t -``` -`fromSortedArrayUnsafe xs ~id` - -The same as [`fromArray`](./#val-fromArray) except it is after assuming the input array `x` is already sorted - -**Unsafe** - -``` -val isEmpty : (_, _) t -> bool -``` -```ocaml - isEmpty (fromArray [||] ~id:(module IntCmp)) = true;; - isEmpty (fromArray [|1|] ~id:(module IntCmp)) = true;; -``` -``` -val has : ('value, 'id) t -> 'value -> bool -``` -```ocaml - let v = fromArray [|1;4;2;5|] ~id:(module IntCmp);; - has v 3 = false;; - has v 1 = true;; -``` -``` -val add : ('value, 'id) t -> 'value -> ('value, 'id) t -``` -`add s x` If `x` was already in `s`, `s` is returned unchanged. - -```ocaml - let s0 = make ~id:(module IntCmp);; - let s1 = add s0 1 ;; - let s2 = add s1 2;; - let s3 = add s2 2;; - toArray s0 = [||];; - toArray s1 = [|1|];; - toArray s2 = [|1;2|];; - toArray s3 = [|1;2|];; - s2 == s3;; -``` -``` -val mergeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t -``` -`mergeMany s xs` - -Adding each of `xs` to `s`, note unlike [`add`](./#val-add), the reference of return value might be changed even if all values in `xs` exist `s` - -``` -val remove : ('value, 'id) t -> 'value -> ('value, 'id) t -``` -`remove m x` If `x` was not in `m`, `m` is returned reference unchanged. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|2;3;1;4;5|];; - let s1 = remove s0 1 ;; - let s2 = remove s1 3 ;; - let s3 = remove s2 3 ;; - - toArray s1 = [|2;3;4;5|];; - toArray s2 = [|2;4;5|];; - s2 == s3;; -``` -``` -val removeMany : ('value, 'id) t -> 'value array -> ('value, 'id) t -``` -`removeMany s xs` - -Removing each of `xs` to `s`, note unlike [`remove`](./#val-remove), the reference of return value might be changed even if none in `xs` exists `s` - -``` -val union : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -`union s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - toArray (union s0 s1) = [|1;2;3;4;5;6|] -``` -``` -val intersect : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -`intersect s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - toArray (intersect s0 s1) = [|2;3;5|] -``` -``` -val diff : ('value, 'id) t -> ('value, 'id) t -> ('value, 'id) t -``` -`diff s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - toArray (diff s0 s1) = [|6|];; - toArray (diff s1 s0) = [|1;4|];; -``` -``` -val subset : ('value, 'id) t -> ('value, 'id) t -> bool -``` -`subset s0 s1` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let s1 = fromArray ~id:(module IntCmp) [|5;2;3;1;5;4;|];; - let s2 = intersect s0 s1;; - subset s2 s0 = true;; - subset s2 s1 = true;; - subset s1 s0 = false;; -``` -``` -val cmp : ('value, 'id) t -> ('value, 'id) t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. It compare `size` first and then iterate over each element following the order of elements - -``` -val eq : ('value, 'id) t -> ('value, 'id) t -> bool -``` -`eq s0 s1` - -returns true if toArray s0 = toArray s1 -``` -val forEachU : ('value, 'id) t -> ('value -> unit) Js.Fn.arity1 -> unit -``` -``` -val forEach : ('value, 'id) t -> ('value -> unit) -> unit -``` -`forEach s f` applies `f` in turn to all elements of `s`. In increasing order - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - let acc = ref [] ;; - forEach s0 (fun x -> acc := x !acc);; - !acc = [6;5;3;2];; -``` -``` -val reduceU : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) Js.Fn.arity2 -> 'a -``` -``` -val reduce : ('value, 'id) t -> 'a -> ('a -> 'value -> 'a) -> 'a -``` -In increasing order. - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - reduce s0 [] Belt.List.add = [6;5;3;2];; -``` -``` -val everyU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val every : ('value, 'id) t -> ('value -> bool) -> bool -``` -`every p s` checks if all elements of the set satisfy the predicate `p`. Order unspecified. - -``` -val someU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> bool -``` -``` -val some : ('value, 'id) t -> ('value -> bool) -> bool -``` -`some p s` checks if at least one element of the set satisfies the predicate `p`. - -``` -val keepU : ('value, 'id) t -> ('value -> bool) Js.Fn.arity1 -> ('value, 'id) t -``` -``` -val keep : ('value, 'id) t -> ('value -> bool) -> ('value, 'id) t -``` -`keep m p` returns the set of all elements in `s` that satisfy predicate `p`. - -``` -val partitionU : - ('value, 'id) t -> - ('value -> bool) Js.Fn.arity1 -> - ('value, 'id) t * ('value, 'id) t -``` -``` -val partition : - ('value, 'id) t -> - ('value -> bool) -> - ('value, 'id) t * ('value, 'id) t -``` -`partition m p` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `p`, and `s2` is the set of all the elements of `s` that do not satisfy `p`. - -``` -val size : ('value, 'id) t -> int -``` -`size s` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - size s0 = 4;; -``` -``` -val toArray : ('value, 'id) t -> 'value array -``` -`toArray s0` - -```ocaml - let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; - toArray s0 = [|2;3;5;6|];; -``` -``` -val toList : ('value, 'id) t -> 'value list -``` -In increasing order - -**See** [`toArray`](./#val-toArray) - -``` -val minimum : ('value, 'id) t -> 'value option -``` -`minimum s0` - -returns the minimum element of the collection, None if it is empty -``` -val minUndefined : ('value, 'id) t -> 'value Js.undefined -``` -`minUndefined s0` - -returns the minimum element of the collection, undefined if it is empty -``` -val maximum : ('value, 'id) t -> 'value option -``` -`maximum s0` - -returns the maximum element of the collection, None if it is empty -``` -val maxUndefined : ('value, 'id) t -> 'value Js.undefined -``` -`maxUndefined s0` - -returns the maximum element of the collection, undefined if it is empty -``` -val get : ('value, 'id) t -> 'value -> 'value option -``` -`get s0 k` - -returns the reference of the value k' which is equivalent to k using the comparator specifiecd by this collection, None if it does not exist -``` -val getUndefined : ('value, 'id) t -> 'value -> 'value Js.undefined -``` -**See** [`get`](./#val-get) - -``` -val getExn : ('value, 'id) t -> 'value -> 'value -``` -**See** [`get`](./#val-get) - -**raise** if not exist - -``` -val split : - ('value, 'id) t -> - 'value -> - (('value, 'id) t * ('value, 'id) t) * bool -``` -`split set ele` - -returns a tuple ((smaller, larger), present), present is true when ele exist in set -Below are operations only when better performance needed, it is still safe API but more verbose. More API will be exposed by needs - -``` -val getData : ('value, 'id) t -> ('value, 'id) Belt__.Belt_SetDict.t -``` -`getData s0` - -**Advanced usage only** - -returns the raw data (detached from comparator), but its type is still manifested, so that user can pass identity directly without boxing -``` -val getId : ('value, 'id) t -> ('value, 'id) id -``` -`getId s0` - -**Advanced usage only** - -returns the identity of s0 -``` -val packIdData : - id:('value, 'id) id -> - data:('value, 'id) Belt__.Belt_SetDict.t -> - ('value, 'id) t -``` -`packIdData ~id ~data` - -**Advanced usage only** - -returns the packed collection \ No newline at end of file diff --git a/docs/api/re/melange/Belt-SortArray-Int.md b/docs/api/re/melange/Belt-SortArray-Int.md deleted file mode 100644 index 44bd7b00f..000000000 --- a/docs/api/re/melange/Belt-SortArray-Int.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `SortArray.Int` - -Specalized when key type is `int`, more efficient than the generic type - -This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined - -``` -type element = int -``` -``` -val strictlySortedLength : element array -> int -``` -The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed - -returns \+n means increasing order -n means negative order -``` -val isSorted : element array -> bool -``` -`sorted xs` return true if `xs` is in non strict increasing order - -``` -val stableSortInPlace : element array -> unit -``` -The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed - -``` -val stableSort : element array -> element array -``` -The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed - -``` -val binarySearch : element array -> element -> int -``` -If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. - -If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) - -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/re/melange/Belt-SortArray-String.md b/docs/api/re/melange/Belt-SortArray-String.md deleted file mode 100644 index 842fd2dd0..000000000 --- a/docs/api/re/melange/Belt-SortArray-String.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `SortArray.String` - -Specalized when key type is `string`, more efficient than the generic type - -This is a specialized module for [`Belt.SortArray`](./Belt-SortArray.md), the docs in that module also applies here, except the comparator is fixed and inlined - -``` -type element = string -``` -``` -val strictlySortedLength : element array -> int -``` -The same as [`Belt.SortArray.strictlySortedLength`](./Belt-SortArray.md#val-strictlySortedLength) except the comparator is fixed - -returns \+n means increasing order -n means negative order -``` -val isSorted : element array -> bool -``` -`sorted xs` return true if `xs` is in non strict increasing order - -``` -val stableSortInPlace : element array -> unit -``` -The same as [`Belt.SortArray.stableSortInPlaceBy`](./Belt-SortArray.md#val-stableSortInPlaceBy) except the comparator is fixed - -``` -val stableSort : element array -> element array -``` -The same as [`Belt.SortArray.stableSortBy`](./Belt-SortArray.md#val-stableSortBy) except the comparator is fixed - -``` -val binarySearch : element array -> element -> int -``` -If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. - -If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) - -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` diff --git a/docs/api/re/melange/Belt-SortArray.md b/docs/api/re/melange/Belt-SortArray.md deleted file mode 100644 index 67893ed3b..000000000 --- a/docs/api/re/melange/Belt-SortArray.md +++ /dev/null @@ -1,81 +0,0 @@ - -# Module `Belt.SortArray` - -[`Belt.SortArray`](#) - -The top level provides some generic sort related utilities. - -It also has two specialized inner modules [`Belt.SortArray.Int`](./Belt-SortArray-Int.md) and [`Belt.SortArray.String`](./Belt-SortArray-String.md) - -A module for Array sort relevant utiliites - -``` -module Int : sig ... end -``` -Specalized when key type is `int`, more efficient than the generic type - -``` -module String : sig ... end -``` -Specalized when key type is `string`, more efficient than the generic type - -``` -val strictlySortedLengthU : 'a array -> ('a -> 'a -> bool) Js.Fn.arity2 -> int -``` -``` -val strictlySortedLength : 'a array -> ('a -> 'a -> bool) -> int -``` -`strictlySortedLenght xs cmp` return `+n` means increasing order `-n` means negative order - -```ocaml - strictlySortedLength [|1;2;3;4;3|] (fun x y -> x < y) = 4;; - strictlySortedLength [||] (fun x y -> x < y) = 0;; - strictlySortedLength [|1|] (fun x y -> x < y) = 1;; - strictlySortedLength [|4;3;2;1|] (fun x y -> x < y) = -4;; -``` -``` -val isSortedU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> bool -``` -``` -val isSorted : 'a array -> ('a -> 'a -> int) -> bool -``` -`isSorted arr cmp` - -returns true if array is increasingly sorted (equal is okay ) isSorted \[\|1;1;2;3;4\|\] (fun x y -\> compare x y) = true -``` -val stableSortInPlaceByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> unit -``` -``` -val stableSortInPlaceBy : 'a array -> ('a -> 'a -> int) -> unit -``` -`stableSortBy xs cmp` - -Sort xs in place using comparator `cmp`, the stable means if the elements are equal, their order will be preserved - -``` -val stableSortByU : 'a array -> ('a -> 'a -> int) Js.Fn.arity2 -> 'a array -``` -``` -val stableSortBy : 'a array -> ('a -> 'a -> int) -> 'a array -``` -`stableSort xs cmp` - -returns a fresh array -The same as [`stableSortInPlaceBy`](./#val-stableSortInPlaceBy) except that `xs` is not modified - -``` -val binarySearchByU : 'a array -> 'a -> ('a -> 'a -> int) Js.Fn.arity2 -> int -``` -``` -val binarySearchBy : 'a array -> 'a -> ('a -> 'a -> int) -> int -``` -If value is not found and value is less than one or more elements in array, the negative number returned is the bitwise complement of the index of the first element that is larger than value. - -If value is not found and value is greater than all elements in array, the negative number returned is the bitwise complement of (the index of the last element plus 1\) - -for example, if `key` is smaller than all elements return `-1` since `lnot (-1) = 0` if `key` is larger than all elements return `- (len + 1)` since `lnot (-(len+1)) = len` - -```ocaml - binarySearchBy [|1;2;3;4;33;35;36|] 33 = 4;; - lnot (binarySearchBy [|1;3;5;7|] 4) = 2;; -``` \ No newline at end of file diff --git a/docs/api/re/melange/Belt.md b/docs/api/re/melange/Belt.md deleted file mode 100644 index 59effce75..000000000 --- a/docs/api/re/melange/Belt.md +++ /dev/null @@ -1,168 +0,0 @@ - -# Module `Belt` - -A stdlib shipped with Melange - -This stdlib is still in *beta* but we encourage you to try it out and give us feedback. - -**Motivation** - -The motivation for creating such library is to provide Melange users a better end-to-end user experience, since the original OCaml stdlib was not written with JS in mind. Below is a list of areas this lib aims to improve: - -1. Consistency in name convention: camlCase, and arguments order -2. Exception thrown functions are all suffixed with *Exn*, e.g, *getExn* -3. Better performance and smaller code size running on JS platform -**Name Convention** - -For higher order functions, it will be suffixed **U** if it takes uncurried callback. - -```ocaml - val forEach : 'a t -> ('a -> unit) -> unit - val forEachU : 'a t -> ('a -> unit [\@u]) -> unit -``` -In general, uncurried version will be faster, but it may be less familiar to people who have a background in functional programming. - -**A special encoding for collection safety** - -When we create a collection library for a custom data type we need a way to provide a comparator function. Take *Set* for example, suppose its element type is a pair of ints, it needs a custom *compare* function that takes two tuples and returns their order. The *Set* could not just be typed as ` Set.t (int * int) `, its customized *compare* function needs to manifest itself in the signature, otherwise, if the user creates another customized *compare* function, the two collection could mix which would result in runtime error. - -The original OCaml stdlib solved the problem using *functor* which creates a big closure at runtime and makes dead code elimination much harder. We use a phantom type to solve the problem: - -```ocaml - module Comparable1 = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c - end) - -let mySet1 = Belt.Set.make ~id:(module Comparable1) - -module Comparable2 = Belt.Id.MakeComparable(struct - type t = int * int - let cmp (a0, a1) (b0, b1) = - match Pervasives.compare a0 b0 with - | 0 -> Pervasives.compare a1 b1 - | c -> c -end) - -let mySet2 = Belt.Set.make ~id:(module Comparable2) -``` -Here, the compiler would infer `mySet1` and `mySet2` having different type, so e.g. a \`merge\` operation that tries to merge these two sets will correctly fail. - -```ocaml - val mySet1 : ((int * int), Comparable1.identity) t - val mySet2 : ((int * int), Comparable2.identity) t -``` -`Comparable1.identity` and `Comparable2.identity` are not the same using our encoding scheme. - -**Collection Hierarchy** - -In general, we provide a generic collection module, but also create specialized modules for commonly used data type. Take *Belt.Set* for example, we provide: - -```ocaml - Belt.Set - Belt.Set.Int - Belt.Set.String -``` -The specialized modules *Belt.Set.Int*, *Belt.Set.String* are in general more efficient. - -Currently, both *Belt\_Set* and *Belt.Set* are accessible to users for some technical reasons, we **strongly recommend** users stick to qualified import, *Belt.Set*, we may hide the internal, *i.e*, *Belt\_Set* in the future - -``` -module Id : sig ... end -``` -[`Belt.Id`](./Belt-Id.md) - -``` -module Array : sig ... end -``` -[`Belt.Array`](./Belt-Array.md) - -``` -module SortArray : sig ... end -``` -[`Belt.SortArray`](./Belt-SortArray.md) - -``` -module MutableQueue : sig ... end -``` -[`Belt.MutableQueue`](./Belt-MutableQueue.md) - -``` -module MutableStack : sig ... end -``` -[`Belt.MutableStack`](./Belt-MutableStack.md) - -``` -module List : sig ... end -``` -[`Belt.List`](./Belt-List.md) - -``` -module Range : sig ... end -``` -[`Belt.Range`](./Belt-Range.md) - -``` -module Set : sig ... end -``` -[`Belt.Set`](./Belt-Set.md) - -``` -module Map : sig ... end -``` -[`Belt.Map`](./Belt-Map.md), - -``` -module MutableSet : sig ... end -``` -[`Belt.MutableSet`](./Belt-MutableSet.md) - -``` -module MutableMap : sig ... end -``` -[`Belt.MutableMap`](./Belt-MutableMap.md) - -``` -module HashSet : sig ... end -``` -[`Belt.HashSet`](./Belt-HashSet.md) - -``` -module HashMap : sig ... end -``` -[`Belt.HashMap`](./Belt-HashMap.md) - -``` -module Option : sig ... end -``` -[`Belt.Option`](./Belt-Option.md) - -[`Belt.Result`](./Belt-Result.md) - -Utilities for result data type. - -``` -module Result : sig ... end -``` -[`Belt.Result`](./Belt-Result.md) - -[`Belt.Int`](./Belt-Int.md) - -Utilities for Int. - -``` -module Int : sig ... end -``` -[`Belt.Int`](./Belt-Int.md) Utililites for Int - -[`Belt.Float`](./Belt-Float.md) - -Utilities for Float. - -``` -module Float : sig ... end -``` -[`Belt.Float`](./Belt-Float.md) Utililites for Float diff --git a/docs/api/re/melange/Dom-Storage.md b/docs/api/re/melange/Dom-Storage.md deleted file mode 100644 index 5196172ac..000000000 --- a/docs/api/re/melange/Dom-Storage.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Module `Dom.Storage` - -``` -type t -``` -``` -val getItem : string -> t -> string option -``` -``` -val setItem : string -> string -> t -> unit -``` -``` -val removeItem : string -> t -> unit -``` -``` -val clear : t -> unit -``` -``` -val key : int -> t -> string option -``` -``` -val length : t -> int -``` -``` -val localStorage : t -``` -``` -val sessionStorage : t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Dom.md b/docs/api/re/melange/Dom.md deleted file mode 100644 index 37f92a4ef..000000000 --- a/docs/api/re/melange/Dom.md +++ /dev/null @@ -1,841 +0,0 @@ - -# Module `Dom` - -``` -type _baseClass -``` -``` -type animation -``` -``` -type cssStyleDeclaration -``` -``` -type cssStyleSheet -``` -``` -type 'a eventTarget_like -``` -``` -type eventTarget = _baseClass eventTarget_like -``` -``` -type _messagePort -``` -``` -type messagePort = _messagePort eventTarget_like -``` -``` -type _serviceWorker -``` -``` -type serviceWorker = _serviceWorker eventTarget_like -``` -``` -type _worker -``` -``` -type worker = _worker eventTarget_like -``` -``` -type 'a _workerGlobalScope -``` -``` -type workerGlobalScope = _baseClass _workerGlobalScope eventTarget_like -``` -``` -type _dedicatedWorkerGlobalScope -``` -``` -type dedicatedWorkerGlobalScope = - _dedicatedWorkerGlobalScope _workerGlobalScope eventTarget_like -``` -``` -type _serviceWorkerGlobalScope -``` -``` -type serviceWorkerGlobalScope = - _serviceWorkerGlobalScope _workerGlobalScope eventTarget_like -``` -``` -type _sharedWorkerGlobalScope -``` -``` -type sharedWorkerGlobalScope = - _sharedWorkerGlobalScope _workerGlobalScope eventTarget_like -``` -``` -type 'a _node -``` -``` -type 'a node_like = 'a _node eventTarget_like -``` -``` -type node = _baseClass node_like -``` -``` -type _attr -``` -``` -type attr = _attr node_like -``` -``` -type 'a _characterData -``` -``` -type 'a characterData_like = 'a _characterData node_like -``` -``` -type characterData = _baseClass characterData_like -``` -``` -type _cdataSection -``` -``` -type cdataSection = _cdataSection characterData_like -``` -``` -type _comment -``` -``` -type comment = _comment characterData_like -``` -``` -type 'a _document -``` -``` -type 'a document_like = 'a _document node_like -``` -``` -type document = _baseClass document_like -``` -``` -type _documentFragment -``` -``` -type documentFragment = _documentFragment node_like -``` -``` -type _documentType -``` -``` -type documentType = _documentType node_like -``` -``` -type domImplementation -``` -``` -type 'a _element -``` -``` -type 'a element_like = 'a _element node_like -``` -``` -type element = _baseClass element_like -``` -``` -type htmlCollection -``` -``` -type htmlFormControlsCollection -``` -``` -type htmlOptionsCollection -``` -``` -type intersectionObserver -``` -``` -type intersectionObserverEntry -``` -``` -type mutationObserver -``` -``` -type mutationRecord -``` -``` -type performanceObserver -``` -``` -type performanceObserverEntryList -``` -``` -type reportingObserver -``` -``` -type reportingObserverOptions -``` -``` -type resizeObserver -``` -``` -type resizeObserverEntry -``` -``` -type namedNodeMap -``` -``` -type nodeList -``` -``` -type radioNodeList -``` -``` -type processingInstruction -``` -``` -type _shadowRoot -``` -``` -type shadowRoot = _shadowRoot node_like -``` -``` -type _text -``` -``` -type text = _text characterData_like -``` -``` -type domRect -``` -``` -type dataTransfer -``` -``` -type domStringMap -``` -``` -type history -``` -``` -type _htmlDocument -``` -``` -type htmlDocument = _htmlDocument document_like -``` -``` -type 'a _htmlElement -``` -``` -type 'a htmlElement_like = 'a _htmlElement element_like -``` -``` -type htmlElement = _baseClass htmlElement_like -``` -``` -type _htmlAnchorElement -``` -``` -type htmlAnchorElement = _htmlAnchorElement htmlElement_like -``` -``` -type _htmlAreaElement -``` -``` -type htmlAreaElement = _htmlAreaElement htmlElement_like -``` -``` -type _htmlAudioElement -``` -``` -type htmlAudioElement = _htmlAudioElement htmlElement_like -``` -``` -type _htmlBaseElement -``` -``` -type htmlBaseElement = _htmlBaseElement htmlElement_like -``` -``` -type _htmlBodyElement -``` -``` -type htmlBodyElement = _htmlBodyElement htmlElement_like -``` -``` -type _htmlBrElement -``` -``` -type htmlBrElement = _htmlBrElement htmlElement_like -``` -``` -type _htmlButtonElement -``` -``` -type htmlButtonElement = _htmlButtonElement htmlElement_like -``` -``` -type _htmlCanvasElement -``` -``` -type htmlCanvasElement = _htmlCanvasElement htmlElement_like -``` -``` -type _htmlDataElement -``` -``` -type htmlDataElement = _htmlDataElement htmlElement_like -``` -``` -type _htmlDataListElement -``` -``` -type htmlDataListElement = _htmlDataListElement htmlElement_like -``` -``` -type _htmlDialogElement -``` -``` -type htmlDialogElement = _htmlDialogElement htmlElement_like -``` -``` -type _htmlDivElement -``` -``` -type htmlDivElement = _htmlDivElement htmlElement_like -``` -``` -type _htmlDlistElement -``` -``` -type htmlDlistElement = _htmlDlistElement htmlElement_like -``` -``` -type _htmlEmbedElement -``` -``` -type htmlEmbedElement = _htmlEmbedElement htmlElement_like -``` -``` -type _htmlFieldSetElement -``` -``` -type htmlFieldSetElement = _htmlFieldSetElement htmlElement_like -``` -``` -type _htmlFormElement -``` -``` -type htmlFormElement = _htmlFormElement htmlElement_like -``` -``` -type _htmlHeadElement -``` -``` -type htmlHeadElement = _htmlHeadElement htmlElement_like -``` -``` -type _htmlHeadingElement -``` -``` -type htmlHeadingElement = _htmlHeadingElement htmlElement_like -``` -``` -type _htmlHrElement -``` -``` -type htmlHrElement = _htmlHrElement htmlElement_like -``` -``` -type _htmlHtmlElement -``` -``` -type htmlHtmlElement = _htmlHtmlElement htmlElement_like -``` -``` -type _htmlIframeElement -``` -``` -type htmlIframeElement = _htmlIframeElement htmlElement_like -``` -``` -type _htmlImageElement -``` -``` -type htmlImageElement = _htmlImageElement htmlElement_like -``` -``` -type _htmlInputElement -``` -``` -type htmlInputElement = _htmlInputElement htmlElement_like -``` -``` -type _htmlLabelElement -``` -``` -type htmlLabelElement = _htmlLabelElement htmlElement_like -``` -``` -type _htmlLegendElement -``` -``` -type htmlLegendElement = _htmlLegendElement htmlElement_like -``` -``` -type _htmlLiElement -``` -``` -type htmlLiElement = _htmlLiElement htmlElement_like -``` -``` -type _htmlLinkElement -``` -``` -type htmlLinkElement = _htmlLinkElement htmlElement_like -``` -``` -type _htmlMapElement -``` -``` -type htmlMapElement = _htmlMapElement htmlElement_like -``` -``` -type _htmlMediaElement -``` -``` -type htmlMediaElement = _htmlMediaElement htmlElement_like -``` -``` -type _htmlMenuElement -``` -``` -type htmlMenuElement = _htmlMenuElement htmlElement_like -``` -``` -type _htmlMetaElement -``` -``` -type htmlMetaElement = _htmlMetaElement htmlElement_like -``` -``` -type _htmlMeterElement -``` -``` -type htmlMeterElement = _htmlMeterElement htmlElement_like -``` -``` -type _htmlModElement -``` -``` -type htmlModElement = _htmlModElement htmlElement_like -``` -``` -type _htmlOListElement -``` -``` -type htmlOListElement = _htmlOListElement htmlElement_like -``` -``` -type _htmlObjectElement -``` -``` -type htmlObjectElement = _htmlObjectElement htmlElement_like -``` -``` -type _htmlOptGroupElement -``` -``` -type htmlOptGroupElement = _htmlOptGroupElement htmlElement_like -``` -``` -type _htmlOptionElement -``` -``` -type htmlOptionElement = _htmlOptionElement htmlElement_like -``` -``` -type _htmlOutputElement -``` -``` -type htmlOutputElement = _htmlOutputElement htmlElement_like -``` -``` -type _htmlParagraphElement -``` -``` -type htmlParagraphElement = _htmlParagraphElement htmlElement_like -``` -``` -type _htmlParamElement -``` -``` -type htmlParamElement = _htmlParamElement htmlElement_like -``` -``` -type _htmlPreElement -``` -``` -type htmlPreElement = _htmlPreElement htmlElement_like -``` -``` -type _htmlProgressElement -``` -``` -type htmlProgressElement = _htmlProgressElement htmlElement_like -``` -``` -type _htmlQuoteElement -``` -``` -type htmlQuoteElement = _htmlQuoteElement htmlElement_like -``` -``` -type _htmlScriptElement -``` -``` -type htmlScriptElement = _htmlScriptElement htmlElement_like -``` -``` -type _htmlSelectElement -``` -``` -type htmlSelectElement = _htmlSelectElement htmlElement_like -``` -``` -type _htmlSlotElement -``` -``` -type htmlSlotElement = _htmlSlotElement htmlElement_like -``` -``` -type _htmlSourceElement -``` -``` -type htmlSourceElement = _htmlSourceElement htmlElement_like -``` -``` -type _htmlSpanElement -``` -``` -type htmlSpanElement = _htmlSpanElement htmlElement_like -``` -``` -type _htmlStyleElement -``` -``` -type htmlStyleElement = _htmlStyleElement htmlElement_like -``` -``` -type _htmlTableCaptionElement -``` -``` -type htmlTableCaptionElement = _htmlTableCaptionElement htmlElement_like -``` -``` -type _htmlTableCellElement -``` -``` -type htmlTableCellElement = _htmlTableCellElement htmlElement_like -``` -``` -type _htmlTableColElement -``` -``` -type htmlTableColElement = _htmlTableColElement htmlElement_like -``` -``` -type _htmlTableDataCellElement -``` -``` -type htmlTableDataCellElement = _htmlTableDataCellElement htmlElement_like -``` -``` -type _htmlTableElement -``` -``` -type htmlTableElement = _htmlTableElement htmlElement_like -``` -``` -type _htmlTableHeaderCellElement -``` -``` -type htmlTableHeaderCellElement = _htmlTableHeaderCellElement htmlElement_like -``` -``` -type _htmlTableRowElement -``` -``` -type htmlTableRowElement = _htmlTableRowElement htmlElement_like -``` -``` -type _htmlTableSectionElement -``` -``` -type htmlTableSectionElement = _htmlTableSectionElement htmlElement_like -``` -``` -type _htmlTextAreaElement -``` -``` -type htmlTextAreaElement = _htmlTextAreaElement htmlElement_like -``` -``` -type _htmlTimeElement -``` -``` -type htmlTimeElement = _htmlTimeElement htmlElement_like -``` -``` -type _htmlTitleElement -``` -``` -type htmlTitleElement = _htmlTitleElement htmlElement_like -``` -``` -type _htmlTrackElement -``` -``` -type htmlTrackElement = _htmlTrackElement htmlElement_like -``` -``` -type _htmlUlistElement -``` -``` -type htmlUlistElement = _htmlUlistElement htmlElement_like -``` -``` -type _htmlUnknownElement -``` -``` -type htmlUnknownElement = _htmlUnknownElement htmlElement_like -``` -``` -type _htmlVideoElement -``` -``` -type htmlVideoElement = _htmlVideoElement htmlElement_like -``` -``` -type location -``` -``` -type window -``` -``` -type _xmlDocument -``` -``` -type xmlDocument = _xmlDocument document_like -``` -``` -type 'a event_like -``` -``` -type event = _baseClass event_like -``` -``` -type 'a _uiEvent -``` -``` -type 'a uiEvent_like = 'a _uiEvent event_like -``` -``` -type uiEvent = _baseClass uiEvent_like -``` -``` -type _animationEvent -``` -``` -type animationEvent = _animationEvent event_like -``` -``` -type _beforeUnloadEvent -``` -``` -type beforeUnloadEvent = _beforeUnloadEvent event_like -``` -``` -type _clipboardEvent -``` -``` -type clipboardEvent = _clipboardEvent event_like -``` -``` -type _closeEvent -``` -``` -type closeEvent = _closeEvent event_like -``` -``` -type _compositionEvent -``` -``` -type compositionEvent = _compositionEvent uiEvent_like -``` -``` -type _customEvent -``` -``` -type customEvent = _customEvent event_like -``` -``` -type _dragEvent -``` -``` -type dragEvent = _dragEvent event_like -``` -``` -type _errorEvent -``` -``` -type errorEvent = _errorEvent event_like -``` -``` -type _focusEvent -``` -``` -type focusEvent = _focusEvent uiEvent_like -``` -``` -type _idbVersionChangeEvent -``` -``` -type idbVersionChangeEvent = _idbVersionChangeEvent event_like -``` -``` -type _inputEvent -``` -``` -type inputEvent = _inputEvent uiEvent_like -``` -``` -type _keyboardEvent -``` -``` -type keyboardEvent = _keyboardEvent uiEvent_like -``` -``` -type _messageEvent -``` -``` -type messageEvent = _messageEvent event_like -``` -``` -type 'a _mouseEvent -``` -``` -type 'a mouseEvent_like = 'a _mouseEvent uiEvent_like -``` -``` -type mouseEvent = _baseClass mouseEvent_like -``` -``` -type _pageTransitionEvent -``` -``` -type pageTransitionEvent = _pageTransitionEvent event_like -``` -``` -type _pointerEvent -``` -``` -type pointerEvent = _pointerEvent mouseEvent_like -``` -``` -type _popStateEvent -``` -``` -type popStateEvent = _popStateEvent event_like -``` -``` -type _progressEvent -``` -``` -type progressEvent = _progressEvent event_like -``` -``` -type _relatedEvent -``` -``` -type relatedEvent = _relatedEvent event_like -``` -``` -type _storageEvent -``` -``` -type storageEvent = _storageEvent event_like -``` -``` -type _svgZoomEvent -``` -``` -type svgZoomEvent = _svgZoomEvent event_like -``` -``` -type _timeEvent -``` -``` -type timeEvent = _timeEvent event_like -``` -``` -type _touchEvent -``` -``` -type touchEvent = _touchEvent uiEvent_like -``` -``` -type _trackEvent -``` -``` -type trackEvent = _trackEvent event_like -``` -``` -type _transitionEvent -``` -``` -type transitionEvent = _transitionEvent event_like -``` -``` -type _webGlContextEvent -``` -``` -type webGlContextEvent = _webGlContextEvent event_like -``` -``` -type _wheelEvent -``` -``` -type wheelEvent = _wheelEvent uiEvent_like -``` -``` -type range -``` -``` -type selection -``` -``` -type domTokenList -``` -``` -type domSettableTokenList -``` -``` -type nodeFilter = { -``` -`acceptNode : element -> int;` -``` -} -``` -``` -type nodeIterator -``` -``` -type treeWalker -``` -``` -type svgRect -``` -``` -type svgPoint -``` -``` -type eventPointerId -``` -``` -type messageChannel -``` -``` -module Storage : sig ... end -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Array.md b/docs/api/re/melange/Js-Array.md deleted file mode 100644 index dff910797..000000000 --- a/docs/api/re/melange/Js-Array.md +++ /dev/null @@ -1,179 +0,0 @@ - -# Module `Js.Array` - -Bindings to the functions in `Array.prototype` - -JavaScript Array API - -``` -type 'a t = 'a array -``` -``` -type 'a array_like = 'a Js.array_like -``` -``` -val from : 'a array_like -> 'a array -``` -``` -val fromMap : 'a array_like -> f:('a -> 'b) -> 'b array -``` -``` -val isArray : 'a -> bool -``` -``` -val length : 'a array -> int -``` -Mutating functions - -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> 'a t -> 'a t -``` -``` -val fill : value:'a -> ?start:int -> ?end_:int -> 'a t -> 'a t -``` -``` -val pop : 'a t -> 'a option -``` -https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/push - -``` -val push : value:'a -> 'a t -> int -``` -``` -val pushMany : values:'a array -> 'a t -> int -``` -``` -val reverseInPlace : 'a t -> 'a t -``` -``` -val shift : 'a t -> 'a option -``` -``` -val sortInPlace : 'a t -> 'a t -``` -``` -val sortInPlaceWith : f:('a -> 'a -> int) -> 'a t -> 'a t -``` -``` -val spliceInPlace : start:int -> remove:int -> add:'a array -> 'a t -> 'a t -``` -``` -val removeFromInPlace : start:int -> 'a t -> 'a t -``` -``` -val removeCountInPlace : start:int -> count:int -> 'a t -> 'a t -``` -``` -val unshift : value:'a -> 'a t -> int -``` -``` -val unshiftMany : values:'a array -> 'a t -> int -``` -``` -val concat : other:'a t -> 'a t -> 'a t -``` -``` -val concatMany : arrays:'a t array -> 'a t -> 'a t -``` -``` -val includes : value:'a -> 'a t -> bool -``` -ES2015 - -``` -val join : ?sep:string -> 'a t -> string -``` -Accessor functions - -``` -val indexOf : value:'a -> ?start:int -> 'a t -> int -``` -``` -val lastIndexOf : value:'a -> 'a t -> int -``` -``` -val lastIndexOfFrom : value:'a -> start:int -> 'a t -> int -``` -``` -val copy : 'a t -> 'a t -``` -``` -val slice : ?start:int -> ?end_:int -> 'a t -> 'a t -``` -``` -val toString : 'a t -> string -``` -``` -val toLocaleString : 'a t -> string -``` -Iteration functions - -``` -val entries : 'a t -> (int * 'a) Js.iterator -``` -``` -val every : f:('a -> bool) -> 'a t -> bool -``` -``` -val everyi : f:('a -> int -> bool) -> 'a t -> bool -``` -``` -val filter : f:('a -> bool) -> 'a t -> 'a t -``` -``` -val filteri : f:('a -> int -> bool) -> 'a t -> 'a t -``` -``` -val find : f:('a -> bool) -> 'a t -> 'a option -``` -``` -val findi : f:('a -> int -> bool) -> 'a t -> 'a option -``` -``` -val findIndex : f:('a -> bool) -> 'a t -> int -``` -``` -val findIndexi : f:('a -> int -> bool) -> 'a t -> int -``` -``` -val forEach : f:('a -> unit) -> 'a t -> unit -``` -``` -val forEachi : f:('a -> int -> unit) -> 'a t -> unit -``` -``` -val keys : 'a t -> int Js.iterator -``` -``` -val map : f:('a -> 'b) -> 'a t -> 'b t -``` -``` -val mapi : f:('a -> int -> 'b) -> 'a t -> 'b t -``` -``` -val reduce : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val reducei : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val reduceRight : f:('b -> 'a -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val reduceRighti : f:('b -> 'a -> int -> 'b) -> init:'b -> 'a t -> 'b -``` -``` -val some : f:('a -> bool) -> 'a t -> bool -``` -``` -val somei : f:('a -> int -> bool) -> 'a t -> bool -``` -``` -val values : 'a t -> 'a Js.iterator -``` -``` -val unsafe_get : 'a array -> int -> 'a -``` -``` -val unsafe_set : 'a array -> int -> 'a -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Bigint.md b/docs/api/re/melange/Js-Bigint.md deleted file mode 100644 index d4b488ac6..000000000 --- a/docs/api/re/melange/Js-Bigint.md +++ /dev/null @@ -1,71 +0,0 @@ - -# Module `Js.Bigint` - -Bindings to functions in JavaScript's `BigInt` - -JavaScript BigInt API - -``` -type t = Js.bigint -``` -``` -val make : 'a -> t -``` -`make repr` creates a new BigInt from the representation `repr`. `repr` can be a number, a string, boolean, etc. - -``` -val asIntN : precision:int -> t -> t -``` -`asIntN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as a signed integer. - -``` -val asUintN : precision:int -> t -> t -``` -`asUintN ~precision bigint` truncates the BigInt value of `bigint` to the given number of least significant bits specified by `precision` and returns that value as an unsigned integer. - -``` -type toLocaleStringOptions = { -``` -`style : string;` -`currency : string;` -``` -} -``` -``` -val toLocaleString : - locale:string -> - ?options:toLocaleStringOptions -> - t -> - string -``` -`toLocaleString bigint` returns a string with a language-sensitive representation of this BigInt. - -``` -val toString : t -> string -``` -`toString bigint` returns a string representing the specified BigInt value. - -``` -val neg : t -> t -``` -``` -val add : t -> t -> t -``` -``` -val sub : t -> t -> t -``` -Subtraction. - -``` -val mul : t -> t -> t -``` -Multiplication. - -``` -val div : t -> t -> t -``` -Division. - -``` -val rem : t -> t -> t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Blob.md b/docs/api/re/melange/Js-Blob.md deleted file mode 100644 index 89b228319..000000000 --- a/docs/api/re/melange/Js-Blob.md +++ /dev/null @@ -1,54 +0,0 @@ - -# Module `Js.Blob` - -Bindings to Blob - -``` -type t = Js.blob -``` -``` -type options = { -``` -`type_ : string option;` -A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". - -``endings : [ `transparent | `native ] option;`` -How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the blob without changing them. To convert newlines to the host system's native convention, specify the value native. - -``` -} -``` -``` -val make : string Js.iterator -> ?options:options -> unit -> t -``` -`make (Js.Array.values contents_array)` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. - -``` -val size : t -> float -``` -`size t` returns the size of the Blob in bytes - -``` -val type_ : t -> string -``` -`type_ t` returns the MIME type of the file. - -``` -val arrayBuffer : t -> Js.arrayBuffer Js.promise -``` -`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. - -``` -val bytes : t -> Js.uint8Array Js.promise -``` -`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the blob as an array of bytes. - -``` -val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t -``` -`slice ?start ?end_ ?contentType t` creates and returns a new Blob object which contains data from a subset of the blob on which it's called. - -``` -val text : t -> string Js.promise -``` -`text t` returns a Promise that resolves with a string containing the contents of the blob, interpreted as UTF-8. diff --git a/docs/api/re/melange/Js-Console.md b/docs/api/re/melange/Js-Console.md deleted file mode 100644 index b68a7e2de..000000000 --- a/docs/api/re/melange/Js-Console.md +++ /dev/null @@ -1,72 +0,0 @@ - -# Module `Js.Console` - -``` -val log : 'a -> unit -``` -``` -val log2 : 'a -> 'b -> unit -``` -``` -val log3 : 'a -> 'b -> 'c -> unit -``` -``` -val log4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val logMany : 'a array -> unit -``` -``` -val info : 'a -> unit -``` -``` -val info2 : 'a -> 'b -> unit -``` -``` -val info3 : 'a -> 'b -> 'c -> unit -``` -``` -val info4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val infoMany : 'a array -> unit -``` -``` -val warn : 'a -> unit -``` -``` -val warn2 : 'a -> 'b -> unit -``` -``` -val warn3 : 'a -> 'b -> 'c -> unit -``` -``` -val warn4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val warnMany : 'a array -> unit -``` -``` -val error : 'a -> unit -``` -``` -val error2 : 'a -> 'b -> unit -``` -``` -val error3 : 'a -> 'b -> 'c -> unit -``` -``` -val error4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val errorMany : 'a array -> unit -``` -``` -val trace : unit -> unit -``` -``` -val timeStart : string -> unit -``` -``` -val timeEnd : string -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Date.md b/docs/api/re/melange/Js-Date.md deleted file mode 100644 index 3d66c2b18..000000000 --- a/docs/api/re/melange/Js-Date.md +++ /dev/null @@ -1,319 +0,0 @@ - -# Module `Js.Date` - -Bindings to the functions in JS's `Date.prototype` - -JavaScript Date API - -``` -type t -``` -``` -val valueOf : t -> float -``` -returns the primitive value of this date, equivalent to getTime - -``` -val make : unit -> t -``` -returns a date representing the current time - -``` -val fromFloat : float -> t -``` -``` -val fromString : string -> t -``` -``` -val makeWithYM : year:float -> month:float -> t -``` -``` -val makeWithYMD : year:float -> month:float -> date:float -> t -``` -``` -val makeWithYMDH : year:float -> month:float -> date:float -> hours:float -> t -``` -``` -val makeWithYMDHM : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - t -``` -``` -val makeWithYMDHMS : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - seconds:float -> - t -``` -``` -val utcWithYM : year:float -> month:float -> float -``` -``` -val utcWithYMD : year:float -> month:float -> date:float -> float -``` -``` -val utcWithYMDH : - year:float -> - month:float -> - date:float -> - hours:float -> - float -``` -``` -val utcWithYMDHM : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - float -``` -``` -val utcWithYMDHMS : - year:float -> - month:float -> - date:float -> - hours:float -> - minutes:float -> - seconds:float -> - float -``` -``` -val now : unit -> float -``` -returns the number of milliseconds since Unix epoch - -``` -val parseAsFloat : string -> float -``` -returns NaN if passed invalid date string - -``` -val getDate : t -> float -``` -return the day of the month (1-31) - -``` -val getDay : t -> float -``` -returns the day of the week (0-6) - -``` -val getFullYear : t -> float -``` -``` -val getHours : t -> float -``` -``` -val getMilliseconds : t -> float -``` -``` -val getMinutes : t -> float -``` -``` -val getMonth : t -> float -``` -returns the month (0-11) - -``` -val getSeconds : t -> float -``` -``` -val getTime : t -> float -``` -returns the number of milliseconds since Unix epoch - -``` -val getTimezoneOffset : t -> float -``` -``` -val getUTCDate : t -> float -``` -return the day of the month (1-31) - -``` -val getUTCDay : t -> float -``` -returns the day of the week (0-6) - -``` -val getUTCFullYear : t -> float -``` -``` -val getUTCHours : t -> float -``` -``` -val getUTCMilliseconds : t -> float -``` -``` -val getUTCMinutes : t -> float -``` -``` -val getUTCMonth : t -> float -``` -returns the month (0-11) - -``` -val getUTCSeconds : t -> float -``` -``` -val setDate : date:float -> t -> float -``` -``` -val setFullYear : year:float -> t -> float -``` -``` -val setFullYearM : year:float -> month:float -> t -> float -``` -``` -val setFullYearMD : year:float -> month:float -> date:float -> t -> float -``` -``` -val setHours : hours:float -> t -> float -``` -``` -val setHoursM : hours:float -> minutes:float -> t -> float -``` -``` -val setHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float -``` -``` -val setHoursMSMs : - hours:float -> - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setMilliseconds : milliseconds:float -> t -> float -``` -``` -val setMinutes : minutes:float -> t -> float -``` -``` -val setMinutesS : minutes:float -> seconds:float -> t -> float -``` -``` -val setMinutesSMs : - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setMonth : month:float -> t -> float -``` -``` -val setMonthD : month:float -> date:float -> t -> float -``` -``` -val setSeconds : seconds:float -> t -> float -``` -``` -val setSecondsMs : seconds:float -> milliseconds:float -> t -> float -``` -``` -val setTime : time:float -> t -> float -``` -``` -val setUTCDate : date:float -> t -> float -``` -``` -val setUTCFullYear : year:float -> t -> float -``` -``` -val setUTCFullYearM : year:float -> month:float -> t -> float -``` -``` -val setUTCFullYearMD : year:float -> month:float -> date:float -> t -> float -``` -``` -val setUTCHours : hours:float -> t -> float -``` -``` -val setUTCHoursM : hours:float -> minutes:float -> t -> float -``` -``` -val setUTCHoursMS : hours:float -> minutes:float -> seconds:float -> t -> float -``` -``` -val setUTCHoursMSMs : - hours:float -> - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setUTCMilliseconds : milliseconds:float -> t -> float -``` -``` -val setUTCMinutes : minutes:float -> t -> float -``` -``` -val setUTCMinutesS : minutes:float -> seconds:float -> t -> float -``` -``` -val setUTCMinutesSMs : - minutes:float -> - seconds:float -> - milliseconds:float -> - t -> - float -``` -``` -val setUTCMonth : month:float -> t -> float -``` -``` -val setUTCMonthD : month:float -> date:float -> t -> float -``` -``` -val setUTCSeconds : seconds:float -> t -> float -``` -``` -val setUTCSecondsMs : seconds:float -> milliseconds:float -> t -> float -``` -``` -val setUTCTime : time:float -> t -> float -``` -``` -val toDateString : t -> string -``` -``` -val toISOString : t -> string -``` -``` -val toJSON : t -> string option -``` -``` -val toJSONUnsafe : t -> string -``` -``` -val toLocaleDateString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val toLocaleTimeString : t -> string -``` -``` -val toString : t -> string -``` -``` -val toTimeString : t -> string -``` -``` -val toUTCString : t -> string -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Dict.md b/docs/api/re/melange/Js-Dict.md deleted file mode 100644 index 3a0f74eb6..000000000 --- a/docs/api/re/melange/Js-Dict.md +++ /dev/null @@ -1,74 +0,0 @@ - -# Module `Js.Dict` - -Utility functions to treat a JS object as a dictionary - -``` -type 'a t = 'a Js.dict -``` -Dictionary type (ie an '{ }' JS object). However it is restricted to hold a single type; therefore values must have the same type. - -This Dictionary type is mostly used with the `Js_json.t` type. - -``` -type key = string -``` -Key type - -``` -val get : 'a t -> key -> 'a option -``` -`get dict key` returns `None` if the `key` is not found in the dictionary, `Some value` otherwise - -``` -val unsafeGet : 'a t -> key -> 'a -``` -`unsafeGet dict key` return the value if the `key` exists, otherwise an **undefined** value is returned. Must be used only when the existence of a key is certain. (i.e. when having called `keys` function previously. - -```ocaml -Array.iter (fun key -> Js.log (Js_dict.unsafeGet dic key)) (Js_dict.keys dict) -``` -``` -val set : 'a t -> key -> 'a -> unit -``` -`set dict key value` sets the `key`/`value` in `dict` - -``` -val keys : 'a t -> string array -``` -`keys dict` returns all the keys in the dictionary `dict` - -``` -val empty : unit -> 'a t -``` -`empty ()` returns an empty dictionary - -``` -val unsafeDeleteKey : (string t -> string -> unit) Js.Fn.arity2 -``` -Experimental internal function - -``` -val entries : 'a t -> (key * 'a) array -``` -`entries dict` returns the key value pairs in `dict` (ES2017) - -``` -val values : 'a t -> 'a array -``` -`values dict` returns the values in `dict` (ES2017) - -``` -val fromList : (key * 'a) list -> 'a t -``` -`fromList entries` creates a new dictionary containing each `(key, value)` pair in `entries` - -``` -val fromArray : (key * 'a) array -> 'a t -``` -`fromArray entries` creates a new dictionary containing each `(key, value)` pair in `entries` - -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -`map f dict` maps `dict` to a new dictionary with the same keys, using `f` to map each value diff --git a/docs/api/re/melange/Js-Exn.md b/docs/api/re/melange/Js-Exn.md deleted file mode 100644 index afea42336..000000000 --- a/docs/api/re/melange/Js-Exn.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Js.Exn` - -Utilities for dealing with Js exceptions - -``` -type t -``` -``` -type exn += private -``` -``` -| Error of t -``` -``` - -``` -``` -val asJsExn : exn -> t option -``` -``` -val stack : t -> string option -``` -``` -val message : t -> string option -``` -``` -val name : t -> string option -``` -``` -val fileName : t -> string option -``` -``` -val isCamlExceptionOrOpenVariant : 'a -> bool -``` -internal use only - -``` -val anyToExnInternal : 'a -> exn -``` -`anyToExnInternal obj` will take any value `obj` and wrap it in a Js.Exn.Error if given value is not an exn already. If `obj` is an exn, it will return `obj` without any changes. - -This function is mostly useful for cases where you want to unify a type of a value that potentially is either exn, a JS error, or any other JS value really (e.g. for a value passed to a Promise.catch callback) - -IMPORTANT: This is an internal API and may be changed / removed any time in the future. - -```ocaml - switch (Js.Exn.unsafeAnyToExn("test")) { - | Js.Exn.Error(v) => - switch (Js.Exn.message(v)) { - | Some(str) => Js.log("We won't end up here") - | None => Js.log2("We will land here: ", v) - } - } -``` -``` -val raiseError : string -> 'a -``` -Raise Js exception Error object with stacktrace - -``` -val raiseEvalError : string -> 'a -``` -``` -val raiseRangeError : string -> 'a -``` -``` -val raiseReferenceError : string -> 'a -``` -``` -val raiseSyntaxError : string -> 'a -``` -``` -val raiseTypeError : string -> 'a -``` -``` -val raiseUriError : string -> 'a -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-File.md b/docs/api/re/melange/Js-File.md deleted file mode 100644 index 71a732734..000000000 --- a/docs/api/re/melange/Js-File.md +++ /dev/null @@ -1,72 +0,0 @@ - -# Module `Js.File` - -Bindings to File - -``` -type t = Js.file -``` -``` -type options = { -``` -`type_ : string option;` -A string representing the MIME type of the content that will be put into the file. Defaults to a value of "". - -``endings : [ `transparent | `native ] option;`` -How to interpret newline characters (\\n) within the contents, if the data is text. The default value, transparent, copies newline characters into the file without changing them. To convert newlines to the host system's native convention, specify the value native. - -`lastModified : float option;` -A number representing the number of milliseconds between the Unix time epoch and when the file was last modified. Defaults to a value of Date.now(). - -``` -} -``` -``` -val make : - string Js.iterator -> - filename:string -> - ?options:options -> - unit -> - t -``` -`make contents_array ~filename` creates a new file from an iterable object such as an Array, having ArrayBuffers, TypedArrays, DataViews, Blobs, strings, or a mix of any of such elements, that will be put inside the File. Note that strings here are encoded as UTF-8, unlike the usual JavaScript UTF-16 strings. - -``` -val lastModified : t -> float -``` -`lastModified t` accesses the read-only property of the File interface, which provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. - -``` -val name : t -> string -``` -The `name t` read-only property of the File interface returns the name of the file represented by a File object. For security reasons, the path is excluded from this property. - -``` -val size : t -> float -``` -`size t` returns the size of the File in bytes - -``` -val type_ : t -> string -``` -`type_ t` returns the MIME type of the file. - -``` -val arrayBuffer : t -> Js.arrayBuffer Js.promise -``` -`arrayBuffer t` returns a Promise that resolves with the contents of the blob as binary data contained in a `Js.arrayBuffer`. - -``` -val bytes : t -> Js.uint8Array Js.promise -``` -`bytes t` returns a Promise that resolves with a `Js.uint8Array` containing the contents of the file as an array of bytes. - -``` -val slice : ?start:int -> ?end_:int -> ?contentType:string -> t -> t -``` -`slice ?start ?end_ ?contentType t` creates and returns a new File object which contains data from a subset of the file on which it's called. - -``` -val text : t -> string Js.promise -``` -`text t` returns a Promise that resolves with a string containing the contents of the file, interpreted as UTF-8. diff --git a/docs/api/re/melange/Js-Float.md b/docs/api/re/melange/Js-Float.md deleted file mode 100644 index fa4803615..000000000 --- a/docs/api/re/melange/Js-Float.md +++ /dev/null @@ -1,140 +0,0 @@ - -# Module `Js.Float` - -Bindings to functions in JavaScript's `Number` that deal with floats - -Provides functions for inspecting and manipulating `float`s - -``` -type t = float -``` -``` -val _NaN : t -``` -The special value "Not a Number" - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/NaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN) MDN -``` -val isNaN : t -> bool -``` -Tests if the given value is `_NaN` - -Note that both `_NaN = _NaN` and `_NaN == _NaN` will return `false`. `isNaN` is therefore necessary to test for `_NaN`. - -**Returns** `true` if the given value is `_NaN`, `false` otherwise - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) MDN -``` -val isFinite : t -> bool -``` -Tests if the given value is finite - -**Returns** `true` if the given value is a finite number, `false` otherwise - -```ocaml -(* returns [false] *) -let _ = Js.Float.isFinite infinity - -(* returns [false] *) -let _ = Js.Float.isFinite neg_infinity - -(* returns [false] *) -let _ = Js.Float.isFinite _NaN - -(* returns [true] *) -let _ = Js.Float.isFinite 1234 -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) MDN -``` -val toExponential : ?digits:int -> t -> string -``` -Formats a `float` using exponential (scientific) notation - -**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). - -**Returns** a `string` representing the given value in exponential notation - -The output will be rounded or padded with zeroes if necessary. - -raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) -```ocaml - Js.Float.toExponential 77.1234 = "7.71234e+1" - Js.Float.toExponential 77. = "7.7e+1" - Js.Float.toExponential ~digits:2 77.1234 = "7.71e+1" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN -``` -val toFixed : ?digits:int -> t -> string -``` -Formats a `float` using fixed point notation - -**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). Defaults to `0`. - -**Returns** a `string` representing the given value in fixed-point notation (usually) - -The output will be rounded or padded with zeroes if necessary. - -raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) -```ocaml - Js.Float.toFixed 12345.6789 = "12346" - Js.Float.toFixed 1.2e21 = "1.2e+21" - Js.Float.toFixed ~digits:1 12345.6789 = "12345.7" - Js.Float.toFixed ~digits:2 0. = "0.00" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toFixed](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) MDN -``` -val toPrecision : ?digits:int -> t -> string -``` -Formats a `float` using some fairly arbitrary rules - -**digits** specifies how many digits should appear in total. The value must between 0 and some arbitrary number that's hopefully at least larger than 20 (for Node it's 21. Why? Who knows). - -**Returns** a `string` representing the given value in fixed-point or scientific notation - -The output will be rounded or padded with zeroes if necessary. - -`toPrecision` differs from `toFixed` in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. - -raises `RangeError` if digits is not in the range accepted by this function (what do you mean "vague"?) -```ocaml - Js.Float.toPrecision 12345.6789 = "12345.6789" - Js.Float.toPrecision 1.2e21 = "1.2e+21" - Js.Float.toPrecision ~digits:1 12345.6789 = "1e+4" - Js.Float.toPrecision ~digits:2 0. = "0.0" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN -``` -val toString : ?radix:int -> t -> string -``` -Formats a `float` as a string - -**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). - -**Returns** a `string` representing the given value in fixed-point (usually) - -raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) -```ocaml - Js.Float.toString 12345.6789 = "12345.6789" - Js.Float.toString ~radix:2 6. = "110" - Js.Float.toString ~radix:2 3.14 = "11.001000111101011100001010001111010111000010100011111" - Js.Float.toString ~radix:16 3735928559. = "deadbeef" - Js.Float.toString ~radix:36 123.456 = "3f.gez4w97ry0a18ymf6qadcxr" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN -``` -val fromString : string -> t -``` -Parses the given `string` into a `float` using JavaScript semantics - -**Returns** the number as a `float` if successfully parsed, `_NaN` otherwise. - -```ocaml -Js.Float.fromString "123" = 123. -Js.Float.fromString "12.3" = 12.3 -Js.Float.fromString "" = 0. -Js.Float.fromString "0x11" = 17. -Js.Float.fromString "0b11" = 3. -Js.Float.fromString "0o11" = 9. -Js.Float.fromString "foo" = _NaN -Js.Float.fromString "100a" = _NaN -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-FormData.md b/docs/api/re/melange/Js-FormData.md deleted file mode 100644 index 57c30522d..000000000 --- a/docs/api/re/melange/Js-FormData.md +++ /dev/null @@ -1,90 +0,0 @@ - -# Module `Js.FormData` - -Bindings to FormData - -``` -type t -``` -``` -type entryValue -``` -The values returned by the \`get`,All`\` and iteration functions is either a string or a Blob. Melange uses an abstract type and defers to users of the API to handle it according to their application needs. - -``` -val make : unit -> t -``` -`make ()` creates a new `FormData` object, initially empty. - -``` -val append : - name:string -> - value:[ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> - t -> - unit -``` -`append t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. - -``` -val appendBlob : - name:string -> - value:[ `Blob of Js.blob | `File of Js.file ] -> - ?filename:string -> - t -> - unit -``` -`appendBlob t ~name ~value` appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist. This method differs from `append` in that instances in the Blob hierarchy can pass a third filename argument. - -``` -val delete : name:string -> t -> unit -``` -`delete t ~name` deletes a key and its value(s) from a FormData object. - -``` -val get : name:string -> t -> entryValue option -``` -`get t ~name` returns the first value associated with a given key from within a FormData object. If you expect multiple values and want all of them, use [`getAll`](./#val-getAll) instead. - -``` -val getAll : name:string -> t -> entryValue array -``` -`getAll t ~name` returns all the values associated with a given key from within a FormData object. - -``` -val set : - name:string -> - [ `String of string | `Object of < .. > Js.t | `Dict of _ Js.dict ] -> - t -> - unit -``` -`set t ~name ~value` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. - -``` -val setBlob : - name:string -> - [ `Blob of Js.blob | `File of Js.file ] -> - ?filename:string -> - t -> - unit -``` -`setBlob t ~name ~value ?filename` sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist. This method differs from `set` in that instances in the Blob hierarchy can pass a third filename argument. - -``` -val has : name:string -> t -> bool -``` -`has ~name t` returns whether a FormData object contains a certain key. - -``` -val keys : t -> string Js.iterator -``` -`keys t` returns an iterator which iterates through all keys contained in the FormData. The keys are strings. - -``` -val values : t -> entryValue Js.iterator -``` -`values t` returns an iterator which iterates through all values contained in the FormData. The values are strings or Blob objects. - -``` -val entries : t -> (string * entryValue) Js.iterator -``` -`entries t` returns an iterator which iterates through all key/value pairs contained in the FormData. diff --git a/docs/api/re/melange/Js-Global.md b/docs/api/re/melange/Js-Global.md deleted file mode 100644 index b8e00b08f..000000000 --- a/docs/api/re/melange/Js-Global.md +++ /dev/null @@ -1,150 +0,0 @@ - -# Module `Js.Global` - -Bindings to functions in the JS global namespace - -Contains functions available in the global scope (`window` in a browser context) - -``` -type intervalId -``` -Identify an interval started by [`setInterval`](./#val-setInterval) - -``` -type timeoutId -``` -Identify timeout started by [`setTimeout`](./#val-setTimeout) - -``` -val clearInterval : intervalId -> unit -``` -Clear an interval started by [`setInterval`](./#val-setInterval) - -```ocaml -(* API for a somewhat aggressive snoozing alarm clock *) - -let interval = ref Js.Nullable.null - -let remind () = - Js.log "Wake Up!"; - IO.punchSleepyGuy () - -let snooze mins = - interval := Js.Nullable.return (Js.Global.setInterval remind (mins * 60 * 1000)) - -let cancel () = - Js.Nullable.iter !interval (fun[\@u] intervalId -> Js.Global.clearInterval intervalId) -``` -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval) MDN -``` -val clearTimeout : timeoutId -> unit -``` -Clear a timeout started by [`setTimeout`](./#val-setTimeout) - -```ocaml -(* A simple model of a code monkey's brain *) - -let timer = ref Js.Nullable.null - -let work () = - IO.closeHackerNewsTab () - -let procrastinate mins = - Js.Nullable.iter !timer (fun[\@u] timer -> Js.Global.clearTimeout timer); - timer := Js.Nullable.return (Js.Global.setTimeout work (mins * 60 * 1000)) -``` -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout) MDN -``` -val setInterval : f:(unit -> unit) -> int -> intervalId -``` -*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls - -**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN -```ocaml -(* Will count up and print the count to the console every second *) - -let count = ref 0 - -let tick () = - count := !count + 1; Js.log (string_of_int !count) - -let _ = - Js.Global.setInterval tick 1000 -``` -``` -val setIntervalFloat : f:(unit -> unit) -> float -> intervalId -``` -*Repeatedly* executes a callback with a specified interval (in milliseconds) between calls - -**Return** an [`intervalId`](./#type-intervalId) that can be passed to [`clearInterval`](./#val-clearInterval) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) MDN -```ocaml -(* Will count up and print the count to the console every second *) - -let count = ref 0 - -let tick () = - count := !count + 1; Js.log (string_of_int !count) - -let _ = - Js.Global.setIntervalFloat tick 1000.0 -``` -``` -val setTimeout : f:(unit -> unit) -> int -> timeoutId -``` -Execute a callback after a specified delay (in milliseconds) - -**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN -```ocaml -(* Prints "Timed out!" in the console after one second *) - -let message = "Timed out!" - -let _ = - Js.Global.setTimeout (fun () -> Js.log message) 1000 -``` -``` -val setTimeoutFloat : f:(unit -> unit) -> float -> timeoutId -``` -Execute a callback after a specified delay (in milliseconds) - -**returns** a [`timeoutId`](./#type-timeoutId) that can be passed to [`clearTimeout`](./#val-clearTimeout) to cancel the timeout - -see [https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) MDN -```ocaml -(* Prints "Timed out!" in the console after one second *) - -let message = "Timed out!" - -let _ = - Js.Global.setTimeoutFloat (fun () -> Js.log message) 1000.0 -``` -``` -val encodeURI : string -> string -``` -URL-encodes a string. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI) MDN -``` -val decodeURI : string -> string -``` -Decodes a URL-enmcoded string produced by `encodeURI` - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURI](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI) MDN -``` -val encodeURIComponent : string -> string -``` -URL-encodes a string, including characters with special meaning in a URI. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/encodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent) MDN -``` -val decodeURIComponent : string -> string -``` -Decodes a URL-enmcoded string produced by `encodeURIComponent` - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/decodeURIComponent](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent) MDN \ No newline at end of file diff --git a/docs/api/re/melange/Js-Int.md b/docs/api/re/melange/Js-Int.md deleted file mode 100644 index 08c28ca4a..000000000 --- a/docs/api/re/melange/Js-Int.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `Js.Int` - -Bindings to functions in JavaScript's `Number` that deal with ints - -Provides functions for inspecting and manipulating `int`s - -``` -type t = int -``` -If we use number, we need coerce to int32 by adding \`\|0\`, otherwise \`+0\` can be wrong. Most JS API is float oriented, it may overflow int32 or comes with `NAN` - -``` -val toExponential : ?digits:t -> t -> string -``` -Formats an `int` using exponential (scientific) notation - -**digits** specifies how many digits should appear after the decimal point. The value must be in the range \[0, 20\] (inclusive). - -**Returns** a `string` representing the given value in exponential notation - -The output will be rounded or padded with zeroes if necessary. - -raises `RangeError` if digits is not in the range \[0, 20\] (inclusive) -```ocaml - Js.Int.toExponential 77 = "7.7e+1" - Js.Int.toExponential ~digits:2 77 = "7.70e+1" - Js.Int.toExponential ~digits:2 5678 = "5.68e+3" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toExponential](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential) MDN -``` -val toPrecision : ?digits:t -> t -> string -``` -Formats an `int` using some fairly arbitrary rules - -**digits** specifies how many digits should appear in total. The value must between 1 and some 100. - -**Returns** a `string` representing the given value in fixed-point or scientific notation - -The output will be rounded or padded with zeroes if necessary. - -`toPrecision` differs from [`Js.Float.toFixed`](./Js-Float.md#val-toFixed) in that the former will count all digits against the precision, while the latter will count only the digits after the decimal point. `toPrecision` will also use scientific notation if the specified precision is less than the number for digits before the decimal point. - -raises `RangeError` if digits is not between 1 and 100. -```ocaml - Js.Int.toPrecision 123456789 = "123456789" - Js.Int.toPrecision ~digits:2 123456789 = "1.2e+8" - Js.Int.toPrecision ~digits:2 0 = "0.0" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toPrecision](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision) MDN -``` -val toString : ?radix:t -> t -> string -``` -Formats an `int` as a string - -**radix** specifies the radix base to use for the formatted number. The value must be in the range \[2, 36\] (inclusive). - -**Returns** a `string` representing the given value in fixed-point (usually) - -raises `RangeError` if radix is not in the range \[2, 36\] (inclusive) -```ocaml - Js.Int.toString 123456789 = "123456789" - Js.Int.toString ~radix:2 6 = "110" - Js.Int.toString ~radix:16 3735928559 = "deadbeef" - Js.Int.toString ~radix:36 123456 = "2n9c" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Number/toString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString) MDN -``` -val toFloat : t -> float -``` -``` -val equal : t -> t -> bool -``` -``` -val max : t -``` -``` -val min : t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Iterator.md b/docs/api/re/melange/Js-Iterator.md deleted file mode 100644 index 3f07302ff..000000000 --- a/docs/api/re/melange/Js-Iterator.md +++ /dev/null @@ -1,25 +0,0 @@ - -# Module `Js.Iterator` - -Bindings to functions on `Iterator` - -``` -type 'a t = 'a Js.iterator -``` -``` -type 'a value = { -``` -`done_ : bool option;` -`value : 'a option;` -``` -} -``` -``` -val next : 'a t -> 'a value -``` -``` -val toArray : 'a t -> 'a array -``` -``` -val toArrayWithMapper : 'a t -> f:('a -> 'b) -> 'b array -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Json.md b/docs/api/re/melange/Js-Json.md deleted file mode 100644 index f23f571bf..000000000 --- a/docs/api/re/melange/Js-Json.md +++ /dev/null @@ -1,285 +0,0 @@ - -# Module `Js.Json` - -Utility functions to manipulate JSON values - -Efficient JSON encoding using JavaScript API @see \ MDN - - -### Types - -``` -type t -``` -The JSON data structure - -``` -type _ kind = -``` -``` -| String : string kind -``` -``` -| Number : float kind -``` -``` -| Object : t Js.dict kind -``` -``` -| Array : t array kind -``` -``` -| Boolean : bool kind -``` -``` -| Null : t Js.null kind -``` -``` - -``` -Underlying type of a JSON value - -``` -type tagged_t = -``` -``` -| JSONFalse -``` -``` -| JSONTrue -``` -``` -| JSONNull -``` -``` -| JSONString of string -``` -``` -| JSONNumber of float -``` -``` -| JSONObject of t Js.dict -``` -``` -| JSONArray of t array -``` -``` - -``` - -### Accessor - -``` -val classify : t -> tagged_t -``` -``` -val test : 'a -> 'b kind -> bool -``` -`test v kind` returns true if `v` is of `kind` - -``` -val decodeString : t -> string option -``` -`decodeString json` returns `Some s` if `json` is a string, `None` otherwise - -``` -val decodeNumber : t -> float option -``` -`decodeNumber json` returns `Some n` if `json` is a number, `None` otherwise - -``` -val decodeObject : t -> t Js.dict option -``` -`decodeObject json` returns `Some o` if `json` is an object, `None` otherwise - -``` -val decodeArray : t -> t array option -``` -`decodeArray json` returns `Some a` if `json` is an array, `None` otherwise - -``` -val decodeBoolean : t -> bool option -``` -`decodeBoolean json` returns `Some b` if `json` is a boolean, `None` otherwise - -``` -val decodeNull : t -> 'a Js.null option -``` -`decodeNull json` returns `Some null` if `json` is a null, `None` otherwise - - -### Construtors - -Those functions allows the construction of an arbitrary complex JSON values. - -``` -val null : t -``` -`null` is the singleton null JSON value - -``` -val string : string -> t -``` -`string s` makes a JSON string of the `string` `s` - -``` -val number : float -> t -``` -`number n` makes a JSON number of the `float` `n` - -``` -val boolean : bool -> t -``` -`boolean b` makes a JSON boolean of the `bool` `b` - -``` -val object_ : t Js.dict -> t -``` -`object_ dict` makes a JSON object of the `Js.dict` `dict` - -``` -val array : t array -> t -``` -`array a` makes a JSON array of the `Js.Json.t array` `a` - -The functions below are specialized for specific array type which happened to be already JSON object in the Melange runtime. Therefore they are more efficient (constant time rather than linear conversion). - -``` -val stringArray : string array -> t -``` -`stringArray a` makes a JSON array of the `string array` `a` - -``` -val numberArray : float array -> t -``` -`numberArray a` makes a JSON array of the `float array` `a` - -``` -val booleanArray : bool array -> t -``` -`booleanArray` makes a JSON array of the `bool array` `a` - -``` -val objectArray : t Js.dict array -> t -``` -`objectArray a` makes a JSON array of the `JsDict.t array` `a` - - -### String conversion - -``` -val parseExn : string -> t -``` -`parseExn s` parses the string `s` into a JSON data structure - -**Returns** a JSON data structure - -raises `SyntaxError` if given string is not a valid JSON. Note SyntaxError is a JavaScript exception. -```ocaml -(* parse a simple JSON string *) - -let json = - try - Js.Json.parseExn {| "foo" |} - with - | _ -> failwith "Error parsing JSON string" -in -match Js.Json.classify json with -| Js.Json.JSONString value -> Js.log value -| _ -> failwith "Expected a string" -``` -```ocaml -(* parse a complex JSON string *) - -let getIds s = - let json = - try - Js.Json.parseExn s - with - | _ -> failwith "Error parsing JSON string" - in - match Js.Json.classify json with - | Js.Json.JSONObject value -> - (* In this branch, compiler infer value : Js.Json.t Js.dict *) - begin match Js.Dict.get value "ids" with - | Some ids -> - begin match Js.Json.classify ids with - | Js.Json.JSONArray ids -> - (* In this branch compiler infer ids : Js.Json.t array *) - ids - | _ -> failwith "Expected an array" - end - | None -> failwith "Expected an `ids` property" - end - | _ -> failwith "Expected an object" - - (* prints `1, 2, 3` *) - let _ = - Js.log (getIds {| { "ids" : [1, 2, 3] } |}) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/parse](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) MDN -``` -val stringify : t -> string -``` -`stringify json` formats the JSON data structure as a string - -**Returns** the string representation of a given JSON data structure - -```ocaml -(* Creates and stringifies a simple JS object *) - -let dict = Js.Dict.empty () in -Js.Dict.set dict "name" (Js.Json.string "John Doe"); -Js.Dict.set dict "age" (Js.Json.number 30.0); -Js.Dict.set dict "likes" - (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); - -Js.log (Js.Json.stringify (Js.Json.object_ dict)) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN -``` -val stringifyWithSpace : t -> int -> string -``` -`stringify json` formats the JSON data structure as a string - -**Returns** the string representation of a given JSON data structure - -```ocaml -(* Creates and stringifies a simple JS object with spacing *) - -let dict = Js.Dict.empty () in -Js.Dict.set dict "name" (Js.Json.string "John Doe"); -Js.Dict.set dict "age" (Js.Json.number 30.0); -Js.Dict.set dict "likes" - (Js.Json.stringArray [|"bucklescript";"ocaml";"js"|]); - - Js.log (Js.Json.stringifyWithSpace (Js.Json.object_ dict) 2) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN -``` -val stringifyAny : 'a -> string option -``` -`stringifyAny value` formats any `value` into a JSON string - -```ocaml - (* prints ``"foo", "bar"`` *) - Js.log (Js.Json.stringifyAny [| "foo"; "bar" |]) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/JSON/stringify](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) MDN -Best-effort serialization, it tries to seralize as many objects as possible and deserialize it back - -``` -val deserializeUnsafe : string -> 'a -``` -It is unsafe in two aspects - -- It may throw during parsing -- when you cast it to a specific type, it may have a type mismatch -``` -val serializeExn : 'a -> string -``` -It will raise in such situations: - -- The object can not be serlialized to a JSON -- There are cycles -- Some JS engines can not stringify deeply nested json objects \ No newline at end of file diff --git a/docs/api/re/melange/Js-Map.md b/docs/api/re/melange/Js-Map.md deleted file mode 100644 index 51c7817bf..000000000 --- a/docs/api/re/melange/Js-Map.md +++ /dev/null @@ -1,49 +0,0 @@ - -# Module `Js.Map` - -Bindings to functions in `Map` - -ES6 Map API - -``` -type ('k, 'v) t -``` -``` -val make : unit -> ('k, 'v) t -``` -``` -val fromArray : ('k * 'v) array -> ('k, 'v) t -``` -``` -val toArray : ('k, 'v) t -> ('k * 'v) array -``` -``` -val size : ('k, 'v) t -> int -``` -``` -val has : key:'k -> ('k, 'v) t -> bool -``` -``` -val get : key:'k -> ('k, 'v) t -> 'v option -``` -``` -val set : key:'k -> value:'v -> ('k, 'v) t -> ('k, 'v) t -``` -``` -val clear : ('k, 'v) t -> unit -``` -``` -val delete : key:'k -> ('k, 'v) t -> bool -``` -``` -val forEach : f:('v -> 'k -> ('k, 'v) t -> unit) -> ('k, 'v) t -> unit -``` -``` -val keys : ('k, 'v) t -> 'k Js.iterator -``` -``` -val values : ('k, 'v) t -> 'v Js.iterator -``` -``` -val entries : ('k, 'v) t -> ('k * 'v) Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Math.md b/docs/api/re/melange/Js-Math.md deleted file mode 100644 index 5d799dbda..000000000 --- a/docs/api/re/melange/Js-Math.md +++ /dev/null @@ -1,299 +0,0 @@ - -# Module `Js.Math` - -Bindings to the functions in the `Math` object - -JavaScript Math API - -``` -val _E : float -``` -Euler's number - -``` -val _LN2 : float -``` -natural logarithm of 2 - -``` -val _LN10 : float -``` -natural logarithm of 10 - -``` -val _LOG2E : float -``` -base 2 logarithm of E - -``` -val _LOG10E : float -``` -base 10 logarithm of E - -``` -val _PI : float -``` -Pi... (ratio of the circumference and diameter of a circle) - -``` -val _SQRT1_2 : float -``` -square root of 1/2 - -``` -val _SQRT2 : float -``` -square root of 2 - -``` -val abs_int : int -> int -``` -absolute value - -``` -val abs_float : float -> float -``` -absolute value - -``` -val acos : float -> float -``` -arccosine in radians, can return NaN - -``` -val acosh : float -> float -``` -hyperbolic arccosine in raidans, can return NaN, ES2015 - -``` -val asin : float -> float -``` -arcsine in radians, can return NaN - -``` -val asinh : float -> float -``` -hyperbolic arcsine in raidans, ES2015 - -``` -val atan : float -> float -``` -arctangent in radians - -``` -val atanh : float -> float -``` -hyperbolic arctangent in radians, can return NaN, ES2015 - -``` -val atan2 : y:float -> x:float -> float -``` -arctangent of the quotient of x and y, mostly... this one's a bit weird - -``` -val cbrt : float -> float -``` -cube root, can return NaN, ES2015 - -``` -val unsafe_ceil_int : float -> int -``` -may return values not representable by `int` - -``` -val ceil_int : float -> int -``` -smallest int greater than or equal to the argument - -``` -val ceil_float : float -> float -``` -smallest float greater than or equal to the argument - -``` -val clz32 : int -> int -``` -number of leading zero bits of the argument's 32 bit int representation, ES2015 - -``` -val cos : float -> float -``` -cosine in radians - -``` -val cosh : float -> float -``` -hyperbolic cosine in radians, ES2015 - -``` -val exp : float -> float -``` -natural exponentional - -``` -val expm1 : float -> float -``` -natural exponential minus 1, ES2015 - -``` -val unsafe_floor_int : float -> int -``` -may return values not representable by `int` - -``` -val floor_int : float -> int -``` -largest int greater than or equal to the arugment - -``` -val floor_float : float -> float -``` -``` -val fround : float -> float -``` -round to nearest single precision float, ES2015 - -``` -val hypot : float -> float -> float -``` -pythagorean equation, ES2015 - -``` -val hypotMany : float array -> float -``` -generalized pythagorean equation, ES2015 - -``` -val imul : int -> int -> int -``` -32-bit integer multiplication, ES2015 - -``` -val log : float -> float -``` -natural logarithm, can return NaN - -``` -val log1p : float -> float -``` -natural logarithm of 1 \+ the argument, can return NaN, ES2015 - -``` -val log10 : float -> float -``` -base 10 logarithm, can return NaN, ES2015 - -``` -val log2 : float -> float -``` -base 2 logarithm, can return NaN, ES2015 - -``` -val max_int : int -> int -> int -``` -max value - -``` -val maxMany_int : int array -> int -``` -max value - -``` -val max_float : float -> float -> float -``` -max value - -``` -val maxMany_float : float array -> float -``` -max value - -``` -val min_int : int -> int -> int -``` -min value - -``` -val minMany_int : int array -> int -``` -min value - -``` -val min_float : float -> float -> float -``` -min value - -``` -val minMany_float : float array -> float -``` -min value - -``` -val pow_float : base:float -> exp:float -> float -``` -base to the power of the exponent - -``` -val random : unit -> float -``` -random number in \[0,1) - -``` -val random_int : int -> int -> int -``` -random number in \[min,max) - -``` -val unsafe_round : float -> int -``` -rounds to nearest integer, returns a value not representable as `int` if NaN - -``` -val round : float -> float -``` -rounds to nearest integer - -``` -val sign_int : int -> int -``` -the sign of the argument, 1, \-1 or 0, ES2015 - -``` -val sign_float : float -> float -``` -the sign of the argument, 1, \-1, 0, \-0 or NaN, ES2015 - -``` -val sin : float -> float -``` -sine in radians - -``` -val sinh : float -> float -``` -hyperbolic sine in radians, ES2015 - -``` -val sqrt : float -> float -``` -square root, can return NaN - -``` -val tan : float -> float -``` -tangent in radians - -``` -val tanh : float -> float -``` -hyperbolic tangent in radians, ES2015 - -``` -val unsafe_trunc : float -> int -``` -truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 - -``` -val trunc : float -> float -``` -truncate, ie. remove fractional digits, returns a value not representable as `int` if NaN, ES2015 diff --git a/docs/api/re/melange/Js-Null.md b/docs/api/re/melange/Js-Null.md deleted file mode 100644 index 46aa576d8..000000000 --- a/docs/api/re/melange/Js-Null.md +++ /dev/null @@ -1,74 +0,0 @@ - -# Module `Js.Null` - -Utility functions on [`null`](./Js.md#type-null) - -Provides functionality for dealing with the `'a Js.null` type - -``` -type +'a t = 'a Js.null -``` -Local alias for `'a Js.null` - -``` -val return : 'a -> 'a t -``` -Constructs a value of `'a Js.null` containing a value of `'a` - -``` -val empty : 'a t -``` -The empty value, `null` - -``` -val getUnsafe : 'a t -> 'a -``` -``` -val getExn : 'a t -> 'a -``` -``` -val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t -``` -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -Maps the contained value using the given function - -If `'a Js.null` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.null` - -```ocaml -let maybeGreetWorld (maybeGreeting: string Js.null) = - Js.Null.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") -``` -``` -val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit -``` -Iterates over the contained value with the given function - -If `'a Js.null` contains a value, that value is unwrapped and applied to the given function. - -```ocaml -let maybeSay (maybeMessage: string Js.null) = - Js.Null.iter maybeMessage ~f:(fun message -> Js.log message) -``` -``` -val fromOption : 'a option -> 'a t -``` -Maps `'a option` to `'a Js.null` - - - -
Some a -> return a -
None -> empty -
- -``` -val toOption : 'a t -> 'a option -``` -Maps `'a Js.null` to `'a option` - - - -
return a -> Some a -
empty -> None -
diff --git a/docs/api/re/melange/Js-Nullable.md b/docs/api/re/melange/Js-Nullable.md deleted file mode 100644 index c4f7ffb3c..000000000 --- a/docs/api/re/melange/Js-Nullable.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `Js.Nullable` - -Utility functions on [`nullable`](./Js.md#type-nullable) - -Contains functionality for dealing with values that can be both `null` and `undefined` - -``` -type +'a t = 'a Js.nullable -``` -Local alias for `'a Js.nullable` - -``` -val return : 'a -> 'a t -``` -Constructs a value of `'a Js.nullable` containing a value of `'a` - -``` -val isNullable : 'a t -> bool -``` -Returns `true` if the given value is `null` or `undefined`, `false` otherwise - -``` -val null : 'a t -``` -The `null` value of type `'a Js.nullable` - -``` -val undefined : 'a t -``` -The `undefined` value of type `'a Js.nullable` - -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -``` -val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t -``` -Binds the contained value using the given function - -If `'a Js.nullable` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.nullable` - -```ocaml -let maybeGreetWorld (maybeGreeting: string Js.nullable) = - Js.Nullable.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") -``` -``` -val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit -``` -Iterates over the contained value with the given function - -If `'a Js.nullable` contains a value, that value is unwrapped and applied to the given function. - -```ocaml -let maybeSay (maybeMessage: string Js.nullable) = - Js.Nullable.iter maybeMessage ~f:(fun message -> Js.log message) -``` -``` -val fromOption : 'a option -> 'a t -``` -Maps `'a option` to `'a Js.nullable` - - - -
Some a -> return a -
None -> undefined -
- -``` -val toOption : 'a t -> 'a option -``` -Maps `'a Js.nullable` to `'a option` - - - -
return a -> Some a -
undefined -> None -
null -> None -
diff --git a/docs/api/re/melange/Js-Obj.md b/docs/api/re/melange/Js-Obj.md deleted file mode 100644 index 7ff457710..000000000 --- a/docs/api/re/melange/Js-Obj.md +++ /dev/null @@ -1,19 +0,0 @@ - -# Module `Js.Obj` - -Utility functions on \`Js.t\` JS objects - -``` -val empty : unit -> < .. > Js.t -``` -``` -val assign : < .. > Js.t -> < .. > Js.t -> < .. > Js.t -``` -``` -val merge : < .. > Js.t -> < .. > Js.t -> < .. > Js.t -``` -`merge obj1 obj2` assigns the properties in `obj2` to a copy of `obj1`. The function returns a new object, and both arguments are not mutated - -``` -val keys : _ Js.t -> string array -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Promise.md b/docs/api/re/melange/Js-Promise.md deleted file mode 100644 index 2a493825c..000000000 --- a/docs/api/re/melange/Js-Promise.md +++ /dev/null @@ -1,57 +0,0 @@ - -# Module `Js.Promise` - -Bindings to JS `Promise` functions - -Specialized bindings to Promise. Note: For simplicity, this binding does not track the error type, it treat it as an opaque type - -``` -type +'a t = 'a Js.promise -``` -``` -type error -``` -``` -val make : - (resolve:('a -> unit) Js.Fn.arity1 -> - reject:(exn -> unit) Js.Fn.arity1 -> - unit) -> - 'a t -``` -``` -val resolve : 'a -> 'a t -``` -``` -val reject : exn -> 'a t -``` -``` -val all : 'a t array -> 'a array t -``` -``` -val all2 : ('a0 t * 'a1 t) -> ('a0 * 'a1) t -``` -``` -val all3 : ('a0 t * 'a1 t * 'a2 t) -> ('a0 * 'a1 * 'a2) t -``` -``` -val all4 : ('a0 t * 'a1 t * 'a2 t * 'a3 t) -> ('a0 * 'a1 * 'a2 * 'a3) t -``` -``` -val all5 : - ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t) -> - ('a0 * 'a1 * 'a2 * 'a3 * 'a4) t -``` -``` -val all6 : - ('a0 t * 'a1 t * 'a2 t * 'a3 t * 'a4 t * 'a5 t) -> - ('a0 * 'a1 * 'a2 * 'a3 * 'a4 * 'a5) t -``` -``` -val race : 'a t array -> 'a t -``` -``` -val then_ : ('a -> 'b t) -> 'a t -> 'b t -``` -``` -val catch : (error -> 'a t) -> 'a t -> 'a t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Re.md b/docs/api/re/melange/Js-Re.md deleted file mode 100644 index 36f5547da..000000000 --- a/docs/api/re/melange/Js-Re.md +++ /dev/null @@ -1,178 +0,0 @@ - -# Module `Js.Re` - -Bindings to the functions in `RegExp.prototype` - -Provides bindings for JavaScript Regular Expressions - - -##### Syntax sugar - -Melange provides a bit of syntax sugar for regex literals: `[%re "/foo/g"]` will evaluate to a [`t`](./#type-t) that can be passed around and used like usual. - -**Note:** This is not an immutable API. A RegExp object with the `global` ("g") flag set will modify the [`lastIndex`](./#val-lastIndex) property when the RegExp object is used, and subsequent uses will continue the search from the previous [`lastIndex`](./#val-lastIndex). - -```ocaml -let maybeMatches = Js.String.exec ~str:"banana" [\[%re "/na+/g"\]] -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) JavaScript API reference on MDN -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular\_Expressions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) JavaScript Regular Expressions Guide on MDN -``` -type t = Js.re -``` -the RegExp object - -``` -type result -``` -the result of a executing a RegExp on a string - -``` -val captures : result -> string Js.nullable array -``` -an array of the match and captures, the first is the full match and the remaining are the substring captures - -``` -val index : result -> int -``` -0-based index of the match in the input string - -``` -val input : result -> string -``` -the original input string - -``` -val fromString : string -> t -``` -Constructs a RegExp object ([`t`](./#type-t)) from a string - -Regex literals (`[%re "/.../"]`) should generally be preferred, but `fromString` is very useful when you need to insert a string into a regex. - -```ocaml -(* A function that extracts the content of the first element with the given tag *) - -let contentOf tag xmlString = - Js.Re.fromString ("<" ^ tag ^ ">(.*?)<\\/" ^ tag ^">") - |> Js.Re.exec ~str:xmlString - |> function - | Some result -> Js.Nullable.toOption (Js.Re.captures result).(1) - | None -> None -``` -``` -val fromStringWithFlags : string -> flags:string -> t -``` -Constructs a RegExp object ([`t`](./#type-t)) from a string with the given `flags` - -See [`fromString`](./#val-fromString) - -Valid flags: - -
g global -
i ignore case -
m multiline -
u unicode (es2015) -
y sticky (es2015) -
- - -``` -val flags : t -> string -``` -returns the enabled flags as a string - -``` -val global : t -> bool -``` -returns a bool indicating whether the `global` flag is set - -``` -val ignoreCase : t -> bool -``` -returns a bool indicating whether the `ignoreCase` flag is set - -``` -val lastIndex : t -> int -``` -returns the index where the next match will start its search - -This property will be modified when the RegExp object is used, if the `global` ("g") flag is set. - -```ocaml -(* Finds and prints successive matches *) - -let re = [%re "/ab*/g"] in -let str = "abbcdefabh" in - -let break = ref false in -while not !break do - match re |> Js.Re.exec ~str with - | None -> break := true - | Some result -> - Js.Nullable.iter (Js.Re.captures result).(0) ((fun match_ -> - let next = string_of_int (Js.Re.lastIndex re) in - Js.log ("Found " ^ match_ ^ ". Next match starts at " ^ next))) -done -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/lastIndex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/lastIndex) MDN -``` -val setLastIndex : t -> int -> unit -``` -sets the index at which the next match will start its search from - -``` -val multiline : t -> bool -``` -returns a bool indicating whether the `multiline` flag is set - -``` -val source : t -> string -``` -returns the pattern as a string - -``` -val sticky : t -> bool -``` -returns a bool indicating whether the `sticky` flag is set - -``` -val unicode : t -> bool -``` -returns a bool indicating whether the `unicode` flag is set - -``` -val exec : str:string -> t -> result option -``` -executes a search on a given string using the given RegExp object - -**returns** `Some` [`result`](./#type-result) if a match is found, `None` otherwise - -```ocaml -(* Match "quick brown" followed by "jumps", ignoring characters in between - * Remember "brown" and "jumps" - * Ignore case - *) - -let re = [%re "/quick\s(brown).+?(jumps)/ig"] in -let result = re |. Js.Re.exec ~str:"The Quick Brown Fox Jumps Over The Lazy Dog" -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/exec](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) MDN -``` -val test : str:string -> t -> bool -``` -tests whether the given RegExp object will match a given string - -**returns** `true` if a match is found, `false` otherwise - -```ocaml -(* A simple implementation of Js.String.startsWith *) - -let str = "hello world!" - -let startsWith target substring = - Js.Re.fromString ("^" ^ substring) - |. Js.Re.test ~str:target - -let () = Js.log (str |. startsWith "hello") (* prints "true" *) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/RegExp/test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) MDN \ No newline at end of file diff --git a/docs/api/re/melange/Js-Set.md b/docs/api/re/melange/Js-Set.md deleted file mode 100644 index bd1087307..000000000 --- a/docs/api/re/melange/Js-Set.md +++ /dev/null @@ -1,43 +0,0 @@ - -# Module `Js.Set` - -Bindings to functions in `Set` - -ES6 Set API - -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val fromArray : 'a array -> 'a t -``` -``` -val toArray : 'a t -> 'a array -``` -``` -val size : 'a t -> int -``` -``` -val add : value:'a -> 'a t -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val delete : value:'a -> 'a t -> bool -``` -``` -val forEach : f:('a -> unit) -> 'a t -> unit -``` -``` -val has : value:'a -> 'a t -> bool -``` -``` -val values : 'a t -> 'a Js.iterator -``` -``` -val entries : 'a t -> ('a * 'a) Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-String.md b/docs/api/re/melange/Js-String.md deleted file mode 100644 index ff90c544a..000000000 --- a/docs/api/re/melange/Js-String.md +++ /dev/null @@ -1,464 +0,0 @@ - -# Module `Js.String` - -Bindings to the functions in `String.prototype` - -JavaScript String API - -``` -type t = string -``` -``` -val make : 'a -> t -``` -`make value` converts the given value to a string - -```ocaml - make 3.5 = "3.5";; - make [|1;2;3|]) = "1,2,3";; -``` -``` -val fromCharCode : int -> t -``` -`fromCharCode n` creates a string containing the character corresponding to that number; *n* ranges from 0 to 65535. If out of range, the lower 16 bits of the value are used. Thus, `fromCharCode 0x1F63A` gives the same result as `fromCharCode 0xF63A`. - -```ocaml - fromCharCode 65 = "A";; - fromCharCode 0x3c8 = {js|ψ|js};; - fromCharCode 0xd55c = {js|한|js};; - fromCharCode -64568 = {js|ψ|js};; -``` -``` -val fromCharCodeMany : int array -> t -``` -`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given numbers, using the same rules as `fromCharCode`. - -```ocaml - fromCharCodeMany([|0xd55c, 0xae00, 33|]) = {js|한글!|js};; -``` -``` -val fromCodePoint : int -> t -``` -`fromCodePoint n` creates a string containing the character corresponding to that numeric code point. If the number is not a valid code point, **raises** `RangeError`. Thus, `fromCodePoint 0x1F63A` will produce a correct value, unlike `fromCharCode 0x1F63A`, and `fromCodePoint -5` will raise a `RangeError`. - -```ocaml - fromCodePoint 65 = "A";; - fromCodePoint 0x3c8 = {js|ψ|js};; - fromCodePoint 0xd55c = {js|한|js};; - fromCodePoint 0x1f63a = {js|😺|js};; -``` -``` -val fromCodePointMany : int array -> t -``` -`fromCharCodeMany [|n1;n2;n3|]` creates a string from the characters corresponding to the given code point numbers, using the same rules as `fromCodePoint`. - -```ocaml - fromCodePointMany([|0xd55c; 0xae00; 0x1f63a|]) = {js|한글😺|js} -``` -``` -val length : t -> int -``` -`length s` returns the length of the given string. - -```ocaml - length "abcd" = 4;; -``` -``` -val get : t -> int -> t -``` -`get s n` returns as a string the character at the given index number. If `n` is out of range, this function returns `undefined`, so at some point this function may be modified to return `t option`. - -```ocaml - get "Reason" 0 = "R";; - get "Reason" 4 = "o";; - get {js|Rẽasöń|js} 5 = {js|ń|js};; -``` -``` -val charAt : index:int -> t -> t -``` -`charAt ~index s` gets the character at position `index` within string `s`. If `index` is negative or greater than the length of `s`, returns the empty string. If the string contains characters outside the range `\u0000-\uffff`, it will return the first 16-bit value at that position in the string. - -```ocaml - charAt ~index:0 "Reason" = "R" - charAt ~index:12 "Reason" = ""; - charAt ~index:5 {js|Rẽasöń|js} = {js|ń|js} -``` -``` -val charCodeAt : index:int -> t -> float -``` -`charCodeAt s ~index` returns the character code at position `index` in string `s`; the result is in the range 0-65535, unlke `codePointAt`, so it will not work correctly for characters with code points greater than or equal to `0x10000`. The return type is `float` because this function returns `NaN` if `index` is less than zero or greater than the length of the string. - -```ocaml - charCodeAt ~index:0 {js|😺|js} = 0xd83d - codePointAt ~index:0 {js|😺|js} = Some 0x1f63a -``` -``` -val codePointAt : index:int -> t -> int option -``` -`codePointAt s ~index` returns the code point at position `index` within string `s` as a `Some` value. The return value handles code points greater than or equal to `0x10000`. If there is no code point at the given position, the function returns `None`. - -```ocaml - codePointAt ~index:1 {js|¿😺?|js} = Some 0x1f63a - codePointAt ~index:5 "abc" = None -``` -ES2015 - -``` -val concat : other:t -> t -> t -``` -`concat ~other:str2 str1` returns a new string with `str2` added after `str1`. - -```ocaml - concat ~other:"bell" "cow" = "cowbell";; -``` -``` -val concatMany : strings:t array -> t -> t -``` -`concatMany ~strings original` returns a new string consisting of each item of the array of strings `strings` added to the `original` string. - -```ocaml - concatMany ~strings:[|"2nd"; "3rd"; "4th"|] "1st" = "1st2nd3rd4th";; -``` -``` -val endsWith : suffix:t -> ?len:int -> t -> bool -``` -`endsWith ~suffix ?len str` returns `true` if the `str` ends with `suffix`, `false` otherwise. If `len` is specified, \`endsWith\` only takes into account the first `len` characters. - -```ocaml - endsWith ~suffix:"cd" ~len:4 "abcd" = true;; - endsWith ~suffix:"cd" ~len:3 "abcde" = false;; - endsWith ~suffix:"cde" ~len:99 "abcde" = true;; - endsWith ~suffix:"ple" ~len:7 "example.dat" = true;; - endsWith ~suffix:"World!" "Hello, World!" = true;; - endsWith ~suffix:"world!" "Hello, World!" = false;; (* case-sensitive *) - endsWith ~suffix:"World" "Hello, World!" = false;; (* exact match *) -``` -``` -val includes : search:t -> ?start:int -> t -> bool -``` -`includes ~search ?start s` returns `true` if `search` is found anywhere within `s` starting at character number `start` (where 0 is the first character), `false` otherwise. - -```ocaml - includes ~search:"gram" "programmer" = true;; - includes ~search:"er" "programmer" = true;; - includes ~search:"pro" "programmer" = true;; - includes ~search:"xyz" "programmer" = false;; - includes ~search:"gram" ~start:1 "programmer" = true;; - includes ~search:"gram" ~start:4 "programmer" = false;; - includes ~search:{js|한|js} ~start:1 {js|대한민국|js} = true;; -``` -``` -val indexOf : search:t -> ?start:int -> t -> int -``` -`indexOf ~search ?start s` returns the position at which `search` was found within `s` starting at character position `start`, or `-1` if `search` is not found in that portion of `s`. The return value is relative to the beginning of the string, no matter where the search started from. - -```ocaml - indexOf ~search:"ok" "bookseller" = 2;; - indexOf ~search:"sell" "bookseller" = 4;; - indexOf ~search:"ee" "beekeeper" = 1;; - indexOf ~search:"xyz" "bookseller" = -1;; - indexOf ~search:"ok" ~start:1 "bookseller" = 2;; - indexOf ~search:"sell" ~start:2 "bookseller" = 4;; - indexOf ~search:"sell" ~start:5 "bookseller" = -1;; -``` -``` -val lastIndexOf : search:t -> ?start:int -> t -> int -``` -`lastIndexOf ~search ~start s` returns the position of the *last* occurrence of `searchValue` within `s`, searching backwards from the given `start` position. Returns `-1` if `searchValue` is not in `s`. The return value is always relative to the beginning of the string. - -```ocaml - lastIndexOf ~search:"ok" "bookseller" = 2;; - lastIndexOf ~search:"ee" "beekeeper" = 4;; - lastIndexOf ~search:"xyz" "abcdefg" = -1;; - lastIndexOf ~search:"ok" ~start:6 "bookseller" = 2;; - lastIndexOf ~search:"ee" ~start:8 "beekeeper" = 4;; - lastIndexOf ~search:"ee" ~start:3 "beekeeper" = 1;; - lastIndexOf ~search:"xyz" ~start:4 "abcdefg" = -1;; -``` -``` -val localeCompare : other:t -> t -> float -``` -`localeCompare ~other:comparison reference` returns: - -- a negative value if `reference` comes before `comparison` in sort order -- zero if `reference` and `comparison` have the same sort order -- a positive value if `reference` comes after `comparison` in sort order -```ocaml - (localeCompare ~other:"ant" "zebra") > 0.0;; - (localeCompare ~other:"zebra" "ant") < 0.0;; - (localeCompare ~other:"cat" "cat") = 0.0;; - (localeCompare ~other:"cat" "CAT") > 0.0;; -``` -``` -val match_ : regexp:Js.re -> t -> t option array option -``` -`match ~regexp str` matches a string against the given `regexp`. If there is no match, it returns `None`. For regular expressions without the `g` modifier, if there is a match, the return value is `Some array` where the array contains: - -- The entire matched string -- Any capture groups if the `regexp` had parentheses -For regular expressions with the `g` modifier, a matched expression returns `Some array` with all the matched substrings and no capture groups. - -```ocaml - match "The better bats" ~regexp:[%re "/b[aeiou]t/"] = Some [|"bet"|] - match "The better bats" ~regexp:[%re "/b[aeiou]t/g"] = Some [|"bet";"bat"|] - match "Today is 2018-04-05." ~regexp:[%re "/(\\d+)-(\\d+)-(\\d+)/"] = Some [|"2018-04-05"; "2018"; "04"; "05"|] - match "The large container." ~regexp:[%re "/b[aeiou]g/"] = None -``` -``` -val normalize : ?form:[ `NFC | `NFD | `NFKC | `NFKD ] -> t -> t -``` -`normalize ~form str` returns the normalized Unicode string using the specified form of normalization, which may be one of: - -- `` `NFC `` — Normalization Form Canonical Composition. -- `` `NFD `` — Normalization Form Canonical Decomposition. -- `` `NFKC `` — Normalization Form Compatibility Composition. -- `` `NFKD `` — Normalization Form Compatibility Decomposition. -If `form` is omitted, `` `NFC `` is used. - -Consider the character `ã`, which can be represented as the single codepoint `\u00e3` or the combination of a lower case letter A `\u0061` and a combining tilde `\u0303`. Normalization ensures that both can be stored in an equivalent binary representation. - -see [https://www.unicode.org/reports/tr15/tr15-45.html](https://www.unicode.org/reports/tr15/tr15-45.html) Unicode technical report for details -``` -val repeat : count:int -> t -> t -``` -`repeat ~count s` returns a string that consists of `count` repetitions of `s`. Raises `RangeError` if `n` is negative. - -```ocaml - repeat ~count:3 "ha" = "hahaha" - repeat ~count:0 "empty" = "" -``` -``` -val replace : search:t -> replacement:t -> t -> t -``` -`replace ~search ~replacement string` returns a new string which is identical to `string` except with the first matching instance of `search` replaced by `replacement`. - -`search` is treated as a verbatim string to match, not a regular expression. - -```ocaml - replace ~search:"old" ~replacement:"new" "old string" = "new string" - replace ~search:"the" ~replacement:"this" "the cat and the dog" = "this cat and the dog" -``` -``` -val replaceByRe : regexp:Js.re -> replacement:t -> t -> t -``` -`replaceByRe ~regexp ~replacement string` returns a new string where occurrences matching `regexp` have been replaced by `replacement`. - -```ocaml - replaceByRe ~regexp:[%re "/[aeiou]/g"] ~replacement:"x" "vowels be gone" = "vxwxls bx gxnx" - replaceByRe ~regexp:[%re "/(\\w+) (\\w+)/"] ~replacement:"$2, $1" "Juan Fulano" = "Fulano, Juan" -``` -``` -val unsafeReplaceBy0 : regexp:Js.re -> f:(t -> int -> t -> t) -> t -> t -``` -`unsafeReplaceBy0 ~regexp ~f s` returns a new string with some or all matches of a pattern with no capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the offset at which the match begins, and the whole string being matched - -```ocaml -let str = "beautiful vowels" -let re = [%re "/[aeiou]/g"] -let matchFn matchPart offset wholeString = Js.String.toUpperCase matchPart - -let replaced = Js.String.unsafeReplaceBy0 ~regexp:re ~f:matchFn str - -let () = Js.log replaced (* prints "bEAUtifUl vOwEls" *) -``` -@see \ MDN - -``` -val unsafeReplaceBy1 : regexp:Js.re -> f:(t -> t -> int -> t -> t) -> t -> t -``` -`unsafeReplaceBy1 ~regexp ~f s` returns a new string with some or all matches of a pattern with one set of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. - -```ocaml -let str = "increment 23" -let re = [%re "/increment (\\d+)/g"] -let matchFn matchPart p1 offset wholeString = - wholeString ^ " is " ^ (string_of_int ((int_of_string p1) + 1)) - -let replaced = Js.String.unsafeReplaceBy1 ~regexp:re ~f:matchFn str - -let () = Js.log replaced (* prints "increment 23 is 24" *) -``` -@see \ MDN - -``` -val unsafeReplaceBy2 : - regexp:Js.re -> - f:(t -> t -> t -> int -> t -> t) -> - t -> - t -``` -`unsafeReplaceBy2 ~regexp ~f s` returns a new string with some or all matches of a pattern with two sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. - -```ocaml -let str = "7 times 6" -let re = [%re "/(\\d+) times (\\d+)/"] -let matchFn matchPart p1 p2 offset wholeString = - string_of_int ((int_of_string p1) * (int_of_string p2)) - -let replaced = Js.String.unsafeReplaceBy2 ~regexp:re ~f:matchFn str - -let () = Js.log replaced (* prints "42" *) -``` -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN -``` -val unsafeReplaceBy3 : - regexp:Js.re -> - f:(t -> t -> t -> t -> int -> t -> t) -> - t -> - t -``` -`unsafeReplaceBy3 ~regexp ~f s` returns a new string with some or all matches of a pattern with three sets of capturing parentheses replaced by the value returned from the given function. The function receives as its parameters the matched string, the captured strings, the offset at which the match begins, and the whole string being matched. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/replace\#Specifying\_a\_function\_as\_a\_parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter) MDN -``` -val search : regexp:Js.re -> t -> int -``` -`search ~regexp str` returns the starting position of the first match of `regexp` in the given `str`, or \-1 if there is no match. - -```ocaml -search ~regexp:[%re "/\\d+/"] "testing 1 2 3" = 8;; -search ~regexp:[%re "/\\d+/"] "no numbers" = -1;; -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`slice ?start ?end str` returns the substring of `str` starting at character `start` up to but not including `end` - -If either `start` or `end` is negative, then it is evaluated as `length str - start` (or `length str - end`). - -If `end` is greater than the length of `str`, then it is treated as `length str`. - -If `start` is greater than `end`, `slice` returns the empty string. - -```ocaml - slice ~start:2 ~end_:5 "abcdefg" = "cde";; - slice ~start:2 ~end_:9 "abcdefg" = "cdefg";; - slice ~start:(-4) ~end_:(-2) "abcdefg" = "de";; - slice ~start:5 ~end_:1 "abcdefg" = "";; -``` -``` -val split : ?sep:t -> ?limit:int -> t -> t array -``` -`split ?sep ?limit str` splits the given `str` at every occurrence of `sep` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. - -```ocaml - split ~sep:"/" ~limit: 3 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"|];; - split ~sep:"/" ~limit: 0 "ant/bee/cat/dog/elk" = [| |];; - split ~sep:"/" ~limit: 9 "ant/bee/cat/dog/elk" = [|"ant"; "bee"; "cat"; "dog"; "elk"|];; -``` -``` -val splitByRe : regexp:Js.re -> ?limit:int -> t -> t option array -``` -`splitByRe str ~regexp ?limit ()` splits the given `str` at every occurrence of `regexp` and returns an array of the first `limit` resulting substrings. If `limit` is negative or greater than the number of substrings, the array will contain all the substrings. - -```ocaml - splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:3 "one: two: three: four" = [|"one"; "two"; "three"|];; - splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:0 "one: two: three: four" = [| |];; - splitByRe ~regexp:[%re "/\\s*:\\s*/"] ~limit:8 "one: two: three: four" = [|"one"; "two"; "three"; "four"|];; -``` -; - -``` -val startsWith : prefix:t -> ?start:int -> t -> bool -``` -`startsWith ~prefix ?start str` returns `true` if the `str` starts with `prefix` starting at position `start`, `false` otherwise. If `start` is negative, the search starts at the beginning of `str`. - -```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;; -``` -``` -val substr : ?start:int -> ?len:int -> t -> t -``` -`substr ?start ?len str` returns the substring of `str` of length `len` starting at position `start`. - -If `start` is less than zero, the starting position is the length of `str` - -- `start`. -If `start` is greater than or equal to the length of `str`, returns the empty string. - -If `len` is less than or equal to zero, returns the empty string. - -```ocaml - substr ~start:3 ~len:4 "abcdefghij" = "defghij" - substr ~start:(-3) ~len:4 "abcdefghij" = "hij" - substr ~start:12 ~len:2 "abcdefghij" = "" -``` -deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/substr\#sect1 -``` -val substring : ?start:int -> ?end_:int -> t -> t -``` -`substring ~start ~end_ str` returns characters `start` up to but not including `end_` from `str`. - -If `start` is less than zero, it is treated as zero. - -If `end_` is zero or negative, the empty string is returned. - -If `start` is greater than `end_`, the start and finish points are swapped. - -```ocaml - substring ~start:3 ~end_:6 "playground" = "ygr";; - substring ~start:6 ~end_:3 "playground" = "ygr";; - substring ~start:4 ~end_:12 "playground" = "ground";; -``` -``` -val toLowerCase : t -> t -``` -`toLowerCase str` converts `str` to lower case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can give different results depending upon context, for example with the Greek letter sigma, which has two different lower case forms when it is the last character in a string or not. - -```ocaml - toLowerCase "ABC" = "abc";; - toLowerCase {js|ΣΠ|js} = {js|σπ|js};; - toLowerCase {js|ΠΣ|js} = {js|πς|js};; -``` -``` -val toLocaleLowerCase : t -> t -``` -`toLocaleLowerCase str` converts `str` to lower case using the current locale - -``` -val toUpperCase : t -> t -``` -`toUpperCase str` converts `str` to upper case using the locale-insensitive case mappings in the Unicode Character Database. Notice that the conversion can expand the number of letters in the result; for example the German `ß` capitalizes to two `S`es in a row. - -```ocaml - toUpperCase "abc" = "ABC";; - toUpperCase {js|Straße|js} = {js|STRASSE|js};; - toUpperCase {js|πς|js} = {js|ΠΣ|js};; -``` -``` -val toLocaleUpperCase : t -> t -``` -`toLocaleUpperCase str` converts `str` to upper case using the current locale - -``` -val trim : t -> t -``` -`trim str` returns a string that is `str` with whitespace stripped from both ends. Internal whitespace is not removed. - -```ocaml - trim " abc def " = "abc def" - trim "\n\r\t abc def \n\n\t\r " = "abc def" -``` -``` -val anchor : name:t -> t -> t -``` -`anchor ~name:anchorName anchorText` creates a string with an HTML `` element with `name` attribute of `anchorName` and `anchorText` as its content. - -```ocaml - anchor ~name:"page1" "Page One" = "Page One" -``` -deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/anchor\#sect1 -``` -val link : href:t -> t -> t -``` -`link ~href:urlText linkText` creates a string with an HTML `` element with `href` attribute of `urlText` and `linkText` as its content. - -```ocaml - link ~href:"page2.html" "Go to page two" = "Go to page two" -``` -deprecated This function is deprecated, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/String/link\#sect1 -``` -val unsafeToArrayLike : t -> t Js.array_like -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-ArrayBuffer.md b/docs/api/re/melange/Js-Typed_array-ArrayBuffer.md deleted file mode 100644 index 3331025db..000000000 --- a/docs/api/re/melange/Js-Typed_array-ArrayBuffer.md +++ /dev/null @@ -1,20 +0,0 @@ - -# Module `Typed_array.ArrayBuffer` - -The underlying buffer that the typed arrays provide views of - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) MDN -``` -type t = Js.arrayBuffer -``` -``` -val make : int -> t -``` -takes length. initializes elements to 0 - -``` -val byteLength : t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> Js.arrayBuffer -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-DataView.md b/docs/api/re/melange/Js-Typed_array-DataView.md deleted file mode 100644 index 1d1ad1f0f..000000000 --- a/docs/api/re/melange/Js-Typed_array-DataView.md +++ /dev/null @@ -1,108 +0,0 @@ - -# Module `Typed_array.DataView` - -The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/DataView](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) MDN -``` -type t -``` -``` -val make : Js.arrayBuffer -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val getInt8 : int -> t -> int -``` -``` -val getUint8 : int -> t -> int -``` -``` -val getInt16 : int -> t -> int -``` -``` -val getInt16LittleEndian : int -> t -> int -``` -``` -val getUint16 : int -> t -> int -``` -``` -val getUint16LittleEndian : int -> t -> int -``` -``` -val getInt32 : int -> t -> int -``` -``` -val getInt32LittleEndian : int -> t -> int -``` -``` -val getUint32 : int -> t -> int -``` -``` -val getUint32LittleEndian : int -> t -> int -``` -``` -val getFloat32 : int -> t -> float -``` -``` -val getFloat32LittleEndian : int -> t -> float -``` -``` -val getFloat64 : int -> t -> float -``` -``` -val getFloat64LittleEndian : int -> t -> float -``` -``` -val setInt8 : int -> int -> t -> unit -``` -``` -val setUint8 : int -> int -> t -> unit -``` -``` -val setInt16 : int -> int -> t -> unit -``` -``` -val setInt16LittleEndian : int -> int -> t -> unit -``` -``` -val setUint16 : int -> int -> t -> unit -``` -``` -val setUint16LittleEndian : int -> int -> t -> unit -``` -``` -val setInt32 : int -> int -> t -> unit -``` -``` -val setInt32LittleEndian : int -> int -> t -> unit -``` -``` -val setUint32 : int -> int -> t -> unit -``` -``` -val setUint32LittleEndian : int -> int -> t -> unit -``` -``` -val setFloat32 : int -> float -> t -> unit -``` -``` -val setFloat32LittleEndian : int -> float -> t -> unit -``` -``` -val setFloat64 : int -> float -> t -> unit -``` -``` -val setFloat64LittleEndian : int -> float -> t -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Float32Array.md b/docs/api/re/melange/Js-Typed_array-Float32Array.md deleted file mode 100644 index 77ea7f873..000000000 --- a/docs/api/re/melange/Js-Typed_array-Float32Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Float32Array` - -``` -type elt = float -``` -``` -type 'a typed_array = Js.float32Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Float64Array.md b/docs/api/re/melange/Js-Typed_array-Float64Array.md deleted file mode 100644 index 47a2c9062..000000000 --- a/docs/api/re/melange/Js-Typed_array-Float64Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Float64Array` - -``` -type elt = float -``` -``` -type 'a typed_array = Js.float64Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Int16Array.md b/docs/api/re/melange/Js-Typed_array-Int16Array.md deleted file mode 100644 index efd85abba..000000000 --- a/docs/api/re/melange/Js-Typed_array-Int16Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Int16Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.int16Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Int32Array.md b/docs/api/re/melange/Js-Typed_array-Int32Array.md deleted file mode 100644 index 459de0957..000000000 --- a/docs/api/re/melange/Js-Typed_array-Int32Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Int32Array` - -``` -type elt = int32 -``` -``` -type 'a typed_array = Js.int32Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Int8Array.md b/docs/api/re/melange/Js-Typed_array-Int8Array.md deleted file mode 100644 index fd129f858..000000000 --- a/docs/api/re/melange/Js-Typed_array-Int8Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Int8Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.int8Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint16Array.md b/docs/api/re/melange/Js-Typed_array-Uint16Array.md deleted file mode 100644 index 44568a6d6..000000000 --- a/docs/api/re/melange/Js-Typed_array-Uint16Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint16Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint16Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint32Array.md b/docs/api/re/melange/Js-Typed_array-Uint32Array.md deleted file mode 100644 index 2faa8f753..000000000 --- a/docs/api/re/melange/Js-Typed_array-Uint32Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint32Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint32Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint8Array.md b/docs/api/re/melange/Js-Typed_array-Uint8Array.md deleted file mode 100644 index e3a3890d2..000000000 --- a/docs/api/re/melange/Js-Typed_array-Uint8Array.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint8Array` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint8Array -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md b/docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md deleted file mode 100644 index 27966ace2..000000000 --- a/docs/api/re/melange/Js-Typed_array-Uint8ClampedArray.md +++ /dev/null @@ -1,165 +0,0 @@ - -# Module `Typed_array.Uint8ClampedArray` - -``` -type elt = int -``` -``` -type 'a typed_array = Js.uint8ClampedArray -``` -``` -type t = elt typed_array -``` -``` -val unsafe_get : t -> int -> elt -``` -``` -val unsafe_set : t -> int -> elt -> unit -``` -``` -val buffer : t -> Js.arrayBuffer -``` -``` -val byteLength : t -> int -``` -``` -val byteOffset : t -> int -``` -``` -val setArray : elt array -> t -> unit -``` -``` -val setArrayOffset : elt array -> int -> t -> unit -``` -``` -val length : t -> int -``` -``` -val copyWithin : to_:int -> ?start:int -> ?end_:int -> t -> t -``` -``` -val fill : elt -> ?start:int -> ?end_:int -> t -> t -``` -``` -val reverseInPlace : t -> t -``` -``` -val sortInPlace : t -> t -``` -``` -val sortInPlaceWith : f:(elt -> elt -> int) -> t -> t -``` -``` -val includes : value:elt -> t -> bool -``` -``` -val indexOf : value:elt -> ?start:int -> t -> int -``` -``` -val join : ?sep:string -> t -> string -``` -``` -val lastIndexOf : value:elt -> t -> int -``` -``` -val lastIndexOfFrom : value:elt -> from:int -> t -> int -``` -``` -val slice : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val copy : t -> t -``` -``` -val subarray : ?start:int -> ?end_:int -> t -> t -``` -`start` is inclusive, `end_` exclusive - -``` -val toString : t -> string -``` -``` -val toLocaleString : t -> string -``` -``` -val entries : t -> (int * elt) Js.iterator -``` -``` -val every : f:(elt -> bool) -> t -> bool -``` -``` -val everyi : f:(elt -> int -> bool) -> t -> bool -``` -``` -val filter : f:(elt -> bool) -> t -> t -``` -``` -val filteri : f:(elt -> int -> bool) -> t -> t -``` -``` -val find : f:(elt -> bool) -> t -> elt Js.undefined -``` -``` -val findi : f:(elt -> int -> bool) -> t -> elt Js.undefined -``` -``` -val findIndex : f:(elt -> bool) -> t -> int -``` -``` -val findIndexi : f:(elt -> int -> bool) -> t -> int -``` -``` -val forEach : f:(elt -> unit) -> t -> unit -``` -``` -val forEachi : f:(elt -> int -> unit) -> t -> unit -``` -``` -val keys : t -> int Js.iterator -``` -``` -val map : f:(elt -> 'b) -> t -> 'b typed_array -``` -``` -val mapi : f:(elt -> int -> 'b) -> t -> 'b typed_array -``` -``` -val reduce : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reducei : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRight : f:('b -> elt -> 'b) -> init:'b -> t -> 'b -``` -``` -val reduceRighti : f:('b -> elt -> int -> 'b) -> init:'b -> t -> 'b -``` -``` -val some : f:(elt -> bool) -> t -> bool -``` -``` -val somei : f:(elt -> int -> bool) -> t -> bool -``` -``` -val _BYTES_PER_ELEMENT : int -``` -``` -val make : elt array -> t -``` -``` -val fromBuffer : Js.arrayBuffer -> ?off:int -> ?len:int -> unit -> t -``` -raises [`Js.Exn.Error`](./Js-Exn.md#extension-Error) raises Js exception -parameter offset is in bytes, length in elements -``` -val fromLength : int -> t -``` -``` -val from : elt Js.array_like -> t -``` -``` -val values : t -> elt Js.iterator -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Typed_array.md b/docs/api/re/melange/Js-Typed_array.md deleted file mode 100644 index 4716bb636..000000000 --- a/docs/api/re/melange/Js-Typed_array.md +++ /dev/null @@ -1,44 +0,0 @@ - -# Module `Js.Typed_array` - -Bindings to the functions in `TypedArray.prototype` - -JavaScript Typed Array API - -see [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/TypedArray](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) MDN -``` -module ArrayBuffer : sig ... end -``` -The underlying buffer that the typed arrays provide views of - -``` -module Int8Array : sig ... end -``` -``` -module Uint8Array : sig ... end -``` -``` -module Uint8ClampedArray : sig ... end -``` -``` -module Int16Array : sig ... end -``` -``` -module Uint16Array : sig ... end -``` -``` -module Int32Array : sig ... end -``` -``` -module Uint32Array : sig ... end -``` -``` -module Float32Array : sig ... end -``` -``` -module Float64Array : sig ... end -``` -``` -module DataView : sig ... end -``` -The DataView view provides a low-level interface for reading and writing multiple number types in an ArrayBuffer irrespective of the platform's endianness. diff --git a/docs/api/re/melange/Js-Types.md b/docs/api/re/melange/Js-Types.md deleted file mode 100644 index d9e8e32ab..000000000 --- a/docs/api/re/melange/Js-Types.md +++ /dev/null @@ -1,109 +0,0 @@ - -# Module `Js.Types` - -Utility functions for runtime reflection on JS types - -``` -type symbol -``` -Js symbol type only available in ES6 - -``` -type bigint_val -``` -Js bigint type only available in ES2020 - -``` -type obj_val -``` -``` -type undefined_val -``` -This type has only one value `undefined` - -``` -type null_val -``` -This type has only one value `null` - -``` -type function_val -``` -``` -type _ t = -``` -``` -| Undefined : undefined_val t -``` -``` -| Null : null_val t -``` -``` -| Boolean : bool t -``` -``` -| Number : float t -``` -``` -| String : string t -``` -``` -| Function : function_val t -``` -``` -| Object : obj_val t -``` -``` -| Symbol : symbol t -``` -``` -| BigInt : bigint_val t -``` -``` - -``` -``` -val test : 'a -> 'b t -> bool -``` -```ocaml -test "x" String = true -``` -``` -type tagged_t = -``` -``` -| JSFalse -``` -``` -| JSTrue -``` -``` -| JSNull -``` -``` -| JSUndefined -``` -``` -| JSNumber of float -``` -``` -| JSString of string -``` -``` -| JSFunction of function_val -``` -``` -| JSObject of obj_val -``` -``` -| JSSymbol of symbol -``` -``` -| JSBigInt of bigint_val -``` -``` - -``` -``` -val classify : 'a -> tagged_t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-Undefined.md b/docs/api/re/melange/Js-Undefined.md deleted file mode 100644 index 749c64f50..000000000 --- a/docs/api/re/melange/Js-Undefined.md +++ /dev/null @@ -1,79 +0,0 @@ - -# Module `Js.Undefined` - -Utility functions on [`undefined`](./Js.md#type-undefined) - -Provides functionality for dealing with the `'a Js.undefined` type - -``` -type +'a t = 'a Js.undefined -``` -Local alias for `'a Js.undefined` - -``` -val return : 'a -> 'a t -``` -Constructs a value of `'a Js.undefined` containing a value of `'a` - -``` -val testAny : 'a -> bool -``` -Returns `true` if the given value is `empty` (`undefined`) - -``` -val empty : 'a t -``` -The empty value, `undefined` - -``` -val getUnsafe : 'a t -> 'a -``` -``` -val getExn : 'a t -> 'a -``` -``` -val map : f:('a -> 'b) Js.Fn.arity1 -> 'a t -> 'b t -``` -``` -val bind : f:('a -> 'b t) Js.Fn.arity1 -> 'a t -> 'b t -``` -Bind the contained value using the given function - -If `'a Js.undefined` contains a value, that value is unwrapped, mapped to a `'b` using the given function `a' -> 'b`, then wrapped back up and returned as `'b Js.undefined` - -```ocaml -let maybeGreetWorld (maybeGreeting: string Js.undefined) = - Js.Undefined.bind maybeGreeting ~f:(fun greeting -> greeting ^ " world!") -``` -``` -val iter : f:('a -> unit) Js.Fn.arity1 -> 'a t -> unit -``` -Iterates over the contained value with the given function - -If `'a Js.undefined` contains a value, that value is unwrapped and applied to the given function. - -```ocaml -let maybeSay (maybeMessage: string Js.undefined) = - Js.Undefined.iter maybeMessage ~f:(fun message -> Js.log message) -``` -``` -val fromOption : 'a option -> 'a t -``` -Maps `'a option` to `'a Js.undefined` - - - -
Some a -> return a -
None -> empty -
- -``` -val toOption : 'a t -> 'a option -``` -Maps `'a Js.undefined` to `'a option` - - - -
return a -> Some a -
empty -> None -
diff --git a/docs/api/re/melange/Js-WeakMap.md b/docs/api/re/melange/Js-WeakMap.md deleted file mode 100644 index a997042d8..000000000 --- a/docs/api/re/melange/Js-WeakMap.md +++ /dev/null @@ -1,25 +0,0 @@ - -# Module `Js.WeakMap` - -Bindings to functions in `WeakMap` - -ES6 WeakMap API - -``` -type ('k, 'v) t -``` -``` -val make : unit -> ('k, 'v) t -``` -``` -val get : key:'k Js.dict -> ('k, 'v) t -> 'v option -``` -``` -val has : key:'k Js.dict -> ('k, 'v) t -> bool -``` -``` -val set : key:'k Js.dict -> value:'v -> ('k, 'v) t -> ('k, 'v) t -``` -``` -val delete : key:'k Js.dict -> ('k, 'v) t -> bool -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js-WeakSet.md b/docs/api/re/melange/Js-WeakSet.md deleted file mode 100644 index a7f07d2ea..000000000 --- a/docs/api/re/melange/Js-WeakSet.md +++ /dev/null @@ -1,22 +0,0 @@ - -# Module `Js.WeakSet` - -Bindings to functions in `WeakSet` - -ES6 WeakSet API - -``` -type 'a t -``` -``` -val make : unit -> 'a t -``` -``` -val add : value:'a Js.dict -> 'a t -> 'a t -``` -``` -val delete : value:'a Js.dict -> 'a t -> bool -``` -``` -val has : value:'a Js.dict -> 'a t -> bool -``` \ No newline at end of file diff --git a/docs/api/re/melange/Js.md b/docs/api/re/melange/Js.md deleted file mode 100644 index 06b1fd244..000000000 --- a/docs/api/re/melange/Js.md +++ /dev/null @@ -1,320 +0,0 @@ - -# Module `Js` - -``` -type +'a null -``` -A value of this type can be either `null` or `'a`. This type is the same as type `t` in [`Null`](./Js-Null.md) - -``` -type +'a undefined -``` -A value of this type can be either `undefined` or `'a`. This type is the same as type `t` in [`Undefined`](./Js-Undefined.md) - -``` -type +'a nullable -``` -A value of this type can be `undefined`, `null` or `'a`. This type is the same as type `t` n [`Nullable`](./Js-Nullable.md) - -``` -type re -``` -The type for JavaScript `RegExp` - -``` -type 'a dict -``` -The type for a simple key-value dictionary abstraction over native JavaScript objects - -``` -type 'a iterator -``` -The type for JavaScript iterators - -``` -type 'a array_like -``` -The type for array-like objects in JavaScript - -``` -type bigint -``` -The type for JavaScript BigInt - -``` -type +'a promise -``` -The type for JavaScript Promise - -``` -type blob -``` -The type for JavaScript [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) - -``` -type file -``` -The type for JavaScript [File](https://developer.mozilla.org/en-US/docs/Web/API/File) - -``` -type arrayBuffer -``` -``` -type int8Array -``` -``` -type uint8Array -``` -``` -type uint8ClampedArray -``` -``` -type int16Array -``` -``` -type uint16Array -``` -``` -type int32Array -``` -``` -type uint32Array -``` -``` -type float32Array -``` -``` -type float64Array -``` -``` -val toOption : 'a nullable -> 'a option -``` -``` -val undefinedToOption : 'a undefined -> 'a option -``` -``` -val nullToOption : 'a null -> 'a option -``` -``` -val isNullable : 'a nullable -> bool -``` -``` -val import : 'a -> 'a promise -``` -TODO(anmonteiro): document - -``` -val testAny : 'a -> bool -``` -The same as [`isNullable`](./#val-isNullable) except that it is more permissive on the types of input - -``` -val null : 'a null -``` -The same as `empty` in [`Js.Null`](./Js-Null.md) will be compiled as `null` - -``` -val undefined : 'a undefined -``` -The same as `empty` [`Js.Undefined`](./Js-Undefined.md) will be compiled as `undefined` - -``` -val typeof : 'a -> string -``` -`typeof x` will be compiled as `typeof x` in JS Please consider functions in [`Types`](./Js-Types.md) for a type safe way of reflection - -``` -val log : 'a -> unit -``` -A convenience function to log everything - -``` -val log2 : 'a -> 'b -> unit -``` -``` -val log3 : 'a -> 'b -> 'c -> unit -``` -``` -val log4 : 'a -> 'b -> 'c -> 'd -> unit -``` -``` -val logMany : 'a array -> unit -``` -A convenience function to log more than 4 arguments - -``` -val eqNull : 'a -> 'a null -> bool -``` -``` -val eqUndefined : 'a -> 'a undefined -> bool -``` -``` -val eqNullable : 'a -> 'a nullable -> bool -``` - -##### Operators - -``` -val unsafe_lt : 'a -> 'a -> bool -``` -`unsafe_lt a b` will be compiled as `a < b`. It is marked as unsafe, since it is impossible to give a proper semantics for comparision which applies to any type - -``` -val unsafe_le : 'a -> 'a -> bool -``` -`unsafe_le a b` will be compiled as `a <= b`. See also [`unsafe_lt`](./#val-unsafe_lt) - -``` -val unsafe_gt : 'a -> 'a -> bool -``` -`unsafe_gt a b` will be compiled as `a > b`. See also [`unsafe_lt`](./#val-unsafe_lt) - -``` -val unsafe_ge : 'a -> 'a -> bool -``` -`unsafe_ge a b` will be compiled as `a >= b`. See also [`unsafe_lt`](./#val-unsafe_lt) - -Types for JS objects - -``` -type 'a t -``` -This used to be mark a Js object type. - -``` -module Exn : sig ... end -``` -Utilities for dealing with Js exceptions - -``` -module String : sig ... end -``` -Bindings to the functions in `String.prototype` - -``` -module Null : sig ... end -``` -Utility functions on [`null`](./#type-null) - -``` -module Undefined : sig ... end -``` -Utility functions on [`undefined`](./#type-undefined) - -``` -module Nullable : sig ... end -``` -Utility functions on [`nullable`](./#type-nullable) - -``` -module Array : sig ... end -``` -Bindings to the functions in `Array.prototype` - -``` -module Re : sig ... end -``` -Bindings to the functions in `RegExp.prototype` - -``` -module Promise : sig ... end -``` -Bindings to JS `Promise` functions - -``` -module Date : sig ... end -``` -Bindings to the functions in JS's `Date.prototype` - -``` -module Dict : sig ... end -``` -Utility functions to treat a JS object as a dictionary - -``` -module Global : sig ... end -``` -Bindings to functions in the JS global namespace - -``` -module Json : sig ... end -``` -Utility functions to manipulate JSON values - -``` -module Math : sig ... end -``` -Bindings to the functions in the `Math` object - -``` -module Obj : sig ... end -``` -Utility functions on \`Js.t\` JS objects - -``` -module Typed_array : sig ... end -``` -Bindings to the functions in `TypedArray.prototype` - -``` -module Types : sig ... end -``` -Utility functions for runtime reflection on JS types - -``` -module Float : sig ... end -``` -Bindings to functions in JavaScript's `Number` that deal with floats - -``` -module Int : sig ... end -``` -Bindings to functions in JavaScript's `Number` that deal with ints - -``` -module Bigint : sig ... end -``` -Bindings to functions in JavaScript's `BigInt` - -``` -module Console : sig ... end -``` -``` -module Set : sig ... end -``` -Bindings to functions in `Set` - -``` -module WeakSet : sig ... end -``` -Bindings to functions in `WeakSet` - -``` -module Map : sig ... end -``` -Bindings to functions in `Map` - -``` -module WeakMap : sig ... end -``` -Bindings to functions in `WeakMap` - -``` -module Iterator : sig ... end -``` -Bindings to functions on `Iterator` - -``` -module Blob : sig ... end -``` -Bindings to Blob - -``` -module File : sig ... end -``` -Bindings to File - -``` -module FormData : sig ... end -``` -Bindings to FormData diff --git a/docs/api/re/melange/Node-Buffer.md b/docs/api/re/melange/Node-Buffer.md deleted file mode 100644 index 3488b30f6..000000000 --- a/docs/api/re/melange/Node-Buffer.md +++ /dev/null @@ -1,56 +0,0 @@ - -# Module `Node.Buffer` - -Node Buffer API - -``` -type t = Node.buffer -``` -``` -type encoding = [ -``` -``` -| `ascii -``` -``` -| `utf8 -``` -``` -| `utf16le -``` -``` -| `ucs2 -``` -``` -| `base64 -``` -``` -| `base64url -``` -``` -| `latin1 -``` -``` -| `binary -``` -``` -| `hex -``` -``` - ] -``` -``` -val isBuffer : 'a -> bool -``` -``` -val fromString : string -> t -``` -``` -val fromStringWithEncoding : string -> encoding:encoding -> t -``` -``` -val toString : ?encoding:encoding -> t -> string -``` -``` -val concat : t array -> t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Child_process.md b/docs/api/re/melange/Node-Child_process.md deleted file mode 100644 index 5a3630c8c..000000000 --- a/docs/api/re/melange/Node-Child_process.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Module `Node.Child_process` - -Node Child Process API - -``` -type option -``` -``` -val option : ?cwd:string -> ?encoding:string -> unit -> option -``` -``` -val execSync : string -> option -> string -``` -``` -type spawnResult -``` -``` -val spawnSync : string -> spawnResult -``` -``` -val readAs : - spawnResult -> - < pid : int - ; status : int Js.null - ; signal : string Js.null - ; stdout : Node.string_buffer Js.null - ; stderr : Node.string_buffer Js.null > - Js.t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Fs-Watch.md b/docs/api/re/melange/Node-Fs-Watch.md deleted file mode 100644 index 581d242fa..000000000 --- a/docs/api/re/melange/Node-Fs-Watch.md +++ /dev/null @@ -1,33 +0,0 @@ - -# Module `Fs.Watch` - -``` -type t -``` -``` -type config -``` -``` -val config : - ?persistent:bool -> - ?recursive:bool -> - ?encoding:Js.String.t -> - unit -> - config -``` -``` -val watch : string -> ?config:config -> unit -> t -``` -there is no need to accept listener, since we return a `watcher` back it can register event listener there. Currently we introduce a type `string_buffer`, for the `filename`, it will be `Buffer` when the encoding is `` `utf8 ``. This is dependent type which can be tracked by GADT in some way, but to make things simple, let's just introduce an or type - -``` -val on : - t -> - f: - [ `change of (string -> Node.string_buffer -> unit) Js.Fn.arity2 - | `error of unit Js.Fn.arity0 ] -> - t -``` -``` -val close : t -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Fs.md b/docs/api/re/melange/Node-Fs.md deleted file mode 100644 index b437a848f..000000000 --- a/docs/api/re/melange/Node-Fs.md +++ /dev/null @@ -1,110 +0,0 @@ - -# Module `Node.Fs` - -Node FS API - -see [https://blogs.janestreet.com/a-and-a/](https://blogs.janestreet.com/a-and-a/) refernce documentation -``` -val readdirSync : string -> string array -``` -Most fs functions let you omit the callback argument. If you do, a default callback is used that rethrows errors. To get a trace to the original call site, set the \`NODE\_DEBUG\` environment variable. - -``` -val renameSync : string -> string -> unit -``` -``` -type fd = private int -``` -``` -type path = string -``` -The relative path to a filename can be used. Remember, however, that this path will be relative to `process.cwd()`. - -``` -module Watch : sig ... end -``` -``` -val ftruncateSync : fd -> int -> unit -``` -``` -val truncateSync : string -> int -> unit -``` -``` -val chownSync : string -> uid:int -> gid:int -> unit -``` -``` -val fchownSync : fd -> uid:int -> gid:int -> unit -``` -``` -val readlinkSync : string -> string -``` -``` -val unlinkSync : string -> unit -``` -``` -val rmdirSync : string -> unit -``` -``` -val openSync : - path -> - [ `Read - | `Read_write - | `Read_write_sync - | `Write - | `Write_fail_if_exists - | `Write_read - | `Write_read_fail_if_exists - | `Append - | `Append_fail_if_exists - | `Append_read - | `Append_read_fail_if_exists ] -> - unit -``` -``` -type encoding = [ -``` -``` -| `hex -``` -``` -| `utf8 -``` -``` -| `ascii -``` -``` -| `latin1 -``` -``` -| `base64 -``` -``` -| `ucs2 -``` -``` -| `base64 -``` -``` -| `binary -``` -``` -| `utf16le -``` -``` - ] -``` -``` -val readFileSync : string -> encoding -> string -``` -``` -val readFileAsUtf8Sync : string -> string -``` -``` -val existsSync : string -> bool -``` -``` -val writeFileSync : string -> string -> encoding -> unit -``` -``` -val writeFileAsUtf8Sync : string -> string -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Module.md b/docs/api/re/melange/Node-Module.md deleted file mode 100644 index 26dbe1439..000000000 --- a/docs/api/re/melange/Node-Module.md +++ /dev/null @@ -1,8 +0,0 @@ - -# Module `Node.Module` - -Node Module API - -``` -val module_ : < __cache : Node.node_module Js.Dict.t > Js.t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Path.md b/docs/api/re/melange/Node-Path.md deleted file mode 100644 index 0d7ebfd71..000000000 --- a/docs/api/re/melange/Node-Path.md +++ /dev/null @@ -1,56 +0,0 @@ - -# Module `Node.Path` - -Node Path API - -``` -val basename : string -> string -``` -``` -val basename_ext : string -> string -> string -``` -``` -val delimiter : string -``` -``` -val dirname : string -> string -``` -``` -val dirname_ext : string -> string -> string -``` -``` -type pathObject = - < dir : string - ; root : string - ; base : string - ; name : string - ; ext : string > - Js.t -``` -``` -val format : pathObject -> string -``` -``` -val isAbsolute : string -> bool -``` -``` -val join2 : string -> string -> string -``` -``` -val join : string array -> string -``` -``` -val normalize : string -> string -``` -``` -val parse : string -> pathObject -``` -``` -val relative : from:string -> to_:string -> unit -> string -``` -``` -val resolve : string -> string -> string -``` -``` -val sep : string -``` \ No newline at end of file diff --git a/docs/api/re/melange/Node-Process.md b/docs/api/re/melange/Node-Process.md deleted file mode 100644 index f2714be7b..000000000 --- a/docs/api/re/melange/Node-Process.md +++ /dev/null @@ -1,38 +0,0 @@ - -# Module `Node.Process` - -``` -type t = - < argv : string array - ; arch : string - ; abort : unit Js.OO.Meth.arity0 - ; chdir : (string -> unit) Js.OO.Meth.arity1 - ; cwd : string Js.OO.Meth.arity0 - ; disconnect : unit Js.OO.Meth.arity0 - ; platform : string - ; env : string Js.Dict.t > - Js.t -``` -``` -val process : t -``` -``` -val argv : string array -``` -``` -val exit : int -> 'a -``` -``` -val cwd : unit -> string -``` -``` -val uptime : t -> unit -> float -``` -The process.uptime() method returns the number of seconds the current Node.js process has been running.) - -``` -val putEnvVar : string -> string -> unit -``` -``` -val deleteEnvVar : string -> unit -``` \ No newline at end of file diff --git a/docs/api/re/melange/Node.md b/docs/api/re/melange/Node.md deleted file mode 100644 index 2730c44a9..000000000 --- a/docs/api/re/melange/Node.md +++ /dev/null @@ -1,73 +0,0 @@ - -# Module `Node` - -``` -type node_exports -``` -``` -type node_module = - < id : string - ; exports : node_exports - ; parent : node_module Js.nullable - ; filename : string - ; loaded : bool - ; children : node_module array - ; paths : string array > - Js.t -``` -``` -type node_require = - < main : node_module Js.undefined - ; resolve : (string -> string) Js.Fn.arity1 > - Js.t -``` -``` -type string_buffer -``` -``` -type buffer -``` -``` -type _ string_buffer_kind = -``` -``` -| String : string string_buffer_kind -``` -``` -| Buffer : buffer string_buffer_kind -``` -``` - -``` -``` -val test : string_buffer -> 't string_buffer_kind * 't -``` -We expect a good inliner will eliminate such boxing in the future - -``` -module Path : sig ... end -``` -Node Path API - -``` -module Fs : sig ... end -``` -Node FS API - -``` -module Process : sig ... end -``` -``` -module Module : sig ... end -``` -Node Module API - -``` -module Buffer : sig ... end -``` -Node Buffer API - -``` -module Child_process : sig ... end -``` -Node Child Process API diff --git a/docs/api/re/melange/Stdlib-Arg.md b/docs/api/re/melange/Stdlib-Arg.md deleted file mode 100644 index 9688b86ce..000000000 --- a/docs/api/re/melange/Stdlib-Arg.md +++ /dev/null @@ -1,261 +0,0 @@ - -# Module `Stdlib.Arg` - -Parsing of command line arguments. - -This module provides a general mechanism for extracting options and arguments from the command line to the program. For example: - -```ocaml - let usage_msg = "append [-verbose] [] ... -o " - let verbose = ref false - let input_files = ref [] - let output_file = ref "" - - let anon_fun filename = - input_files := filename::!input_files - - let speclist = - [("-verbose", Arg.Set verbose, "Output debug information"); - ("-o", Arg.Set_string output_file, "Set output file name")] - - let () = - Arg.parse speclist anon_fun usage_msg; - (* Main functionality here *) -``` -Syntax of command lines: A keyword is a character string starting with a `-`. An option is a keyword alone or followed by an argument. The types of keywords are: `Unit`, `Bool`, `Set`, `Clear`, `String`, `Set_string`, `Int`, `Set_int`, `Float`, `Set_float`, `Tuple`, `Symbol`, `Rest`, `Rest_all` and `Expand`. - -`Unit`, `Set` and `Clear` keywords take no argument. - -A `Rest` or `Rest_all` keyword takes the remainder of the command line as arguments. (More explanations below.) - -Every other keyword takes the following word on the command line as argument. For compatibility with GNU getopt\_long, `keyword=arg` is also allowed. Arguments not preceded by a keyword are called anonymous arguments. - -Examples (`cmd` is assumed to be the command name): - -- `cmd -flag `(a unit option) -- `cmd -int 1 `(an int option with argument `1`) -- `cmd -string foobar `(a string option with argument `"foobar"`) -- `cmd -float 12.34 `(a float option with argument `12.34`) -- `cmd a b c `(three anonymous arguments: `"a"`, `"b"`, and `"c"`) -- `cmd a b -- c d `(two anonymous arguments and a rest option with two arguments) -`Rest` takes a function that is called repeatedly for each remaining command line argument. `Rest_all` takes a function that is called once, with the list of all remaining arguments. - -Note that if no arguments follow a `Rest` keyword then the function is not called at all whereas the function for a `Rest_all` keyword is called with an empty list. - -alert unsynchronized\_access The Arg module relies on a mutable global state, parsing functions should only be called from a single domain. -``` -type spec = -``` -``` -| Unit of unit -> unit -``` -Call the function with unit argument - -``` -| Bool of bool -> unit -``` -Call the function with a bool argument - -``` -| Set of bool ref -``` -Set the reference to true - -``` -| Clear of bool ref -``` -Set the reference to false - -``` -| String of string -> unit -``` -Call the function with a string argument - -``` -| Set_string of string ref -``` -Set the reference to the string argument - -``` -| Int of int -> unit -``` -Call the function with an int argument - -``` -| Set_int of int ref -``` -Set the reference to the int argument - -``` -| Float of float -> unit -``` -Call the function with a float argument - -``` -| Set_float of float ref -``` -Set the reference to the float argument - -``` -| Tuple of spec list -``` -Take several arguments according to the spec list - -``` -| Symbol of string list * string -> unit -``` -Take one of the symbols as argument and call the function with the symbol - -``` -| Rest of string -> unit -``` -Stop interpreting keywords and call the function with each remaining argument - -``` -| Rest_all of string list -> unit -``` -Stop interpreting keywords and call the function with all remaining arguments - -``` -| Expand of string -> string array -``` -If the remaining arguments to process are of the form `["-foo"; "arg"] @ rest` where "foo" is registered as `Expand f`, then the arguments `f "arg" @ rest` are processed. Only allowed in `parse_and_expand_argv_dynamic`. - -``` - -``` -The concrete type describing the behavior associated with a keyword. - -``` -type key = string -``` -``` -type doc = string -``` -``` -type usage_msg = string -``` -``` -type anon_fun = string -> unit -``` -``` -val parse : (key * spec * doc) list -> anon_fun -> usage_msg -> unit -``` -`Arg.parse speclist anon_fun usage_msg` parses the command line. `speclist` is a list of triples `(key, spec, doc)`. `key` is the option keyword, it must start with a `'-'` character. `spec` gives the option type and the function to call when this option is found on the command line. `doc` is a one-line description of this option. `anon_fun` is called on anonymous arguments. The functions in `spec` and `anon_fun` are called in the same order as their arguments appear on the command line. - -If an error occurs, `Arg.parse` exits the program, after printing to standard error an error message as follows: - -- The reason for the error: unknown option, invalid or missing argument, etc. -- `usage_msg` -- The list of options, each followed by the corresponding `doc` string. Beware: options that have an empty `doc` string will not be included in the list. -For the user to be able to specify anonymous arguments starting with a `-`, include for example `("-", String anon_fun, doc)` in `speclist`. - -By default, `parse` recognizes two unit options, `-help` and `--help`, which will print to standard output `usage_msg` and the list of options, and exit the program. You can override this behaviour by specifying your own `-help` and `--help` options in `speclist`. - -``` -val parse_dynamic : - (key * spec * doc) list ref -> - anon_fun -> - usage_msg -> - unit -``` -Same as [`Arg.parse`](./#val-parse), except that the `speclist` argument is a reference and may be updated during the parsing. A typical use for this feature is to parse command lines of the form: - -- command subcommand `options` where the list of options depends on the value of the subcommand argument. -since 4.01 -``` -val parse_argv : - ?current:int ref -> - string array -> - (key * spec * doc) list -> - anon_fun -> - usage_msg -> - unit -``` -`Arg.parse_argv ~current args speclist anon_fun usage_msg` parses the array `args` as if it were the command line. It uses and updates the value of `~current` (if given), or [`Arg.current`](./#val-current). You must set it before calling `parse_argv`. The initial value of `current` is the index of the program name (argument 0) in the array. If an error occurs, `Arg.parse_argv` raises [`Arg.Bad`](./#exception-Bad) with the error message as argument. If option `-help` or `--help` is given, `Arg.parse_argv` raises [`Arg.Help`](./#exception-Help) with the help message as argument. - -``` -val parse_argv_dynamic : - ?current:int ref -> - string array -> - (key * spec * doc) list ref -> - anon_fun -> - string -> - unit -``` -Same as [`Arg.parse_argv`](./#val-parse_argv), except that the `speclist` argument is a reference and may be updated during the parsing. See [`Arg.parse_dynamic`](./#val-parse_dynamic). - -since 4.01 -``` -val parse_and_expand_argv_dynamic : - int ref -> - string array ref -> - (key * spec * doc) list ref -> - anon_fun -> - string -> - unit -``` -Same as [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic), except that the `argv` argument is a reference and may be updated during the parsing of `Expand` arguments. See [`Arg.parse_argv_dynamic`](./#val-parse_argv_dynamic). - -since 4.05 -``` -val parse_expand : (key * spec * doc) list -> anon_fun -> usage_msg -> unit -``` -Same as [`Arg.parse`](./#val-parse), except that the `Expand` arguments are allowed and the [`current`](./#val-current) reference is not updated. - -since 4.05 -``` -exception Help of string -``` -Raised by `Arg.parse_argv` when the user asks for help. - -``` -exception Bad of string -``` -Functions in `spec` or `anon_fun` can raise `Arg.Bad` with an error message to reject invalid arguments. `Arg.Bad` is also raised by [`Arg.parse_argv`](./#val-parse_argv) in case of an error. - -``` -val usage : (key * spec * doc) list -> usage_msg -> unit -``` -`Arg.usage speclist usage_msg` prints to standard error an error message that includes the list of valid options. This is the same message that [`Arg.parse`](./#val-parse) prints in case of error. `speclist` and `usage_msg` are the same as for [`Arg.parse`](./#val-parse). - -``` -val usage_string : (key * spec * doc) list -> usage_msg -> string -``` -Returns the message that would have been printed by [`Arg.usage`](./#val-usage), if provided with the same parameters. - -``` -val align : ?limit:int -> (key * spec * doc) list -> (key * spec * doc) list -``` -Align the documentation strings by inserting spaces at the first alignment separator (tab or, if tab is not found, space), according to the length of the keyword. Use a alignment separator as the first character in a doc string if you want to align the whole string. The doc strings corresponding to `Symbol` arguments are aligned on the next line. - -parameter limit options with keyword and message longer than limit will not be used to compute the alignment. -``` -val current : int ref -``` -Position (in [`Sys.argv`](./Stdlib-Sys.md#val-argv)) of the argument being processed. You can change this value, e.g. to force [`Arg.parse`](./#val-parse) to skip some arguments. [`Arg.parse`](./#val-parse) uses the initial value of [`Arg.current`](./#val-current) as the index of argument 0 (the program name) and starts parsing arguments at the next element. - -``` -val read_arg : string -> string array -``` -`Arg.read_arg file` reads newline-terminated command line arguments from file `file`. - -since 4.05 -``` -val read_arg0 : string -> string array -``` -Identical to [`Arg.read_arg`](./#val-read_arg) but assumes null character terminated command line arguments. - -since 4.05 -``` -val write_arg : string -> string array -> unit -``` -`Arg.write_arg file args` writes the arguments `args` newline-terminated into the file `file`. If any of the arguments in `args` contains a newline, use [`Arg.write_arg0`](./#val-write_arg0) instead. - -since 4.05 -``` -val write_arg0 : string -> string array -> unit -``` -Identical to [`Arg.write_arg`](./#val-write_arg) but uses the null character for terminator instead of newline. - -since 4.05 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Array.md b/docs/api/re/melange/Stdlib-Array.md deleted file mode 100644 index 9653f6b3d..000000000 --- a/docs/api/re/melange/Stdlib-Array.md +++ /dev/null @@ -1,373 +0,0 @@ - -# Module `Stdlib.Array` - -Array operations. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a array -``` -An alias for the type of arrays. - -``` -val length : 'a array -> int -``` -Return the length (number of elements) of the given array. - -``` -val get : 'a array -> int -> 'a -``` -`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val set : 'a array -> int -> 'a -> unit -``` -`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. -``` -val make : int -> 'a -> 'a array -``` -`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val create_float : int -> float array -``` -`create_float n` returns a fresh float array of length `n`, with uninitialized data. - -since 4.03 -``` -val init : int -> (int -> 'a) -> 'a array -``` -`init n f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -``` -val make_matrix : int -> int -> 'a -> 'a array array -``` -`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val init_matrix : int -> int -> (int -> int -> 'a) -> 'a array array -``` -`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -since 5.2 -``` -val append : 'a array -> 'a array -> 'a array -``` -`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. -``` -val concat : 'a array list -> 'a array -``` -Same as [`append`](./#val-append), but concatenates a list of arrays. - -``` -val sub : 'a array -> int -> int -> 'a array -``` -`sub a pos len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. -``` -val copy : 'a array -> 'a array -``` -`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. - -``` -val fill : 'a array -> int -> int -> 'a -> unit -``` -`fill a pos len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. -``` -val blit : 'a array -> int -> 'a array -> int -> int -> unit -``` -`blit src src_pos dst dst_pos len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. -``` -val to_list : 'a array -> 'a list -``` -`to_list a` returns the list of all the elements of `a`. - -``` -val of_list : 'a list -> 'a array -``` -`of_list l` returns a fresh array containing the elements of `l`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. - -## Iterators - -``` -val iter : ('a -> unit) -> 'a array -> unit -``` -`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. - -``` -val iteri : (int -> 'a -> unit) -> 'a array -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val map : ('a -> 'b) -> 'a array -> 'b array -``` -`map f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. - -``` -val map_inplace : ('a -> 'a) -> 'a array -> unit -``` -`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. - -since 5.1 -``` -val mapi : (int -> 'a -> 'b) -> 'a array -> 'b array -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val mapi_inplace : (int -> 'a -> 'a) -> 'a array -> unit -``` -Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -since 5.1 -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a array -> 'acc -``` -`fold_left f init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. - -``` -val fold_left_map : - ('acc -> 'a -> 'acc * 'b) -> - 'acc -> - 'a array -> - 'acc * 'b array -``` -`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. - -since 4.13 -``` -val fold_right : ('a -> 'acc -> 'acc) -> 'a array -> 'acc -> 'acc -``` -`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. - - -## Iterators on two arrays - -``` -val iter2 : ('a -> 'b -> unit) -> 'a array -> 'b array -> unit -``` -`iter2 f a b` applies function `f` to all the elements of `a` and `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) -``` -val map2 : ('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array -``` -`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) - -## Array scanning - -``` -val for_all : ('a -> bool) -> 'a array -> bool -``` -`for_all f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. - -since 4.03 -``` -val exists : ('a -> bool) -> 'a array -> bool -``` -`exists f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. - -since 4.03 -``` -val for_all2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val exists2 : ('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val mem : 'a -> 'a array -> bool -``` -`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). - -since 4.03 -``` -val memq : 'a -> 'a array -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. - -since 4.03 -``` -val find_opt : ('a -> bool) -> 'a array -> 'a option -``` -`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. - -since 4.13 -``` -val find_index : ('a -> bool) -> 'a array -> int option -``` -`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : ('a -> 'b option) -> 'a array -> 'b option -``` -`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.13 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a array -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 - -## Arrays of pairs - -``` -val split : ('a * 'b) array -> 'a array * 'b array -``` -`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. - -since 4.13 -``` -val combine : 'a array -> 'b array -> ('a * 'b) array -``` -`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. - -since 4.13 - -## Sorting and shuffling - -``` -val sort : ('a -> 'a -> int) -> 'a array -> unit -``` -Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. - -The current implementation uses Heap Sort. It runs in constant stack space. - -Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : - -- `cmp x y` \> 0 if and only if `cmp y x` \< 0 -- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 -When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : - -- `cmp a.(i) a.(j)` \>= 0 if i \>= j -``` -val stable_sort : ('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. - -The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). - -``` -val fast_sort : ('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val shuffle : rand:(int -> int) -> 'a array -> unit -``` -`shuffle rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. - -`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). - -since 5.2 - -## Arrays and Sequences - -``` -val to_seq : 'a array -> 'a Seq.t -``` -Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : 'a array -> (int * 'a) Seq.t -``` -Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a array -``` -Create an array from the generator - -since 4.07 - -## Arrays and concurrency safety - -Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let a = Array.make size 1 -let d1 = Domain.spawn (fun () -> - Array.iteri (fun i x -> a.(i) <- x + 1) a -) -let d2 = Domain.spawn (fun () -> - Array.iteri (fun i x -> a.(i) <- 2 * x + 1) a -) -let () = Domain.join d1; Domain.join d2 -``` -After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). - - -### Float arrays - -Float arrays have two supplementary caveats in the presence of data races. - -First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. - -For instance, at the end of - -```ocaml - let zeros = Array.make size 0. -let max_floats = Array.make size Float.max_float -let res = Array.copy zeros -let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) -let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) -let () = Domain.join d1; Domain.join d2 -``` -the `res` array might contain values that are neither `0.` nor `max_float`. - -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/re/melange/Stdlib-ArrayLabels.md b/docs/api/re/melange/Stdlib-ArrayLabels.md deleted file mode 100644 index 22c66dcff..000000000 --- a/docs/api/re/melange/Stdlib-ArrayLabels.md +++ /dev/null @@ -1,383 +0,0 @@ - -# Module `Stdlib.ArrayLabels` - -Array operations. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a array -``` -An alias for the type of arrays. - -``` -val length : 'a array -> int -``` -Return the length (number of elements) of the given array. - -``` -val get : 'a array -> int -> 'a -``` -`get a n` returns the element number `n` of array `a`. The first element has number 0. The last element has number `length a - 1`. You can also write `a.(n)` instead of `get a n`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val set : 'a array -> int -> 'a -> unit -``` -`set a n x` modifies array `a` in place, replacing element number `n` with `x`. You can also write `a.(n) <- x` instead of `set a n x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to length a - 1. -``` -val make : int -> 'a -> 'a array -``` -`make n x` returns a fresh array of length `n`, initialized with `x`. All the elements of this new array are initially physically equal to `x` (in the sense of the `==` predicate). Consequently, if `x` is mutable, it is shared among all elements of the array, and modifying `x` through one of the array entries will modify all other entries at the same time. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the value of x is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val create_float : int -> float array -``` -`create_float n` returns a fresh float array of length `n`, with uninitialized data. - -since 4.03 -``` -val init : int -> f:(int -> 'a) -> 'a array -``` -`init n ~f` returns a fresh array of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n ~f` tabulates the results of `f` applied in order to the integers `0` to `n-1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -``` -val make_matrix : dimx:int -> dimy:int -> 'a -> 'a array array -``` -`make_matrix ~dimx ~dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`. All the elements of this new matrix are initially physically equal to `e`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the value of e is a floating-point number, then the maximum size is only Sys.max\_array\_length / 2. -``` -val init_matrix : - dimx:int -> - dimy:int -> - f:(int -> int -> 'a) -> - 'a array array -``` -`init_matrix ~dimx ~dimy ~f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. The element (`x,y`) of a matrix `m` is accessed with the notation `m.(x).(y)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_array\_length. If the return type of f is float, then the maximum size is only Sys.max\_array\_length / 2. -since 5.2 -``` -val append : 'a array -> 'a array -> 'a array -``` -`append v1 v2` returns a fresh array containing the concatenation of the arrays `v1` and `v2`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_array\_length. -``` -val concat : 'a array list -> 'a array -``` -Same as [`append`](./#val-append), but concatenates a list of arrays. - -``` -val sub : 'a array -> pos:int -> len:int -> 'a array -``` -`sub a ~pos ~len` returns a fresh array of length `len`, containing the elements number `pos` to `pos + len - 1` of array `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. -``` -val copy : 'a array -> 'a array -``` -`copy a` returns a copy of `a`, that is, a fresh array containing the same elements as `a`. - -``` -val fill : 'a array -> pos:int -> len:int -> 'a -> unit -``` -`fill a ~pos ~len x` modifies the array `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. -``` -val blit : - src:'a array -> - src_pos:int -> - dst:'a array -> - dst_pos:int -> - len:int -> - unit -``` -`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from array `src`, starting at element number `src_pos`, to array `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. -``` -val to_list : 'a array -> 'a list -``` -`to_list a` returns the list of all the elements of `a`. - -``` -val of_list : 'a list -> 'a array -``` -`of_list l` returns a fresh array containing the elements of `l`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_array\_length. - -## Iterators - -``` -val iter : f:('a -> unit) -> 'a array -> unit -``` -`iter ~f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. - -``` -val iteri : f:(int -> 'a -> unit) -> 'a array -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val map : f:('a -> 'b) -> 'a array -> 'b array -``` -`map ~f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. - -``` -val map_inplace : f:('a -> 'a) -> 'a array -> unit -``` -`map_inplace ~f a` applies function `f` to all elements of `a`, and updates their values in place. - -since 5.1 -``` -val mapi : f:(int -> 'a -> 'b) -> 'a array -> 'b array -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val mapi_inplace : f:(int -> 'a -> 'a) -> 'a array -> unit -``` -Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -since 5.1 -``` -val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a array -> 'acc -``` -`fold_left ~f ~init a` computes `f (... (f (f init a.(0)) a.(1)) ...) a.(n-1)`, where `n` is the length of the array `a`. - -``` -val fold_left_map : - f:('acc -> 'a -> 'acc * 'b) -> - init:'acc -> - 'a array -> - 'acc * 'b array -``` -`fold_left_map` is a combination of [`fold_left`](./#val-fold_left) and [`map`](./#val-map) that threads an accumulator through calls to `f`. - -since 4.13 -``` -val fold_right : f:('a -> 'acc -> 'acc) -> 'a array -> init:'acc -> 'acc -``` -`fold_right ~f a ~init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the array `a`. - - -## Iterators on two arrays - -``` -val iter2 : f:('a -> 'b -> unit) -> 'a array -> 'b array -> unit -``` -`iter2 ~f a b` applies function `f` to all the elements of `a` and `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) -``` -val map2 : f:('a -> 'b -> 'c) -> 'a array -> 'b array -> 'c array -``` -`map2 ~f a b` applies function `f` to all the elements of `a` and `b`, and builds an array with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the arrays are not the same size. -since 4.03 (4.05 in ArrayLabels) - -## Array scanning - -``` -val for_all : f:('a -> bool) -> 'a array -> bool -``` -`for_all ~f [|a1; ...; an|]` checks if all elements of the array satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. - -since 4.03 -``` -val exists : f:('a -> bool) -> 'a array -> bool -``` -`exists ~f [|a1; ...; an|]` checks if at least one element of the array satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. - -since 4.03 -``` -val for_all2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val exists2 : f:('a -> 'b -> bool) -> 'a array -> 'b array -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two arrays have different lengths. -since 4.11 -``` -val mem : 'a -> set:'a array -> bool -``` -`mem a ~set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). - -since 4.03 -``` -val memq : 'a -> set:'a array -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. - -since 4.03 -``` -val find_opt : f:('a -> bool) -> 'a array -> 'a option -``` -`find_opt ~f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. - -since 4.13 -``` -val find_index : f:('a -> bool) -> 'a array -> int option -``` -`find_index ~f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : f:('a -> 'b option) -> 'a array -> 'b option -``` -`find_map ~f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.13 -``` -val find_mapi : f:(int -> 'a -> 'b option) -> 'a array -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 - -## Arrays of pairs - -``` -val split : ('a * 'b) array -> 'a array * 'b array -``` -`split [|(a1,b1); ...; (an,bn)|]` is `([|a1; ...; an|], [|b1; ...; bn|])`. - -since 4.13 -``` -val combine : 'a array -> 'b array -> ('a * 'b) array -``` -`combine [|a1; ...; an|] [|b1; ...; bn|]` is `[|(a1,b1); ...; (an,bn)|]`. Raise `Invalid_argument` if the two arrays have different lengths. - -since 4.13 - -## Sorting and shuffling - -``` -val sort : cmp:('a -> 'a -> int) -> 'a array -> unit -``` -Sort an array in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. - -The current implementation uses Heap Sort. It runs in constant stack space. - -Specification of the comparison function: Let `a` be the array and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : - -- `cmp x y` \> 0 if and only if `cmp y x` \< 0 -- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 -When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : - -- `cmp a.(i) a.(j)` \>= 0 if i \>= j -``` -val stable_sort : cmp:('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. - -The current implementation uses Merge Sort. It uses a temporary array of length `n/2`, where `n` is the length of the array. It is usually faster than the current implementation of [`sort`](./#val-sort). - -``` -val fast_sort : cmp:('a -> 'a -> int) -> 'a array -> unit -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val shuffle : rand:(int -> int) -> 'a array -> unit -``` -`shuffle ~rand a` randomly permutes `a`'s element using `rand` for randomness. The distribution of permutations is uniform. - -`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). - -since 5.2 - -## Arrays and Sequences - -``` -val to_seq : 'a array -> 'a Seq.t -``` -Iterate on the array, in increasing order. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : 'a array -> (int * 'a) Seq.t -``` -Iterate on the array, in increasing order, yielding indices along elements. Modifications of the array during iteration will be reflected in the sequence. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a array -``` -Create an array from the generator - -since 4.07 - -## Arrays and concurrency safety - -Care must be taken when concurrently accessing arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let a = ArrayLabels.make size 1 -let d1 = Domain.spawn (fun () -> - ArrayLabels.iteri ~f:(fun i x -> a.(i) <- x + 1) a -) -let d2 = Domain.spawn (fun () -> - ArrayLabels.iteri ~f:(fun i x -> a.(i) <- 2 * x + 1) a -) -let () = Domain.join d1; Domain.join d2 -``` -After executing this code, each field of the array `a` is either `2`, `3`, `4` or `5`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location (with a few exceptions for float arrays). - - -### Float arrays - -Float arrays have two supplementary caveats in the presence of data races. - -First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. - -For instance, at the end of - -```ocaml - let zeros = Array.make size 0. -let max_floats = Array.make size Float.max_float -let res = Array.copy zeros -let d1 = Domain.spawn (fun () -> Array.blit zeros 0 res 0 size) -let d2 = Domain.spawn (fun () -> Array.blit max_floats 0 res 0 size) -let () = Domain.join d1; Domain.join d2 -``` -the `res` array might contain values that are neither `0.` nor `max_float`. - -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/re/melange/Stdlib-Atomic.md b/docs/api/re/melange/Stdlib-Atomic.md deleted file mode 100644 index 1fc036d20..000000000 --- a/docs/api/re/melange/Stdlib-Atomic.md +++ /dev/null @@ -1,144 +0,0 @@ - -# Module `Stdlib.Atomic` - -Atomic references. - -See [the examples](./#examples) below. See 'Memory model: The hard bits' chapter in the manual. - -since 4.12 -``` -type !'a t -``` -An atomic (mutable) reference to a value of type `'a`. - -``` -val make : 'a -> 'a t -``` -Create an atomic reference. - -Create an atomic reference that is alone on a cache line. It occupies 4-16x the memory of one allocated with `make v`. - -The primary purpose is to prevent false-sharing and the resulting performance degradation. When a CPU performs an atomic operation, it temporarily takes ownership of an entire cache line that contains the atomic reference. If multiple atomic references share the same cache line, modifying these disjoint memory regions simultaneously becomes impossible, which can create a bottleneck. Hence, as a general guideline, if an atomic reference is experiencing contention, assigning it its own cache line may enhance performance. - -``` -val get : 'a t -> 'a -``` -Get the current value of the atomic reference. - -``` -val set : 'a t -> 'a -> unit -``` -Set a new value for the atomic reference. - -``` -val exchange : 'a t -> 'a -> 'a -``` -Set a new value for the atomic reference, and return the current value. - -``` -val compare_and_set : 'a t -> 'a -> 'a -> bool -``` -`compare_and_set r seen v` sets the new value of `r` to `v` only if its current value is physically equal to `seen` \-- the comparison and the set occur atomically. Returns `true` if the comparison succeeded (so the set happened) and `false` otherwise. - -``` -val fetch_and_add : int t -> int -> int -``` -`fetch_and_add r n` atomically increments the value of `r` by `n`, and returns the current value (before the increment). - -``` -val incr : int t -> unit -``` -`incr r` atomically increments the value of `r` by `1`. - -``` -val decr : int t -> unit -``` -`decr r` atomically decrements the value of `r` by `1`. - - -## Examples - - -### Basic Thread Coordination - -A basic use case is to have global counters that are updated in a thread-safe way, for example to keep some sorts of metrics over IOs performed by the program. Another basic use case is to coordinate the termination of threads in a given program, for example when one thread finds an answer, or when the program is shut down by the user. - -Here, for example, we're going to try to find a number whose hash satisfies a basic property. To do that, we'll run multiple threads which will try random numbers until they find one that works. - -Of course the output below is a sample run and will change every time the program is run. - -```ocaml -(* use for termination *) -let stop_all_threads = Atomic.make false - -(* total number of individual attempts to find a number *) -let num_attempts = Atomic.make 0 - -(* find a number that satisfies [p], by... trying random numbers - until one fits. *) -let find_number_where (p:int -> bool) = - let rand = Random.State.make_self_init() in - while not (Atomic.get stop_all_threads) do - - let n = Random.State.full_int rand max_int in - ignore (Atomic.fetch_and_add num_attempts 1 : int); - - if p (Hashtbl.hash n) then ( - Printf.printf "found %d (hash=%d)\n%!" n (Hashtbl.hash n); - Atomic.set stop_all_threads true; (* signal all threads to stop *) - ) - done;; - - -(* run multiple domains to search for a [n] where [hash n <= 100] *) -let () = - let criterion n = n <= 100 in - let threads = - Array.init 8 - (fun _ -> Domain.spawn (fun () -> find_number_where criterion)) - in - Array.iter Domain.join threads; - Printf.printf "total number of attempts: %d\n%!" - (Atomic.get num_attempts) ;; - -- : unit = () -found 1651745641680046833 (hash=33) -total number of attempts: 30230350 -``` - -### Treiber Stack - -Another example is a basic [Treiber stack](https://en.wikipedia.org/wiki/Treiber_stack) (a thread-safe stack) that can be safely shared between threads. - -Note how both `push` and `pop` are recursive, because they attempt to swap the new stack (with one more, or one fewer, element) with the old stack. This is optimistic concurrency: each iteration of, say, `push stack x` gets the old stack `l`, and hopes that by the time it tries to replace `l` with `x::l`, nobody else has had time to modify the list. If the `compare_and_set` fails it means we were too optimistic, and must try again. - -```ocaml -type 'a stack = 'a list Atomic.t - -let rec push (stack: _ stack) elt : unit = - let cur = Atomic.get stack in - let success = Atomic.compare_and_set stack cur (elt :: cur) in - if not success then - push stack elt - -let rec pop (stack: _ stack) : _ option = - let cur = Atomic.get stack in - match cur with - | [] -> None - | x :: tail -> - let success = Atomic.compare_and_set stack cur tail in - if success then Some x - else pop stack - -# let st = Atomic.make [] -# push st 1 -- : unit = () -# push st 2 -- : unit = () -# pop st -- : int option = Some 2 -# pop st -- : int option = Some 1 -# pop st -- : int option = None -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Bool.md b/docs/api/re/melange/Stdlib-Bool.md deleted file mode 100644 index d6f379425..000000000 --- a/docs/api/re/melange/Stdlib-Bool.md +++ /dev/null @@ -1,83 +0,0 @@ - -# Module `Stdlib.Bool` - -Boolean values. - -since 4.08 - -## Booleans - -``` -type t = bool = -``` -``` -| false -``` -``` -| true -``` -``` - -``` -The type of booleans (truth values). - -The constructors `false` and `true` are included here so that they have paths, but they are not intended to be used in user-defined data types. - -``` -val not : bool -> bool -``` -`not b` is the boolean negation of `b`. - -``` -val (&&) : bool -> bool -> bool -``` -`e0 && e1` is the lazy boolean conjunction of expressions `e0` and `e1`. If `e0` evaluates to `false`, `e1` is not evaluated. Right-associative operator at precedence level 3/11. - -``` -val (||) : bool -> bool -> bool -``` -`e0 || e1` is the lazy boolean disjunction of expressions `e0` and `e1`. If `e0` evaluates to `true`, `e1` is not evaluated. Right-associative operator at precedence level 2/11. - - -## Predicates and comparisons - -``` -val equal : bool -> bool -> bool -``` -`equal b0 b1` is `true` if and only if `b0` and `b1` are both `true` or both `false`. - -``` -val compare : bool -> bool -> int -``` -`compare b0 b1` is a total order on boolean values. `false` is smaller than `true`. - - -## Converting - -``` -val to_int : bool -> int -``` -`to_int b` is `0` if `b` is `false` and `1` if `b` is `true`. - -``` -val to_float : bool -> float -``` -`to_float b` is `0.` if `b` is `false` and `1.` if `b` is `true`. - -``` -val to_string : bool -> string -``` -`to_string b` is `"true"` if `b` is `true` and `"false"` if `b` is `false`. - -``` -val seeded_hash : int -> bool -> int -``` -A seeded hash function for booleans, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : bool -> int -``` -An unseeded hash function for booleans, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Buffer.md b/docs/api/re/melange/Stdlib-Buffer.md deleted file mode 100644 index 9af9a8328..000000000 --- a/docs/api/re/melange/Stdlib-Buffer.md +++ /dev/null @@ -1,282 +0,0 @@ - -# Module `Stdlib.Buffer` - -Extensible buffers. - -This module implements buffers that automatically expand as necessary. It provides accumulative concatenation of strings in linear time (instead of quadratic time when strings are concatenated pairwise). For example: - -```ocaml - let concat_strings ss = - let b = Buffer.create 16 in - List.iter (Buffer.add_string b) ss; - Buffer.contents b - -``` -**Unsynchronized accesses** - -Unsynchronized accesses to a buffer may lead to an invalid buffer state. Thus, concurrent accesses to a buffer must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -type t -``` -The abstract type of buffers. - -``` -val create : int -> t -``` -`create n` returns a fresh buffer, initially empty. The `n` parameter is the initial size of the internal byte sequence that holds the buffer contents. That byte sequence is automatically reallocated when more than `n` characters are stored in the buffer, but shrinks back to `n` characters when `reset` is called. For best performance, `n` should be of the same order of magnitude as the number of characters that are expected to be stored in the buffer (for instance, 80 for a buffer that holds one output line). Nothing bad will happen if the buffer grows beyond that limit, however. In doubt, take `n = 16` for instance. If `n` is not between 1 and [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length), it will be clipped to that interval. - -``` -val contents : t -> string -``` -Return a copy of the current contents of the buffer. The buffer itself is unchanged. - -``` -val to_bytes : t -> bytes -``` -Return a copy of the current contents of the buffer. The buffer itself is unchanged. - -since 4.02 -``` -val sub : t -> int -> int -> string -``` -`Buffer.sub b off len` returns a copy of `len` bytes from the current contents of the buffer `b`, starting at offset `off`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off and len do not designate a valid range of b. -``` -val blit : t -> int -> bytes -> int -> int -> unit -``` -`Buffer.blit src srcoff dst dstoff len` copies `len` characters from the current contents of the buffer `src`, starting at offset `srcoff` to `dst`, starting at character `dstoff`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if srcoff and len do not designate a valid range of src, or if dstoff and len do not designate a valid range of dst. -since 3.11.2 -``` -val nth : t -> int -> char -``` -Get the n-th character of the buffer. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if index out of bounds -``` -val length : t -> int -``` -Return the number of characters currently contained in the buffer. - -``` -val clear : t -> unit -``` -Empty the buffer. - -``` -val reset : t -> unit -``` -Empty the buffer and deallocate the internal byte sequence holding the buffer contents, replacing it with the initial internal byte sequence of length `n` that was allocated by [`Buffer.create`](./#val-create) `n`. For long-lived buffers that may have grown a lot, `reset` allows faster reclamation of the space used by the buffer. - -``` -val output_buffer : out_channel -> t -> unit -``` -`output_buffer oc b` writes the current contents of buffer `b` on the output channel `oc`. - -``` -val truncate : t -> int -> unit -``` -`truncate b len` truncates the length of `b` to `len` Note: the internal byte sequence is not shortened. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> length b. -since 4.05 - -## Appending - -Note: all `add_*` operations can raise `Failure` if the internal byte sequence of the buffer would need to grow beyond [`Sys.max_string_length`](./Stdlib-Sys.md#val-max_string_length). - -``` -val add_char : t -> char -> unit -``` -`add_char b c` appends the character `c` at the end of buffer `b`. - -``` -val add_utf_8_uchar : t -> Uchar.t -> unit -``` -`add_utf_8_uchar b u` appends the [UTF-8](https://tools.ietf.org/html/rfc3629) encoding of `u` at the end of buffer `b`. - -since 4.06 -``` -val add_utf_16le_uchar : t -> Uchar.t -> unit -``` -`add_utf_16le_uchar b u` appends the [UTF-16LE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. - -since 4.06 -``` -val add_utf_16be_uchar : t -> Uchar.t -> unit -``` -`add_utf_16be_uchar b u` appends the [UTF-16BE](https://tools.ietf.org/html/rfc2781) encoding of `u` at the end of buffer `b`. - -since 4.06 -``` -val add_string : t -> string -> unit -``` -`add_string b s` appends the string `s` at the end of buffer `b`. - -``` -val add_bytes : t -> bytes -> unit -``` -`add_bytes b s` appends the byte sequence `s` at the end of buffer `b`. - -since 4.02 -``` -val add_substring : t -> string -> int -> int -> unit -``` -`add_substring b s ofs len` takes `len` characters from offset `ofs` in string `s` and appends them at the end of buffer `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. -``` -val add_subbytes : t -> bytes -> int -> int -> unit -``` -`add_subbytes b s ofs len` takes `len` characters from offset `ofs` in byte sequence `s` and appends them at the end of buffer `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid range of s. -since 4.02 -``` -val add_substitute : t -> (string -> string) -> string -> unit -``` -`add_substitute b f s` appends the string pattern `s` at the end of buffer `b` with substitution. The substitution process looks for variable references in the pattern and substitutes each variable reference with its value, as obtained by applying the mapping `f` to the variable name. Inside the string pattern, a variable reference is a non-escaped `$` immediately followed by a variable name, which is one of the following: - -- a non empty sequence of alphanumeric or `_` characters, -- an arbitrary sequence of characters enclosed by a pair of matching parentheses or curly brackets. An escaped `$` character is a `$` that immediately follows a backslash character; the two characters together stand for a plain `$`. -``` -val add_buffer : t -> t -> unit -``` -`add_buffer b1 b2` appends the current contents of buffer `b2` at the end of buffer `b1`. `b2` is not modified. - -``` -val add_channel : t -> in_channel -> int -> unit -``` -`add_channel b ic n` reads at most `n` characters from the input channel `ic` and stores them at the end of buffer `b`. - -raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if the channel contains fewer than n characters. In this case, the characters are still added to the buffer, so as to avoid loss of data. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0 or len \> Sys.max\_string\_length. - -## Buffers and Sequences - -``` -val to_seq : t -> char Seq.t -``` -Iterate on the buffer, in increasing order. - -The behavior is not specified if the buffer is modified during iteration. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -Iterate on the buffer, in increasing order, yielding indices along chars. - -The behavior is not specified if the buffer is modified during iteration. - -since 4.07 -``` -val add_seq : t -> char Seq.t -> unit -``` -Add chars to the buffer - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -Create a buffer from the generator - -since 4.07 - -## Binary encoding of integers - -The functions in this section append binary encodings of integers to buffers. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. Functions that encode these values truncate their inputs to their least significant bytes. - -``` -val add_uint8 : t -> int -> unit -``` -`add_uint8 b i` appends a binary unsigned 8-bit integer `i` to `b`. - -since 4.08 -``` -val add_int8 : t -> int -> unit -``` -`add_int8 b i` appends a binary signed 8-bit integer `i` to `b`. - -since 4.08 -``` -val add_uint16_ne : t -> int -> unit -``` -`add_uint16_ne b i` appends a binary native-endian unsigned 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_uint16_be : t -> int -> unit -``` -`add_uint16_be b i` appends a binary big-endian unsigned 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_uint16_le : t -> int -> unit -``` -`add_uint16_le b i` appends a binary little-endian unsigned 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int16_ne : t -> int -> unit -``` -`add_int16_ne b i` appends a binary native-endian signed 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int16_be : t -> int -> unit -``` -`add_int16_be b i` appends a binary big-endian signed 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int16_le : t -> int -> unit -``` -`add_int16_le b i` appends a binary little-endian signed 16-bit integer `i` to `b`. - -since 4.08 -``` -val add_int32_ne : t -> int32 -> unit -``` -`add_int32_ne b i` appends a binary native-endian 32-bit integer `i` to `b`. - -since 4.08 -``` -val add_int32_be : t -> int32 -> unit -``` -`add_int32_be b i` appends a binary big-endian 32-bit integer `i` to `b`. - -since 4.08 -``` -val add_int32_le : t -> int32 -> unit -``` -`add_int32_le b i` appends a binary little-endian 32-bit integer `i` to `b`. - -since 4.08 -``` -val add_int64_ne : t -> int64 -> unit -``` -`add_int64_ne b i` appends a binary native-endian 64-bit integer `i` to `b`. - -since 4.08 -``` -val add_int64_be : t -> int64 -> unit -``` -`add_int64_be b i` appends a binary big-endian 64-bit integer `i` to `b`. - -since 4.08 -``` -val add_int64_le : t -> int64 -> unit -``` -`add_int64_ne b i` appends a binary little-endian 64-bit integer `i` to `b`. - -since 4.08 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Bytes.md b/docs/api/re/melange/Stdlib-Bytes.md deleted file mode 100644 index 28c026643..000000000 --- a/docs/api/re/melange/Stdlib-Bytes.md +++ /dev/null @@ -1,683 +0,0 @@ - -# Module `Stdlib.Bytes` - -Byte sequence operations. - -A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. - -Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. - -Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. - -Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. - -Bytes are represented by the OCaml type `char`. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -since 4.02 -``` -val length : bytes -> int -``` -Return the length (number of bytes) of the argument. - -``` -val get : bytes -> int -> char -``` -`get s n` returns the byte at index `n` in argument `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val set : bytes -> int -> char -> unit -``` -`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val create : int -> bytes -``` -`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val make : int -> char -> bytes -``` -`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> (int -> char) -> bytes -``` -`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val empty : bytes -``` -A byte sequence of size 0. - -``` -val copy : bytes -> bytes -``` -Return a new byte sequence that contains the same bytes as the argument. - -``` -val of_string : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -``` -val to_string : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -``` -val sub : bytes -> int -> int -> bytes -``` -`sub s pos len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val sub_string : bytes -> int -> int -> string -``` -Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. - -``` -val extend : bytes -> int -> int -> bytes -``` -`extend s left right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val fill : bytes -> int -> int -> char -> unit -``` -`fill s pos len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val blit : bytes -> int -> bytes -> int -> int -> unit -``` -`blit src src_pos dst dst_pos len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -``` -val blit_string : string -> int -> bytes -> int -> int -> unit -``` -`blit_string src src_pos dst dst_pos len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -since 4.05 in BytesLabels -``` -val concat : bytes -> bytes list -> bytes -``` -`concat sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : bytes -> bytes -> bytes -``` -`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val iter : (char -> unit) -> bytes -> unit -``` -`iter f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. - -``` -val iteri : (int -> char -> unit) -> bytes -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. - -``` -val map : (char -> char) -> bytes -> bytes -``` -`map f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val mapi : (int -> char -> char) -> bytes -> bytes -``` -`mapi f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val fold_left : ('acc -> char -> 'acc) -> 'acc -> bytes -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. - -since 4.13 -``` -val fold_right : (char -> 'acc -> 'acc) -> bytes -> 'acc -> 'acc -``` -`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. - -since 4.13 -``` -val for_all : (char -> bool) -> bytes -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : (char -> bool) -> bytes -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : bytes -> bytes -``` -Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. - -``` -val escaped : bytes -> bytes -``` -Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val index : bytes -> char -> int -``` -`index s c` returns the index of the first occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val index_opt : bytes -> char -> int option -``` -`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val rindex : bytes -> char -> int -``` -`rindex s c` returns the index of the last occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val rindex_opt : bytes -> char -> int option -``` -`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val index_from : bytes -> int -> char -> int -``` -`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -``` -val index_from_opt : bytes -> int -> char -> int option -``` -`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : bytes -> int -> char -> int -``` -`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -``` -val rindex_from_opt : bytes -> int -> char -> int option -``` -`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val contains : bytes -> char -> bool -``` -`contains s c` tests if byte `c` appears in `s`. - -``` -val contains_from : bytes -> int -> char -> bool -``` -`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : bytes -> int -> char -> bool -``` -`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val uppercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val lowercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val capitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val uncapitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -type t = bytes -``` -An alias for the type of byte sequences. - -``` -val compare : t -> t -> int -``` -The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val equal : t -> t -> bool -``` -The equality function for byte sequences. - -since 4.03 (4.05 in BytesLabels) -``` -val starts_with : prefix:bytes -> bytes -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:bytes -> bytes -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 - -## Unsafe conversions (for advanced users) - -This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. - -``` -val unsafe_to_string : bytes -> string -``` -Unsafely convert a byte sequence into a string. - -To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: - -- Unique ownership: the data may be accessed and mutated -- Shared ownership: the data has several owners, that may only access it, not mutate it. -Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. - -`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. - -There are two valid use-cases that respect this ownership discipline: - -1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. - -```ocaml -let string_init len f : string = - let s = Bytes.create len in - for i = 0 to len - 1 do Bytes.set s i (f i) done; - Bytes.unsafe_to_string s -``` -This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. - -Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. - -We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. - -2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. - -```ocaml -let bytes_length (s : bytes) = - String.length (Bytes.unsafe_to_string s) -``` -In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. - -The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. - -``` -val unsafe_of_string : string -> bytes -``` -Unsafely convert a shared string to a byte sequence that should not be mutated. - -The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. - -In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. - -For example, string literals are implicitly shared by the compiler, so you never uniquely own them. - -```ocaml -let incorrect = Bytes.unsafe_of_string "hello" -let s = Bytes.of_string "hello" -``` -The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. - -Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. - -The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. - -``` -val split_on_char : char -> bytes -> bytes list -``` -`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. - -The function's output is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). -- No byte sequence in the result contains the `sep` character. -since 4.13 - -## Iterators - -``` -val to_seq : t -> char Seq.t -``` -Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -Iterate on the string, in increasing order, yielding indices along chars - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -Create a string from the generator - -since 4.07 - -## UTF codecs and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val set_utf_8_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val set_utf_16be_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val set_utf_16le_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary encoding/decoding of integers - -The functions in this section binary encode and decode integers to and from byte sequences. - -All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: - -- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. -- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. -``` -val get_uint8 : bytes -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int8 : bytes -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_ne : bytes -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_be : bytes -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_le : bytes -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_ne : bytes -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_be : bytes -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_le : bytes -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_ne : bytes -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_be : bytes -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_le : bytes -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_ne : bytes -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_be : bytes -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_le : bytes -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val set_uint8 : bytes -> int -> int -> unit -``` -`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int8 : bytes -> int -> int -> unit -``` -`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_ne : bytes -> int -> int -> unit -``` -`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_be : bytes -> int -> int -> unit -``` -`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_le : bytes -> int -> int -> unit -``` -`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_ne : bytes -> int -> int -> unit -``` -`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_be : bytes -> int -> int -> unit -``` -`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_le : bytes -> int -> int -> unit -``` -`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_ne : bytes -> int -> int32 -> unit -``` -`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_be : bytes -> int -> int32 -> unit -``` -`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_le : bytes -> int -> int32 -> unit -``` -`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_ne : bytes -> int -> int64 -> unit -``` -`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_be : bytes -> int -> int64 -> unit -``` -`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_le : bytes -> int -> int64 -> unit -``` -`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 - -## Byte sequences and concurrency safety - -Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let b = Bytes.make size ' ' -let update b f () = - Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b -let d1 = Domain.spawn (update b (fun x -> x + 1)) -let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) -let () = Domain.join d1; Domain.join d2 -``` -the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. - -After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. - - -### Mixed-size accesses - -Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index - -```ocaml -let b = Bytes.make 10 '\000' -let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) -``` -In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/re/melange/Stdlib-BytesLabels.md b/docs/api/re/melange/Stdlib-BytesLabels.md deleted file mode 100644 index ece55c1e0..000000000 --- a/docs/api/re/melange/Stdlib-BytesLabels.md +++ /dev/null @@ -1,695 +0,0 @@ - -# Module `Stdlib.BytesLabels` - -Byte sequence operations. - -A byte sequence is a mutable data structure that contains a fixed-length sequence of bytes. Each byte can be indexed in constant time for reading or writing. - -Given a byte sequence `s` of length `l`, we can access each of the `l` bytes of `s` via its index in the sequence. Indexes start at `0`, and we will call an index valid in `s` if it falls within the range `[0...l-1]` (inclusive). A position is the point between two bytes or at the beginning or end of the sequence. We call a position valid in `s` if it falls within the range `[0...l]` (inclusive). Note that the byte at index `n` is between positions `n` and `n+1`. - -Two parameters `start` and `len` are said to designate a valid range of `s` if `len >= 0` and `start` and `start+len` are valid positions in `s`. - -Byte sequences can be modified in place, for instance via the `set` and `blit` functions described below. See also strings (module [`String`](./Stdlib-String.md)), which are almost the same data structure, but cannot be modified in place. - -Bytes are represented by the OCaml type `char`. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -since 4.02 -``` -val length : bytes -> int -``` -Return the length (number of bytes) of the argument. - -``` -val get : bytes -> int -> char -``` -`get s n` returns the byte at index `n` in argument `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val set : bytes -> int -> char -> unit -``` -`set s n c` modifies `s` in place, replacing the byte at index `n` with `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not a valid index in s. -``` -val create : int -> bytes -``` -`create n` returns a new byte sequence of length `n`. The sequence is uninitialized and contains arbitrary bytes. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val make : int -> char -> bytes -``` -`make n c` returns a new byte sequence of length `n`, filled with the byte `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> f:(int -> char) -> bytes -``` -`init n f` returns a fresh byte sequence of length `n`, with character `i` initialized to the result of `f i` (in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val empty : bytes -``` -A byte sequence of size 0. - -``` -val copy : bytes -> bytes -``` -Return a new byte sequence that contains the same bytes as the argument. - -``` -val of_string : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -``` -val to_string : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -``` -val sub : bytes -> pos:int -> len:int -> bytes -``` -`sub s ~pos ~len` returns a new byte sequence of length `len`, containing the subsequence of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val sub_string : bytes -> pos:int -> len:int -> string -``` -Same as [`sub`](./#val-sub) but return a string instead of a byte sequence. - -``` -val extend : bytes -> left:int -> right:int -> bytes -``` -`extend s ~left ~right` returns a new byte sequence that contains the bytes of `s`, with `left` uninitialized bytes prepended and `right` uninitialized bytes appended to it. If `left` or `right` is negative, then bytes are removed (instead of appended) from the corresponding side of `s`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result length is negative or longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val fill : bytes -> pos:int -> len:int -> char -> unit -``` -`fill s ~pos ~len c` modifies `s` in place, replacing `len` characters with `c`, starting at `pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of s. -``` -val blit : - src:bytes -> - src_pos:int -> - dst:bytes -> - dst_pos:int -> - len:int -> - unit -``` -`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from byte sequence `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same byte sequence, and the source and destination intervals overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -``` -val blit_string : - src:string -> - src_pos:int -> - dst:bytes -> - dst_pos:int -> - len:int -> - unit -``` -`blit_string ~src ~src_pos ~dst ~dst_pos ~len` copies `len` bytes from string `src`, starting at index `src_pos`, to byte sequence `dst`, starting at index `dst_pos`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid range of src, or if dst\_pos and len do not designate a valid range of dst. -since 4.05 in BytesLabels -``` -val concat : sep:bytes -> bytes list -> bytes -``` -`concat ~sep sl` concatenates the list of byte sequences `sl`, inserting the separator byte sequence `sep` between each, and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : bytes -> bytes -> bytes -``` -`cat s1 s2` concatenates `s1` and `s2` and returns the result as a new byte sequence. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.05 in BytesLabels -``` -val iter : f:(char -> unit) -> bytes -> unit -``` -`iter ~f s` applies function `f` in turn to all the bytes of `s`. It is equivalent to `f (get s 0); f (get s 1); ...; f (get s (length s - 1)); ()`. - -``` -val iteri : f:(int -> char -> unit) -> bytes -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the byte as first argument and the byte itself as second argument. - -``` -val map : f:(char -> char) -> bytes -> bytes -``` -`map ~f s` applies function `f` in turn to all the bytes of `s` (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val mapi : f:(int -> char -> char) -> bytes -> bytes -``` -`mapi ~f s` calls `f` with each character of `s` and its index (in increasing index order) and stores the resulting bytes in a new sequence that is returned as the result. - -``` -val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> bytes -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x (get s 0)) (get s 1)) ...) (get s (n-1))`, where `n` is the length of `s`. - -since 4.13 -``` -val fold_right : f:(char -> 'acc -> 'acc) -> bytes -> init:'acc -> 'acc -``` -`fold_right f s x` computes `f (get s 0) (f (get s 1) ( ... (f (get s (n-1)) x) ...))`, where `n` is the length of `s`. - -since 4.13 -``` -val for_all : f:(char -> bool) -> bytes -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : f:(char -> bool) -> bytes -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : bytes -> bytes -``` -Return a copy of the argument, without leading and trailing whitespace. The bytes regarded as whitespace are the ASCII characters `' '`, `'\012'`, `'\n'`, `'\r'`, and `'\t'`. - -``` -val escaped : bytes -> bytes -``` -Return a copy of the argument, with special characters represented by escape sequences, following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash and double-quote. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val index : bytes -> char -> int -``` -`index s c` returns the index of the first occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val index_opt : bytes -> char -> int option -``` -`index_opt s c` returns the index of the first occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val rindex : bytes -> char -> int -``` -`rindex s c` returns the index of the last occurrence of byte `c` in `s`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s. -``` -val rindex_opt : bytes -> char -> int option -``` -`rindex_opt s c` returns the index of the last occurrence of byte `c` in `s` or `None` if `c` does not occur in `s`. - -since 4.05 -``` -val index_from : bytes -> int -> char -> int -``` -`index_from s i c` returns the index of the first occurrence of byte `c` in `s` after position `i`. `index s c` is equivalent to `index_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -``` -val index_from_opt : bytes -> int -> char -> int option -``` -`index_from_opt s i c` returns the index of the first occurrence of byte `c` in `s` after position `i` or `None` if `c` does not occur in `s` after position `i`. `index_opt s c` is equivalent to `index_from_opt s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : bytes -> int -> char -> int -``` -`rindex_from s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1`. `rindex s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -``` -val rindex_from_opt : bytes -> int -> char -> int option -``` -`rindex_from_opt s i c` returns the index of the last occurrence of byte `c` in `s` before position `i+1` or `None` if `c` does not occur in `s` before position `i+1`. `rindex_opt s c` is equivalent to `rindex_from s (length s - 1) c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val contains : bytes -> char -> bool -``` -`contains s c` tests if byte `c` appears in `s`. - -``` -val contains_from : bytes -> int -> char -> bool -``` -`contains_from s start c` tests if byte `c` appears in `s` after position `start`. `contains s c` is equivalent to `contains_from s 0 c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : bytes -> int -> char -> bool -``` -`rcontains_from s stop c` tests if byte `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val uppercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val lowercase_ascii : bytes -> bytes -``` -Return a copy of the argument, with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val capitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -val uncapitalize_ascii : bytes -> bytes -``` -Return a copy of the argument, with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in BytesLabels) -``` -type t = bytes -``` -An alias for the type of byte sequences. - -``` -val compare : t -> t -> int -``` -The comparison function for byte sequences, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Bytes` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val equal : t -> t -> bool -``` -The equality function for byte sequences. - -since 4.03 (4.05 in BytesLabels) -``` -val starts_with : prefix:bytes -> bytes -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:bytes -> bytes -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 - -## Unsafe conversions (for advanced users) - -This section describes unsafe, low-level conversion functions between `bytes` and `string`. They do not copy the internal data; used improperly, they can break the immutability invariant on strings. They are available for expert library authors, but for most purposes you should use the always-correct [`to_string`](./#val-to_string) and [`of_string`](./#val-of_string) instead. - -``` -val unsafe_to_string : bytes -> string -``` -Unsafely convert a byte sequence into a string. - -To reason about the use of `unsafe_to_string`, it is convenient to consider an "ownership" discipline. A piece of code that manipulates some data "owns" it; there are several disjoint ownership modes, including: - -- Unique ownership: the data may be accessed and mutated -- Shared ownership: the data has several owners, that may only access it, not mutate it. -Unique ownership is linear: passing the data to another piece of code means giving up ownership (we cannot write the data again). A unique owner may decide to make the data shared (giving up mutation rights on it), but shared data may not become uniquely-owned again. - -`unsafe_to_string s` can only be used when the caller owns the byte sequence `s` \-- either uniquely or as shared immutable data. The caller gives up ownership of `s`, and gains ownership of the returned string. - -There are two valid use-cases that respect this ownership discipline: - -1\. Creating a string by initializing and mutating a byte sequence that is never changed after initialization is performed. - -```ocaml -let string_init len f : string = - let s = Bytes.create len in - for i = 0 to len - 1 do Bytes.set s i (f i) done; - Bytes.unsafe_to_string s -``` -This function is safe because the byte sequence `s` will never be accessed or mutated after `unsafe_to_string` is called. The `string_init` code gives up ownership of `s`, and returns the ownership of the resulting string to its caller. - -Note that it would be unsafe if `s` was passed as an additional parameter to the function `f` as it could escape this way and be mutated in the future \-- `string_init` would give up ownership of `s` to pass it to `f`, and could not call `unsafe_to_string` safely. - -We have provided the [`String.init`](./Stdlib-String.md#val-init), [`String.map`](./Stdlib-String.md#val-map) and [`String.mapi`](./Stdlib-String.md#val-mapi) functions to cover most cases of building new strings. You should prefer those over `to_string` or `unsafe_to_string` whenever applicable. - -2. Temporarily giving ownership of a byte sequence to a function that expects a uniquely owned string and returns ownership back, so that we can mutate the sequence again after the call ended. - -```ocaml -let bytes_length (s : bytes) = - String.length (Bytes.unsafe_to_string s) -``` -In this use-case, we do not promise that `s` will never be mutated after the call to `bytes_length s`. The [`String.length`](./Stdlib-String.md#val-length) function temporarily borrows unique ownership of the byte sequence (and sees it as a `string`), but returns this ownership back to the caller, which may assume that `s` is still a valid byte sequence after the call. Note that this is only correct because we know that [`String.length`](./Stdlib-String.md#val-length) does not capture its argument \-- it could escape by a side-channel such as a memoization combinator. - -The caller may not mutate `s` while the string is borrowed (it has temporarily given up ownership). This affects concurrent programs, but also higher-order functions: if [`String.length`](./Stdlib-String.md#val-length) returned a closure to be called later, `s` should not be mutated until this closure is fully applied and returns ownership. - -``` -val unsafe_of_string : string -> bytes -``` -Unsafely convert a shared string to a byte sequence that should not be mutated. - -The same ownership discipline that makes `unsafe_to_string` correct applies to `unsafe_of_string`: you may use it if you were the owner of the `string` value, and you will own the return `bytes` in the same mode. - -In practice, unique ownership of string values is extremely difficult to reason about correctly. You should always assume strings are shared, never uniquely owned. - -For example, string literals are implicitly shared by the compiler, so you never uniquely own them. - -```ocaml -let incorrect = Bytes.unsafe_of_string "hello" -let s = Bytes.of_string "hello" -``` -The first declaration is incorrect, because the string literal `"hello"` could be shared by the compiler with other parts of the program, and mutating `incorrect` is a bug. You must always use the second version, which performs a copy and is thus correct. - -Assuming unique ownership of strings that are not string literals, but are (partly) built from string literals, is also incorrect. For example, mutating `unsafe_of_string ("foo" ^ s)` could mutate the shared string `"foo"` \-- assuming a rope-like representation of strings. More generally, functions operating on strings will assume shared ownership, they do not preserve unique ownership. It is thus incorrect to assume unique ownership of the result of `unsafe_of_string`. - -The only case we have reasonable confidence is safe is if the produced `bytes` is shared \-- used as an immutable byte sequence. This is possibly useful for incremental migration of low-level programs that manipulate immutable sequences of bytes (for example [`Marshal.from_bytes`](./Stdlib-Marshal.md#val-from_bytes)) and previously used the `string` type for this purpose. - -``` -val split_on_char : sep:char -> bytes -> bytes list -``` -`split_on_char sep s` returns the list of all (possibly empty) subsequences of `s` that are delimited by the `sep` character. If `s` is empty, the result is the singleton list `[empty]`. - -The function's output is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a byte sequence equal to the input (`Bytes.concat (Bytes.make 1 sep) (Bytes.split_on_char sep s) = s`). -- No byte sequence in the result contains the `sep` character. -since 4.13 - -## Iterators - -``` -val to_seq : t -> char Seq.t -``` -Iterate on the string, in increasing index order. Modifications of the string during iteration will be reflected in the sequence. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -Iterate on the string, in increasing order, yielding indices along chars - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -Create a string from the generator - -since 4.07 - -## UTF codecs and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val set_utf_8_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_8_uchar b i u` UTF-8 encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val set_utf_16be_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16be_uchar b i u` UTF-16BE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val set_utf_16le_uchar : t -> int -> Uchar.t -> int -``` -`set_utf_16le_uchar b i u` UTF-16LE encodes `u` at index `i` in `b` and returns the number of bytes `n` that were written starting at `i`. If `n` is `0` there was not enough space to encode `u` at `i` and `b` was left untouched. Otherwise a new character can be encoded at `i + n`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary encoding/decoding of integers - -The functions in this section binary encode and decode integers to and from byte sequences. - -All following functions raise `Invalid_argument` if the space needed at index `i` to decode or encode the integer is not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are handled as follows: - -- Functions that decode signed (resp. unsigned) 8-bit or 16-bit integers represented by `int` values sign-extend (resp. zero-extend) their result. -- Functions that encode 8-bit or 16-bit integers represented by `int` values truncate their input to their least significant bytes. -``` -val get_uint8 : bytes -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int8 : bytes -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_ne : bytes -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_be : bytes -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_uint16_le : bytes -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_ne : bytes -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_be : bytes -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int16_le : bytes -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_ne : bytes -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_be : bytes -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int32_le : bytes -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_ne : bytes -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_be : bytes -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val get_int64_le : bytes -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at byte index `i`. - -since 4.08 -``` -val set_uint8 : bytes -> int -> int -> unit -``` -`set_uint8 b i v` sets `b`'s unsigned 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int8 : bytes -> int -> int -> unit -``` -`set_int8 b i v` sets `b`'s signed 8-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_ne : bytes -> int -> int -> unit -``` -`set_uint16_ne b i v` sets `b`'s native-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_be : bytes -> int -> int -> unit -``` -`set_uint16_be b i v` sets `b`'s big-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_uint16_le : bytes -> int -> int -> unit -``` -`set_uint16_le b i v` sets `b`'s little-endian unsigned 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_ne : bytes -> int -> int -> unit -``` -`set_int16_ne b i v` sets `b`'s native-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_be : bytes -> int -> int -> unit -``` -`set_int16_be b i v` sets `b`'s big-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int16_le : bytes -> int -> int -> unit -``` -`set_int16_le b i v` sets `b`'s little-endian signed 16-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_ne : bytes -> int -> int32 -> unit -``` -`set_int32_ne b i v` sets `b`'s native-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_be : bytes -> int -> int32 -> unit -``` -`set_int32_be b i v` sets `b`'s big-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int32_le : bytes -> int -> int32 -> unit -``` -`set_int32_le b i v` sets `b`'s little-endian 32-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_ne : bytes -> int -> int64 -> unit -``` -`set_int64_ne b i v` sets `b`'s native-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_be : bytes -> int -> int64 -> unit -``` -`set_int64_be b i v` sets `b`'s big-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 -``` -val set_int64_le : bytes -> int -> int64 -> unit -``` -`set_int64_le b i v` sets `b`'s little-endian 64-bit integer starting at byte index `i` to `v`. - -since 4.08 - -## Byte sequences and concurrency safety - -Care must be taken when concurrently accessing byte sequences from multiple domains: accessing a byte sequence will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every byte sequence operation that accesses more than one byte is not atomic. This includes iteration and scanning. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let b = Bytes.make size ' ' -let update b f () = - Bytes.iteri (fun i x -> Bytes.set b i (Char.chr (f (Char.code x)))) b -let d1 = Domain.spawn (update b (fun x -> x + 1)) -let d2 = Domain.spawn (update b (fun x -> 2 * x + 1)) -let () = Domain.join d1; Domain.join d2 -``` -the bytes sequence `b` may contain a non-deterministic mixture of `'!'`, `'A'`, `'B'`, and `'C'` values. - -After executing this code, each byte of the sequence `b` is either `'!'`, `'A'`, `'B'`, or `'C'`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of a byte sequence, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same byte without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the elements of the sequence. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location. - - -### Mixed-size accesses - -Another subtle point is that if a data race involves mixed-size writes and reads to the same location, the order in which those writes and reads are observed by domains is not specified. For instance, the following code write sequentially a 32-bit integer and a `char` to the same index - -```ocaml -let b = Bytes.make 10 '\000' -let d1 = Domain.spawn (fun () -> Bytes.set_int32_ne b 0 100; b.[0] <- 'd' ) -``` -In this situation, a domain that observes the write of 'd' to b.`0` is not guaranteed to also observe the write to indices `1`, `2`, or `3`. diff --git a/docs/api/re/melange/Stdlib-Char.md b/docs/api/re/melange/Stdlib-Char.md deleted file mode 100644 index 31c382bda..000000000 --- a/docs/api/re/melange/Stdlib-Char.md +++ /dev/null @@ -1,61 +0,0 @@ - -# Module `Stdlib.Char` - -Character operations. - -``` -val code : char -> int -``` -Return the ASCII code of the argument. - -``` -val chr : int -> char -``` -Return the character with the given ASCII code. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is outside the range 0--255. -``` -val escaped : char -> string -``` -Return a string representing the given character, with special characters escaped following the lexical conventions of OCaml. All characters outside the ASCII printable range (32..126) are escaped, as well as backslash, double-quote, and single-quote. - -``` -val lowercase_ascii : char -> char -``` -Convert the given character to its equivalent lowercase character, using the US-ASCII character set. - -since 4.03 -``` -val uppercase_ascii : char -> char -``` -Convert the given character to its equivalent uppercase character, using the US-ASCII character set. - -since 4.03 -``` -type t = char -``` -An alias for the type of characters. - -``` -val compare : t -> t -> int -``` -The comparison function for characters, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Char` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val equal : t -> t -> bool -``` -The equal function for chars. - -since 4.03 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for characters, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for characters, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Complex.md b/docs/api/re/melange/Stdlib-Complex.md deleted file mode 100644 index e751d99b7..000000000 --- a/docs/api/re/melange/Stdlib-Complex.md +++ /dev/null @@ -1,106 +0,0 @@ - -# Module `Stdlib.Complex` - -Complex numbers. - -This module provides arithmetic operations on complex numbers. Complex numbers are represented by their real and imaginary parts (cartesian representation). Each part is represented by a double-precision floating-point number (type `float`). - -``` -type t = { -``` -`re : float;` -`im : float;` -``` -} -``` -The type of complex numbers. `re` is the real part and `im` the imaginary part. - -``` -val zero : t -``` -The complex number `0`. - -``` -val one : t -``` -The complex number `1`. - -``` -val i : t -``` -The complex number `i`. - -``` -val neg : t -> t -``` -Unary negation. - -``` -val conj : t -> t -``` -Conjugate: given the complex `x + i.y`, returns `x - i.y`. - -``` -val add : t -> t -> t -``` -Addition - -``` -val sub : t -> t -> t -``` -Subtraction - -``` -val mul : t -> t -> t -``` -Multiplication - -``` -val inv : t -> t -``` -Multiplicative inverse (`1/z`). - -``` -val div : t -> t -> t -``` -Division - -``` -val sqrt : t -> t -``` -Square root. The result `x + i.y` is such that `x > 0` or `x = 0` and `y >= 0`. This function has a discontinuity along the negative real axis. - -``` -val norm2 : t -> float -``` -Norm squared: given `x + i.y`, returns `x^2 + y^2`. - -``` -val norm : t -> float -``` -Norm: given `x + i.y`, returns `sqrt(x^2 + y^2)`. - -``` -val arg : t -> float -``` -Argument. The argument of a complex number is the angle in the complex plane between the positive real axis and a line passing through zero and the number. This angle ranges from `-pi` to `pi`. This function has a discontinuity along the negative real axis. - -``` -val polar : float -> float -> t -``` -`polar norm arg` returns the complex having norm `norm` and argument `arg`. - -``` -val exp : t -> t -``` -Exponentiation. `exp z` returns `e` to the `z` power. - -``` -val log : t -> t -``` -Natural logarithm (in base `e`). - -``` -val pow : t -> t -> t -``` -Power function. `pow z1 z2` returns `z1` to the `z2` power. diff --git a/docs/api/re/melange/Stdlib-Digest-BLAKE128.md b/docs/api/re/melange/Stdlib-Digest-BLAKE128.md deleted file mode 100644 index d066e1e33..000000000 --- a/docs/api/re/melange/Stdlib-Digest-BLAKE128.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.BLAKE128` - -`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-BLAKE256.md b/docs/api/re/melange/Stdlib-Digest-BLAKE256.md deleted file mode 100644 index ee9952c96..000000000 --- a/docs/api/re/melange/Stdlib-Digest-BLAKE256.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.BLAKE256` - -`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-BLAKE512.md b/docs/api/re/melange/Stdlib-Digest-BLAKE512.md deleted file mode 100644 index a22b0bc72..000000000 --- a/docs/api/re/melange/Stdlib-Digest-BLAKE512.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.BLAKE512` - -`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-MD5.md b/docs/api/re/melange/Stdlib-Digest-MD5.md deleted file mode 100644 index 9909a727e..000000000 --- a/docs/api/re/melange/Stdlib-Digest-MD5.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module `Digest.MD5` - -`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest-module-type-S.md b/docs/api/re/melange/Stdlib-Digest-module-type-S.md deleted file mode 100644 index 8e6095b8a..000000000 --- a/docs/api/re/melange/Stdlib-Digest-module-type-S.md +++ /dev/null @@ -1,78 +0,0 @@ - -# Module type `Digest.S` - -The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. - -since 5.2 -``` -type t = string -``` -The type of digests. - -``` -val hash_length : int -``` -The length of digests, in bytes. - -``` -val compare : t -> t -> int -``` -Compare two digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). - -``` -val equal : t -> t -> bool -``` -Test two digests for equality. - -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -``` -val substring : string -> int -> int -> t -``` -`substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -``` -val channel : in_channel -> int -> t -``` -Read characters from the channel and return their digest. See [`Digest.channel`](./Stdlib-Digest.md#val-channel) for the full specification. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not hash\_length, -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of the argument is not 2 \* hash\_length, or if the arguments contains non-hexadecimal characters. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Digest.md b/docs/api/re/melange/Stdlib-Digest.md deleted file mode 100644 index 6ef661f6d..000000000 --- a/docs/api/re/melange/Stdlib-Digest.md +++ /dev/null @@ -1,120 +0,0 @@ - -# Module `Stdlib.Digest` - -Message digest. - -This module provides functions to compute 'digests', also known as 'hashes', of arbitrary-length strings or files. The supported hashing algorithms are BLAKE2 and MD5. - - -## Basic functions - -The functions in this section use the MD5 hash function to produce 128-bit digests (16 bytes). MD5 is not cryptographically secure. Hence, these functions should not be used for security-sensitive applications. The BLAKE2 functions below are cryptographically secure. - -``` -type t = string -``` -The type of digests: 16-byte strings. - -``` -val compare : t -> t -> int -``` -The comparison function for 16-byte digests, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare) and the implementation shared with [`String.compare`](./Stdlib-String.md#val-compare). Along with the type `t`, this function `compare` allows the module `Digest` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -since 4.00 -``` -val equal : t -> t -> bool -``` -The equal function for 16-byte digests. - -since 4.03 -``` -val string : string -> t -``` -Return the digest of the given string. - -``` -val bytes : bytes -> t -``` -Return the digest of the given byte sequence. - -since 4.02 -``` -val substring : string -> int -> int -> t -``` -`Digest.substring s ofs len` returns the digest of the substring of `s` starting at index `ofs` and containing `len` characters. - -``` -val subbytes : bytes -> int -> int -> t -``` -`Digest.subbytes s ofs len` returns the digest of the subsequence of `s` starting at index `ofs` and containing `len` bytes. - -since 4.02 -``` -val channel : in_channel -> int -> t -``` -If `len` is nonnegative, `Digest.channel ic len` reads `len` characters from channel `ic` and returns their digest, or raises `End_of_file` if end-of-file is reached before `len` characters are read. If `len` is negative, `Digest.channel ic len` reads all characters from `ic` until end-of-file is reached and return their digest. - -``` -val file : string -> t -``` -Return the digest of the file whose name is given. - -``` -val output : out_channel -> t -> unit -``` -Write a digest on the given output channel. - -``` -val input : in_channel -> t -``` -Read a digest from the given input channel. - -``` -val to_hex : t -> string -``` -Return the printable hexadecimal representation of the given digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 16 bytes. -``` -val of_hex : string -> t -``` -Convert a hexadecimal representation back into the corresponding digest. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the argument is not exactly 32 hexadecimal characters. -since 5.2 -``` -val from_hex : string -> t -``` -Same function as [`Digest.of_hex`](./#val-of_hex). - -since 4.00 - -## Generic interface - -``` -module type S = sig ... end -``` -The signature for a hash function that produces digests of length `hash_length` from character strings, byte arrays, and files. - - -## Specific hash functions - -``` -module BLAKE128 : S -``` -`BLAKE128` is the BLAKE2b hash function producing 128-bit (16-byte) digests. It is cryptographically secure. However, the small size of the digests enables brute-force attacks in `2{^64}` attempts. - -``` -module BLAKE256 : S -``` -`BLAKE256` is the BLAKE2b hash function producing 256-bit (32-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -``` -module BLAKE512 : S -``` -`BLAKE512` is the BLAKE2b hash function producing 512-bit (64-byte) digests. It is cryptographically secure, and the digests are large enough to thwart brute-force attacks. - -``` -module MD5 : S -``` -`MD5` is the MD5 hash function. It produces 128-bit (16-byte) digests and is not cryptographically secure at all. It should be used only for compatibility with earlier designs that mandate the use of MD5. diff --git a/docs/api/re/melange/Stdlib-Domain-DLS.md b/docs/api/re/melange/Stdlib-Domain-DLS.md deleted file mode 100644 index 5c29e70ee..000000000 --- a/docs/api/re/melange/Stdlib-Domain-DLS.md +++ /dev/null @@ -1,45 +0,0 @@ - -# Module `Domain.DLS` - -Domain-local Storage - -``` -type 'a key -``` -Type of a DLS key - -``` -val new_key : ?split_from_parent:('a -> 'a) -> (unit -> 'a) -> 'a key -``` -`new_key f` returns a new key bound to initialiser `f` for accessing domain-local variables. - -If `split_from_parent` is not provided, the value for a new domain will be computed on-demand by the new domain: the first `get` call will call the initializer `f` and store that value. - -**Warning.** `f` may be called several times if another call to `get` occurs during initialization on the same domain. Only the 'first' value computed will be used, the other now-useless values will be discarded. Your initialization function should support this situation, or contain logic to detect this case and fail. - -If `split_from_parent` is provided, spawning a domain will derive the child value (for this key) from the parent value. This computation happens in the parent domain and it always happens, regardless of whether the child domain will use it. If the splitting function is expensive or requires child-side computation, consider using `'a Lazy.t key`: - -```ocaml -let init () = ... - -let split_from_parent parent_value = - ... parent-side computation ...; - lazy ( - ... child-side computation ... - ) - -let key = Domain.DLS.new_key ~split_from_parent init - -let get () = Lazy.force (Domain.DLS.get key) -``` -In this case a part of the computation happens on the child domain; in particular, it can access `parent_value` concurrently with the parent domain, which may require explicit synchronization to avoid data races. - -``` -val get : 'a key -> 'a -``` -`get k` returns `v` if a value `v` is associated to the key `k` on the calling domain's domain-local state. Sets `k`'s value with its initialiser and returns it otherwise. - -``` -val set : 'a key -> 'a -> unit -``` -`set k v` updates the calling domain's domain-local state to associate the key `k` with value `v`. It overwrites any previous values associated to `k`, which cannot be restored later. diff --git a/docs/api/re/melange/Stdlib-Domain.md b/docs/api/re/melange/Stdlib-Domain.md deleted file mode 100644 index 5a038a823..000000000 --- a/docs/api/re/melange/Stdlib-Domain.md +++ /dev/null @@ -1,89 +0,0 @@ - -# Module `Stdlib.Domain` - -alert unstable The Domain interface may change in incompatible ways in the future. -Domains. - -See 'Parallel programming' chapter in the manual. - -since 5.0 -alert unstable The Domain interface may change in incompatible ways in the future. -``` -type !'a t -``` -A domain of type `'a t` runs independently, eventually producing a result of type 'a, or an exception - -``` -val spawn : (unit -> 'a) -> 'a t -``` -`spawn f` creates a new domain that runs in parallel with the current domain. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the program has insufficient resources to create another domain. -``` -val join : 'a t -> 'a Js.Promise.t -``` -`join d` blocks until domain `d` runs to completion. If `d` results in a value, then that is returned by `join d`. If `d` raises an uncaught exception, then that is re-raised by `join d`. - -``` -type id = private int -``` -Domains have unique integer identifiers - -``` -val get_id : 'a t -> id -``` -`get_id d` returns the identifier of the domain `d` - -``` -val self : unit -> id -``` -`self ()` is the identifier of the currently running domain - -``` -val before_first_spawn : (unit -> unit) -> unit -``` -`before_first_spawn f` registers `f` to be called before the first domain is spawned by the program. The functions registered with `before_first_spawn` are called on the main (initial) domain. The functions registered with `before_first_spawn` are called in 'first in, first out' order: the oldest function added with `before_first_spawn` is called first. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the program has already spawned a domain. -``` -val at_exit : (unit -> unit) -> unit -``` -`at_exit f` registers `f` to be called when the current domain exits. Note that `at_exit` callbacks are domain-local and only apply to the calling domain. The registered functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. An example: - -```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) -``` -The snippet above creates a key that when retrieved for the first time will open a temporary file and register an `at_exit` callback to close it, thus guaranteeing the descriptor is not leaked in case the current domain exits. - -``` -val cpu_relax : unit -> unit -``` -If busy-waiting, calling cpu\_relax () between iterations will improve performance on some CPU architectures - -``` -val is_main_domain : unit -> bool -``` -`is_main_domain ()` returns true if called from the initial domain. - -``` -val recommended_domain_count : unit -> int -``` -The recommended maximum number of domains which should be running simultaneously (including domains already running). - -The value returned is at least `1`. - -``` -val self_index : unit -> int -``` -The index of the current domain. It is an integer unique among currently-running domains, in the interval `0; N-1` where N is the peak number of domains running simultaneously so far. - -The index of a terminated domain may be reused for a new domain. Use `(Domain.self () :> int)` instead for an identifier unique among all domains ever created by the program. - -since 5.3 -``` -module DLS : sig ... end -``` -Domain-local Storage diff --git a/docs/api/re/melange/Stdlib-Dynarray.md b/docs/api/re/melange/Stdlib-Dynarray.md deleted file mode 100644 index c278e16be..000000000 --- a/docs/api/re/melange/Stdlib-Dynarray.md +++ /dev/null @@ -1,582 +0,0 @@ - -# Module `Stdlib.Dynarray` - -Dynamic arrays. - -The [`Array`](./Stdlib-Array.md) module provide arrays of fixed length. [`Dynarray`](#) provides arrays whose length can change over time, by adding or removing elements at the end of the array. - -This is typically used to accumulate elements whose number is not known in advance or changes during computation, while also providing fast access to elements at arbitrary indices. - -```ocaml - let dynarray_of_list li = - let arr = Dynarray.create () in - List.iter (fun v -> Dynarray.add_last arr v) li; - arr -``` -The [`Buffer`](./Stdlib-Buffer.md) module provides similar features, but it is specialized for accumulating characters into a dynamically-resized string. - -The [`Stack`](./Stdlib-Stack.md) module provides a last-in first-out data structure that can be easily implemented on top of dynamic arrays. - -since 5.2 -**Unsynchronized accesses** - -Concurrent accesses to dynamic arrays must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). Unsynchronized accesses to a dynamic array are a programming error that may lead to an invalid dynamic array state, on which some operations would fail with an `Invalid_argument` exception. - - -## Dynamic arrays - -``` -type !'a t -``` -A dynamic array containing values of type `'a`. - -A dynamic array `a` provides constant-time `get` and `set` operations on indices between `0` and `Dynarray.length a - 1` included. Its [`length`](./#val-length) may change over time by adding or removing elements to the end of the array. - -We say that an index into a dynarray `a` is valid if it is in `0 .. length a - 1` and invalid otherwise. - -``` -val create : unit -> 'a t -``` -`create ()` is a new, empty array. - -``` -val make : int -> 'a -> 'a t -``` -`make n x` is a new array of length `n`, filled with `x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. -``` -val init : int -> (int -> 'a) -> 'a t -``` -`init n f` is a new array `a` of length `n`, such that `get a i` is `f i`. In other words, the elements of `a` are `f 0`, then `f 1`, then `f 2`... and `f (n - 1)` last, evaluated in that order. - -This is similar to [`Array.init`](./Stdlib-Array.md#val-init). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_array\_length. -``` -val get : 'a t -> int -> 'a -``` -`get a i` is the `i`\-th element of `a`, starting with index `0`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid -``` -val set : 'a t -> int -> 'a -> unit -``` -`set a i x` sets the `i`\-th element of `a` to be `x`. - -`i` must be a valid index. `set` does not add new elements to the array \-- see [`add_last`](./#val-add_last) to add an element. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the index is invalid. -``` -val length : 'a t -> int -``` -`length a` is the number of elements in the array. - -``` -val is_empty : 'a t -> bool -``` -`is_empty a` is `true` if `a` is empty, that is, if `length a = 0`. - -``` -val get_last : 'a t -> 'a -``` -`get_last a` is the element of `a` at index `length a - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if a is empty. -``` -val find_last : 'a t -> 'a option -``` -`find_last a` is `None` if `a` is empty and `Some (get_last a)` otherwise. - -``` -val copy : 'a t -> 'a t -``` -`copy a` is a shallow copy of `a`, a new array containing the same elements as `a`. - - -## Adding elements - -Note: all operations adding elements raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). - -``` -val add_last : 'a t -> 'a -> unit -``` -`add_last a x` adds the element `x` at the end of the array `a`. - -``` -val append_array : 'a t -> 'a array -> unit -``` -`append_array a b` adds all elements of `b` at the end of `a`, in the order they appear in `b`. - -For example: - -```ocaml - let a = Dynarray.of_list [1;2] in - Dynarray.append_array a [|3; 4|]; - assert (Dynarray.to_list a = [1; 2; 3; 4]) -``` -``` -val append_list : 'a t -> 'a list -> unit -``` -Like [`append_array`](./#val-append_array) but with a list. - -``` -val append : 'a t -> 'a t -> unit -``` -`append a b` is like `append_array a b`, but `b` is itself a dynamic array instead of a fixed-size array. - -Warning: `append a a` is a programming error because it iterates on `a` and adds elements to it at the same time \-- see the [Iteration](./#iteration) section below. It fails with `Invalid_argument`. If you really want to append a copy of `a` to itself, you can use `Dynarray.append_array a (Dynarray.to_array a)` which copies `a` into a temporary array. - -``` -val append_seq : 'a t -> 'a Seq.t -> unit -``` -Like [`append_array`](./#val-append_array) but with a sequence. - -Warning: `append_seq a (to_seq_reentrant a)` simultaneously traverses `a` and adds element to it; the ordering of those operations is unspecified, and may result in an infinite loop \-- the new elements may in turn be produced by `to_seq_reentrant a` and get added again and again. - -``` -val append_iter : 'a t -> (('a -> unit) -> 'x -> unit) -> 'x -> unit -``` -`append_iter a iter x` adds each element of `x` to the end of `a`. This is `iter (add_last a) x`. - -For example, `append_iter a List.iter [1;2;3]` would add elements `1`, `2`, and then `3` at the end of `a`. `append_iter a Queue.iter q` adds elements from the queue `q`. - -``` -val blit : - src:'a t -> - src_pos:int -> - dst:'a t -> - dst_pos:int -> - len:int -> - unit -``` -`blit ~src ~src_pos ~dst ~dst_pos ~len` copies `len` elements from a source dynarray `src`, starting at index `src_pos`, to a destination dynarray `dst`, starting at index `dst_pos`. It works correctly even if `src` and `dst` are the same array, and the source and destination chunks overlap. - -Unlike [`Array.blit`](./Stdlib-Array.md#val-blit), [`Dynarray.blit`](./#val-blit) can extend the destination array with new elements: it is valid to call `blit` even when `dst_pos + len` is larger than `length dst`. The only requirement is that `dst_pos` must be at most `length dst` (included), so that there is no gap between the current elements and the blit region. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos is strictly below 0 or strictly above length dst. - -## Removing elements - -``` -val pop_last_opt : 'a t -> 'a option -``` -`pop_last_opt a` removes and returns the last element of `a`, or `None` if the array is empty. - -``` -val pop_last : 'a t -> 'a -``` -`pop_last a` removes and returns the last element of `a`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) on an empty array. -``` -val remove_last : 'a t -> unit -``` -`remove_last a` removes the last element of `a`, if any. It does nothing if `a` is empty. - -``` -val truncate : 'a t -> int -> unit -``` -`truncate a n` truncates `a` to have at most `n` elements. - -It removes elements whose index is greater or equal to `n`. It does nothing if `n >= length a`. - -`truncate a n` is equivalent to: - -```ocaml - if n < 0 then invalid_argument "..."; - while length a > n do - remove_last a - done -``` -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. -``` -val clear : 'a t -> unit -``` -`clear a` is `truncate a 0`, it removes all the elements of `a`. - - -## Iteration - -The iteration functions traverse the elements of a dynamic array. Traversals of `a` are computed in increasing index order: from the element of index `0` to the element of index `length a - 1`. - -It is a programming error to change the length of an array (by adding or removing elements) during an iteration on the array. Any iteration function will fail with `Invalid_argument` if it detects such a length change. - -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f a` calls `f` on each element of `a`. - -``` -val iteri : (int -> 'a -> unit) -> 'a t -> unit -``` -`iteri f a` calls `f i x` for each `x` at index `i` in `a`. - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f a` is a new array of elements of the form `f x` for each element `x` of `a`. - -For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f x0`, `f x1`, `f x2`. - -``` -val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t -``` -`mapi f a` is a new array of elements of the form `f i x` for each element `x` of `a` at index `i`. - -For example, if the elements of `a` are `x0`, `x1`, `x2`, then the elements of `b` are `f 0 x0`, `f 1 x1`, `f 2 x2`. - -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold_left f acc a` folds `f` over `a` in order, starting with accumulator `acc`. - -For example, if the elements of `a` are `x0`, `x1`, then `fold f acc a` is - -```ocaml - let acc = f acc x0 in - let acc = f acc x1 in - acc -``` -``` -val fold_right : ('a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -`fold_right f a acc` computes `f x0 (f x1 (... (f xn acc) ...))` where `x0`, `x1`, ..., `xn` are the elements of `a`. - -``` -val filter : ('a -> bool) -> 'a t -> 'a t -``` -`filter f a` is a new array of all the elements of `a` that satisfy `f`. In other words, it is an array `b` such that, for each element `x` in `a` in order, `x` is added to `b` if `f x` is `true`. - -For example, `filter (fun x -> x >= 0) a` is a new array of all non-negative elements of `a`, in order. - -``` -val filter_map : ('a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f a` is a new array of elements `y` such that `f x` is `Some y` for an element `x` of `a`. In others words, it is an array `b` such that, for each element `x` of `a` in order: - -- if `f x = Some y`, then `y` is added to `b`, -- if `f x = None`, then no element is added to `b`. -For example, `filter_map int_of_string_opt inputs` returns a new array of integers read from the strings in `inputs`, ignoring strings that cannot be converted to integers. - - -## Dynarray scanning - -``` -val exists : ('a -> bool) -> 'a t -> bool -``` -`exists f a` is `true` if some element of `a` satisfies `f`. - -For example, if the elements of `a` are `x0`, `x1`, `x2`, then `exists f a` is `f x0 || f x1 || f x2`. - -``` -val for_all : ('a -> bool) -> 'a t -> bool -``` -`for_all f a` is `true` if all elements of `a` satisfy `f`. This includes the case where `a` is empty. - -For example, if the elements of `a` are `x0`, `x1`, then `exists f a` is `f x0 && f x1 && f x2`. - -``` -val mem : 'a -> 'a t -> bool -``` -`mem a set` is true if and only if `a` is structurally equal to an element of `set` (i.e. there is an `x` in `set` such that `compare a x = 0`). - -since 5.3 -``` -val memq : 'a -> 'a t -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare array elements. - -since 5.3 -``` -val find_opt : ('a -> bool) -> 'a t -> 'a option -``` -`find_opt f a` returns the first element of the array `a` that satisfies the predicate `f`, or `None` if there is no value that satisfies `f` in the array `a`. - -since 5.3 -``` -val find_index : ('a -> bool) -> 'a t -> int option -``` -`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.3 -``` -val find_map : ('a -> 'b option) -> 'a t -> 'b option -``` -`find_map f a` applies `f` to the elements of `a` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 5.3 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.3 - -## Comparison functions - -Comparison functions iterate over their arguments; it is a programming error to change their length during the iteration, see the [Iteration](./#iteration) section above. - -``` -val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal eq a b` holds when `a` and `b` have the same length, and for all indices `i` we have `eq (get a i) (get b i)`. - -since 5.3 -``` -val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Provided the function `cmp` defines a preorder on elements, `compare cmp a b` compares first `a` and `b` by their length, and then, if equal, by their elements according to the lexicographic preorder. - -For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). - -since 5.3 - -## Conversions to other data structures - -Note: the `of_*` functions raise `Invalid_argument` if the length needs to grow beyond [`Sys.max_array_length`](./Stdlib-Sys.md#val-max_array_length). - -The `to_*` functions, except those specifically marked "reentrant", iterate on their dynarray argument. In particular it is a programming error if the length of the dynarray changes during their execution, and the conversion functions raise `Invalid_argument` if they observe such a change. - -``` -val of_array : 'a array -> 'a t -``` -`of_array arr` returns a dynamic array corresponding to the fixed-sized array `a`. Operates in `O(n)` time by making a copy. - -``` -val to_array : 'a t -> 'a array -``` -`to_array a` returns a fixed-sized array corresponding to the dynamic array `a`. This always allocate a new array and copies elements into it. - -``` -val of_list : 'a list -> 'a t -``` -`of_list l` is the array containing the elements of `l` in the same order. - -``` -val to_list : 'a t -> 'a list -``` -`to_list a` is a list with the elements contained in the array `a`. - -``` -val of_seq : 'a Seq.t -> 'a t -``` -`of_seq seq` is an array containing the same elements as `seq`. - -It traverses `seq` once and will terminate only if `seq` is finite. - -``` -val to_seq : 'a t -> 'a Seq.t -``` -`to_seq a` is the sequence of elements `get a 0`, `get a 1`... `get a (length a - 1)`. - -``` -val to_seq_reentrant : 'a t -> 'a Seq.t -``` -`to_seq_reentrant a` is a reentrant variant of [`to_seq`](./#val-to_seq), in the sense that one may still access its elements after the length of `a` has changed. - -Demanding the `i`\-th element of the resulting sequence (which can happen zero, one or several times) will access the `i`\-th element of `a` at the time of the demand. The sequence stops if `a` has less than `i` elements at this point. - -``` -val to_seq_rev : 'a t -> 'a Seq.t -``` -`to_seq_rev a` is the sequence of elements `get a (l - 1)`, `get a (l - 2)`... `get a 0`, where `l` is `length a` at the time `to_seq_rev` is invoked. - -``` -val to_seq_rev_reentrant : 'a t -> 'a Seq.t -``` -`to_seq_rev_reentrant a` is a reentrant variant of [`to_seq_rev`](./#val-to_seq_rev), in the sense that one may still access its elements after the length of `a` has changed. - -Elements that have been removed from the array by the time they are demanded in the sequence are skipped. - - -## Advanced topics for performance - - -### Backing array, capacity - -Internally, a dynamic array uses a **backing array** (a fixed-size array as provided by the [`Array`](./Stdlib-Array.md) module) whose length is greater or equal to the length of the dynamic array. We define the **capacity** of a dynamic array as the length of its backing array. - -The capacity of a dynamic array is relevant in advanced scenarios, when reasoning about the performance of dynamic array programs: - -- The memory usage of a dynamic array is proportional to its capacity, rather than its length. -- When there is no empty space left at the end of the backing array, adding elements requires allocating a new, larger backing array. -The implementation uses a standard exponential reallocation strategy which guarantees amortized constant-time operation; in particular, the total capacity of all backing arrays allocated over the lifetime of a dynamic array is at worst proportional to the total number of elements added. - -In other words, users need not care about capacity and reallocations, and they will get reasonable behavior by default. However, in some performance-sensitive scenarios the functions below can help control memory usage or guarantee an optimal number of reallocations. - -``` -val capacity : 'a t -> int -``` -`capacity a` is the length of `a`'s backing array. - -``` -val ensure_capacity : 'a t -> int -> unit -``` -`ensure_capacity a n` makes sure that the capacity of `a` is at least `n`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the requested capacity is outside the range 0 .. Sys.max\_array\_length. -An example would be to reimplement [`of_array`](./#val-of_array) without using [`init`](./#val-init): - -```ocaml -let of_array arr = - let a = Dynarray.create () in - Dynarray.ensure_capacity a (Array.length arr); - Array.iter (fun v -> add_last a v) arr -``` -Using `ensure_capacity` guarantees that at most one reallocation will take place, instead of possibly several. - -Without this `ensure_capacity` hint, the number of resizes would be logarithmic in the length of `arr`, creating a constant-factor slowdown noticeable when `arr` is large. - -``` -val ensure_extra_capacity : 'a t -> int -> unit -``` -`ensure_extra_capacity a n` is `ensure_capacity a (length a + n)`, it makes sure that `a` has room for `n` extra items. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the total requested capacity is outside the range 0 .. Sys.max\_array\_length. -A use case would be to implement [`append_array`](./#val-append_array): - -```ocaml -let append_array a arr = - ensure_extra_capacity a (Array.length arr); - Array.iter (fun v -> add_last a v) arr -``` -``` -val fit_capacity : 'a t -> unit -``` -`fit_capacity a` reallocates a backing array if necessary, so that the resulting capacity is exactly `length a`, with no additional empty space at the end. This can be useful to make sure there is no memory wasted on a long-lived array. - -Note that calling `fit_capacity` breaks the amortized complexity guarantees provided by the default reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. - -If you know that a dynamic array has reached its final length, which will remain fixed in the future, it is sufficient to call `to_array` and only keep the resulting fixed-size array. `fit_capacity` is useful when you need to keep a dynamic array for eventual future resizes. - -``` -val set_capacity : 'a t -> int -> unit -``` -`set_capacity a n` reallocates a backing array if necessary, so that the resulting capacity is exactly `n`. In particular, all elements of index `n` or greater are removed. - -Like [`fit_capacity`](./#val-fit_capacity), this function breaks the amortized complexity guarantees provided by the reallocation strategy. Calling it repeatedly on an array may have quadratic complexity, both in time and in total number of words allocated. - -This is an advanced function; in particular, [`ensure_capacity`](./#val-ensure_capacity) should be preferred to increase the capacity, as it preserves those amortized guarantees. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0. -``` -val reset : 'a t -> unit -``` -`reset a` clears `a` and replaces its backing array by an empty array. - -It is equivalent to `set_capacity a 0` or `clear a; fit_capacity a`. - - -### No leaks: preservation of memory liveness - -The user-provided values reachable from a dynamic array `a` are exactly the elements in the indices `0` to `length a - 1`. In particular, no user-provided values are "leaked" by being present in the backing array at index `length a` or later. - - -## Code examples - - -### Min-heaps for mutable priority queues - -We can use dynamic arrays to implement a mutable priority queue. A priority queue provides a function to add elements, and a function to extract the minimum element \-- according to some comparison function. - -```ocaml -(* We present our priority queues as a functor - parametrized on the comparison function. *) -module Heap (Elem : Map.OrderedType) : sig - type t - val create : unit -> t - val add : t -> Elem.t -> unit - val pop_min : t -> Elem.t option -end = struct - - (* Our priority queues are implemented using the standard "min heap" - data structure, a dynamic array representing a binary tree. *) - type t = Elem.t Dynarray.t - let create = Dynarray.create - - (* The node of index [i] has as children the nodes of index [2 * i + 1] - and [2 * i + 2] -- if they are valid indices in the dynarray. *) - let left_child i = 2 * i + 1 - let right_child i = 2 * i + 2 - let parent_node i = (i - 1) / 2 - - (* We use indexing operators for convenient notations. *) - let ( .!() ) = Dynarray.get - let ( .!()<- ) = Dynarray.set - - (* Auxiliary functions to compare and swap two elements - in the dynamic array. *) - let order h i j = - Elem.compare h.!(i) h.!(j) - - let swap h i j = - let v = h.!(i) in - h.!(i) <- h.!(j); - h.!(j) <- v - - (* We say that a heap respects the "heap ordering" if the value of - each node is smaller than the value of its children. The - algorithm manipulates arrays that respect the heap algorithm, - except for one node whose value may be too small or too large. - - The auxiliary functions [heap_up] and [heap_down] take - such a misplaced value, and move it "up" (respectively: "down") - the tree by permuting it with its parent value (respectively: - a child value) until the heap ordering is restored. *) - - let rec heap_up h i = - if i = 0 then () else - let parent = parent_node i in - if order h i parent < 0 then - (swap h i parent; heap_up h parent) - - and heap_down h ~len i = - let left, right = left_child i, right_child i in - if left >= len then () (* no child, stop *) else - let smallest = - if right >= len then left (* no right child *) else - if order h left right < 0 then left else right - in - if order h i smallest > 0 then - (swap h i smallest; heap_down h ~len smallest) - - let add h s = - let i = Dynarray.length h in - Dynarray.add_last h s; - heap_up h i - - let pop_min h = - if Dynarray.is_empty h then None - else begin - (* Standard trick: swap the 'best' value at index 0 - with the last value of the array. *) - let last = Dynarray.length h - 1 in - swap h 0 last; - (* At this point [pop_last] returns the 'best' value, - and leaves a heap with one misplaced element at index [0]. *) - let best = Dynarray.pop_last h in - (* Restore the heap ordering -- does nothing if the heap is empty. *) - heap_down h ~len:last 0; - Some best - end -end -``` -The production code from which this example was inspired includes logic to free the backing array when the heap becomes empty, only in the case where the capacity is above a certain threshold. This can be done by calling the following function from `pop`: - -```ocaml -let shrink h = - if Dynarray.length h = 0 && Dynarray.capacity h > 1 lsl 18 then - Dynarray.reset h -``` -The `Heap` functor can be used to implement a sorting function, by adding all elements into a priority queue and then extracting them in order. - -```ocaml -let heap_sort (type a) cmp li = - let module Heap = Heap(struct type t = a let compare = cmp end) in - let heap = Heap.create () in - List.iter (Heap.add heap) li; - List.map (fun _ -> Heap.pop_min heap |> Option.get) li -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Either.md b/docs/api/re/melange/Stdlib-Either.md deleted file mode 100644 index 444260295..000000000 --- a/docs/api/re/melange/Stdlib-Either.md +++ /dev/null @@ -1,115 +0,0 @@ - -# Module `Stdlib.Either` - -Either type. - -Either is the simplest and most generic sum/variant type: a value of `('a, 'b) Either.t` is either a `Left (v : 'a)` or a `Right (v : 'b)`. - -It is a natural choice in the API of generic functions where values could fall in two different cases, possibly at different types, without assigning a specific meaning to what each case should be. - -For example: - -```ocaml -List.partition_map: - ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list -``` -If you are looking for a parametrized type where one alternative means success and the other means failure, you should use the more specific type [`Result.t`](./Stdlib-Result.md#type-t). - -since 4.12 -``` -type ('a, 'b) t = -``` -``` -| Left of 'a -``` -``` -| Right of 'b -``` -``` - -``` -A value of `('a, 'b) Either.t` contains either a value of `'a` or a value of `'b` - -``` -val left : 'a -> ('a, 'b) t -``` -`left v` is `Left v`. - -``` -val right : 'b -> ('a, 'b) t -``` -`right v` is `Right v`. - -``` -val is_left : ('a, 'b) t -> bool -``` -`is_left (Left v)` is `true`, `is_left (Right v)` is `false`. - -``` -val is_right : ('a, 'b) t -> bool -``` -`is_right (Left v)` is `false`, `is_right (Right v)` is `true`. - -``` -val find_left : ('a, 'b) t -> 'a option -``` -`find_left (Left v)` is `Some v`, `find_left (Right _)` is `None` - -``` -val find_right : ('a, 'b) t -> 'b option -``` -`find_right (Right v)` is `Some v`, `find_right (Left _)` is `None` - -``` -val map_left : ('a1 -> 'a2) -> ('a1, 'b) t -> ('a2, 'b) t -``` -`map_left f e` is `Left (f v)` if `e` is `Left v` and `e` if `e` is `Right _`. - -``` -val map_right : ('b1 -> 'b2) -> ('a, 'b1) t -> ('a, 'b2) t -``` -`map_right f e` is `Right (f v)` if `e` is `Right v` and `e` if `e` is `Left _`. - -``` -val map : - left:('a1 -> 'a2) -> - right:('b1 -> 'b2) -> - ('a1, 'b1) t -> - ('a2, 'b2) t -``` -`map ~left ~right (Left v)` is `Left (left v)`, `map ~left ~right (Right v)` is `Right (right v)`. - -``` -val fold : left:('a -> 'c) -> right:('b -> 'c) -> ('a, 'b) t -> 'c -``` -`fold ~left ~right (Left v)` is `left v`, and `fold ~left ~right (Right v)` is `right v`. - -``` -val iter : left:('a -> unit) -> right:('b -> unit) -> ('a, 'b) t -> unit -``` -`iter ~left ~right (Left v)` is `left v`, and `iter ~left ~right (Right v)` is `right v`. - -``` -val for_all : left:('a -> bool) -> right:('b -> bool) -> ('a, 'b) t -> bool -``` -`for_all ~left ~right (Left v)` is `left v`, and `for_all ~left ~right (Right v)` is `right v`. - -``` -val equal : - left:('a -> 'a -> bool) -> - right:('b -> 'b -> bool) -> - ('a, 'b) t -> - ('a, 'b) t -> - bool -``` -`equal ~left ~right e0 e1` tests equality of `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _` and `Right _`. - -``` -val compare : - left:('a -> 'a -> int) -> - right:('b -> 'b -> int) -> - ('a, 'b) t -> - ('a, 'b) t -> - int -``` -`compare ~left ~right e0 e1` totally orders `e0` and `e1` using `left` and `right` to respectively compare values wrapped by `Left _ ` and `Right _`. `Left _` values are smaller than `Right _` values. diff --git a/docs/api/re/melange/Stdlib-Filename.md b/docs/api/re/melange/Stdlib-Filename.md deleted file mode 100644 index f56fdfaec..000000000 --- a/docs/api/re/melange/Stdlib-Filename.md +++ /dev/null @@ -1,167 +0,0 @@ - -# Module `Stdlib.Filename` - -Operations on file names. - -``` -val current_dir_name : string -``` -The conventional name for the current directory (e.g. `.` in Unix). - -``` -val parent_dir_name : string -``` -The conventional name for the parent of the current directory (e.g. `..` in Unix). - -``` -val dir_sep : string -``` -The directory separator (e.g. `/` in Unix). - -since 3.11.2 -``` -val concat : string -> string -> string -``` -`concat dir file` returns a file name that designates file `file` in directory `dir`. - -``` -val is_relative : string -> bool -``` -Return `true` if the file name is relative to the current directory, `false` if it is absolute (i.e. in Unix, starts with `/`). - -``` -val is_implicit : string -> bool -``` -Return `true` if the file name is relative and does not start with an explicit reference to the current directory (`./` or `../` in Unix), `false` if it starts with an explicit reference to the root directory or the current directory. - -``` -val check_suffix : string -> string -> bool -``` -`check_suffix name suff` returns `true` if the filename `name` ends with the suffix `suff`. - -Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. - -``` -val chop_suffix : string -> string -> string -``` -`chop_suffix name suff` removes the suffix `suff` from the filename `name`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if name does not end with the suffix suff. -``` -val chop_suffix_opt : suffix:string -> string -> string option -``` -`chop_suffix_opt ~suffix filename` removes the suffix from the `filename` if possible, or returns `None` if the filename does not end with the suffix. - -Under Windows ports (including Cygwin), comparison is case-insensitive, relying on `String.lowercase_ascii`. Note that this does not match exactly the interpretation of case-insensitive filename equivalence from Windows. - -since 4.08 -``` -val extension : string -> string -``` -`extension name` is the shortest suffix `ext` of `name0` where: - -- `name0` is the longest suffix of `name` that does not contain a directory separator; -- `ext` starts with a period; -- `ext` is preceded by at least one non-period character in `name0`. -If such a suffix does not exist, `extension name` is the empty string. - -since 4.04 -``` -val remove_extension : string -> string -``` -Return the given file name without its extension, as defined in [`Filename.extension`](./#val-extension). If the extension is empty, the function returns the given file name. - -The following invariant holds for any file name `s`: - -`remove_extension s ^ extension s = s` - -since 4.04 -``` -val chop_extension : string -> string -``` -Same as [`Filename.remove_extension`](./#val-remove_extension), but raise `Invalid_argument` if the given name has an empty extension. - -``` -val basename : string -> string -``` -Split a file name into directory name / base file name. If `name` is a valid file name, then `concat (dirname name) (basename name)` returns a file name which is equivalent to `name`. Moreover, after setting the current directory to `dirname name` (with [`Sys.chdir`](./Stdlib-Sys.md#val-chdir)), references to `basename name` (which is a relative file name) designate the same file as `name` before the call to [`Sys.chdir`](./Stdlib-Sys.md#val-chdir). - -This function conforms to the specification of POSIX.1-2008 for the `basename` utility. - -``` -val dirname : string -> string -``` -See [`Filename.basename`](./#val-basename). This function conforms to the specification of POSIX.1-2008 for the `dirname` utility. - -``` -val null : string -``` -`null` is `"/dev/null"` on POSIX and `"NUL"` on Windows. It represents a file on the OS that discards all writes and returns end of file on reads. - -since 4.10 -``` -val temp_file : ?temp_dir:string -> string -> string -> string -``` -`temp_file prefix suffix` returns the name of a fresh temporary file in the temporary directory. The base name of the temporary file is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary file is created empty, with permissions `0o600` (readable and writable only by the file owner). The file is guaranteed to be different from any other file that existed when `temp_file` was called. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be created. -before 3.11.2 no ?temp\_dir optional argument -``` -val open_temp_file : - ?mode:open_flag list -> - ?perms:int -> - ?temp_dir:string -> - string -> - string -> - string * out_channel -``` -Same as [`Filename.temp_file`](./#val-temp_file), but returns both the name of a fresh temporary file, and an output channel opened (atomically) on this file. This function is more secure than `temp_file`: there is no risk that the temporary file will be modified (e.g. replaced by a symbolic link) before the program opens it. The optional argument `mode` is a list of additional flags to control the opening of the file. It can contain one or several of `Open_append`, `Open_binary`, and `Open_text`. The default is `[Open_text]` (open in text mode). The file is created with permissions `perms` (defaults to readable and writable only by the file owner, `0o600`). - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the file could not be opened. -before 4.03 no ?perms optional argument -before 3.11.2 no ?temp\_dir optional argument -``` -val temp_dir : ?temp_dir:string -> ?perms:int -> string -> string -> string -``` -`temp_dir prefix suffix` creates and returns the name of a fresh temporary directory with permissions `perms` (defaults to 0o700) inside `temp_dir`. The base name of the temporary directory is formed by concatenating `prefix`, then a suitably chosen integer number, then `suffix`. The optional argument `temp_dir` indicates the temporary directory to use, defaulting to the current result of [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name). The temporary directory is created empty, with permissions `0o700` (readable, writable, and searchable only by the file owner). The directory is guaranteed to be different from any other directory that existed when `temp_dir` was called. - -If temp\_dir does not exist, this function does not create it. Instead, it raises Sys\_error. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the directory could not be created. -since 5.1 -``` -val get_temp_dir_name : unit -> string -``` -The name of the temporary directory: Under Unix, the value of the `TMPDIR` environment variable, or "/tmp" if the variable is not set. Under Windows, the value of the `TEMP` environment variable, or "." if the variable is not set. The temporary directory can be changed with [`Filename.set_temp_dir_name`](./#val-set_temp_dir_name). - -since 4.00 -``` -val set_temp_dir_name : string -> unit -``` -Change the temporary directory returned by [`Filename.get_temp_dir_name`](./#val-get_temp_dir_name) and used by [`Filename.temp_file`](./#val-temp_file) and [`Filename.open_temp_file`](./#val-open_temp_file). The temporary directory is a domain-local value which is inherited by child domains. - -since 4.00 -``` -val quote : string -> string -``` -Return a quoted version of a file name, suitable for use as one argument in a command line, escaping all meta-characters. Warning: under Windows, the output is only suitable for use with programs that follow the standard Windows quoting conventions. - -``` -val quote_command : - string -> - ?stdin:string -> - ?stdout:string -> - ?stderr:string -> - string list -> - string -``` -`quote_command cmd args` returns a quoted command line, suitable for use as an argument to [`Sys.command`](./Stdlib-Sys.md#val-command), `Unix.system`, and the `Unix.open_process` functions. - -The string `cmd` is the command to call. The list `args` is the list of arguments to pass to this command. It can be empty. - -The optional arguments `?stdin` and `?stdout` and `?stderr` are file names used to redirect the standard input, the standard output, or the standard error of the command. If `~stdin:f` is given, a redirection `< f` is performed and the standard input of the command reads from file `f`. If `~stdout:f` is given, a redirection `> f` is performed and the standard output of the command is written to file `f`. If `~stderr:f` is given, a redirection `2> f` is performed and the standard error of the command is written to file `f`. If both `~stdout:f` and `~stderr:f` are given, with the exact same file name `f`, a `2>&1` redirection is performed so that the standard output and the standard error of the command are interleaved and redirected to the same file `f`. - -Under Unix and Cygwin, the command, the arguments, and the redirections if any are quoted using [`Filename.quote`](./#val-quote), then concatenated. Under Win32, additional quoting is performed as required by the `cmd.exe` shell that is called by [`Sys.command`](./Stdlib-Sys.md#val-command). - -raises [`Failure`](./Stdlib.md#exception-Failure) if the command cannot be escaped on the current platform. -since 4.10 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Float-Array.md b/docs/api/re/melange/Stdlib-Float-Array.md deleted file mode 100644 index 99c3234de..000000000 --- a/docs/api/re/melange/Stdlib-Float-Array.md +++ /dev/null @@ -1,330 +0,0 @@ - -# Module `Float.Array` - -Float arrays with packed representation. - -``` -type t = floatarray -``` -The type of float arrays with packed representation. - -since 4.08 -``` -val length : t -> int -``` -Return the length (number of elements) of the given floatarray. - -``` -val get : t -> int -> float -``` -`get a n` returns the element number `n` of floatarray `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val set : t -> int -> float -> unit -``` -`set a n x` modifies floatarray `a` in place, replacing element number `n` with `x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is outside the range 0 to (length a - 1). -``` -val make : int -> float -> t -``` -`make n x` returns a fresh floatarray of length `n`, initialized with `x`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. -``` -val create : int -> t -``` -`create n` returns a fresh floatarray of length `n`, with uninitialized data. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. -``` -val init : int -> (int -> float) -> t -``` -`init n f` returns a fresh floatarray of length `n`, with element number `i` initialized to the result of `f i`. In other terms, `init n f` tabulates the results of `f` applied to the integers `0` to `n-1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_floatarray\_length. -``` -val make_matrix : int -> int -> float -> t array -``` -`make_matrix dimx dimy e` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where all elements are initialized with `e`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. -since 5.2 -``` -val init_matrix : int -> int -> (int -> int -> float) -> t array -``` -`init_matrix dimx dimy f` returns a two-dimensional array (an array of arrays) with first dimension `dimx` and second dimension `dimy`, where the element at index (`x,y`) is initialized with `f x y`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if dimx or dimy is negative or greater than Sys.max\_floatarray\_length. -since 5.2 -``` -val append : t -> t -> t -``` -`append v1 v2` returns a fresh floatarray containing the concatenation of the floatarrays `v1` and `v2`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if length v1 + length v2 \> Sys.max\_floatarray\_length. -``` -val concat : t list -> t -``` -Same as [`append`](./#val-append), but concatenates a list of floatarrays. - -``` -val sub : t -> int -> int -> t -``` -`sub a pos len` returns a fresh floatarray of length `len`, containing the elements number `pos` to `pos + len - 1` of floatarray `a`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a; that is, if pos \< 0, or len \< 0, or pos + len \> length a. -``` -val copy : t -> t -``` -`copy a` returns a copy of `a`, that is, a fresh floatarray containing the same elements as `a`. - -``` -val fill : t -> int -> int -> float -> unit -``` -`fill a pos len x` modifies the floatarray `a` in place, storing `x` in elements number `pos` to `pos + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid subarray of a. -``` -val blit : t -> int -> t -> int -> int -> unit -``` -`blit src src_pos dst dst_pos len` copies `len` elements from floatarray `src`, starting at element number `src_pos`, to floatarray `dst`, starting at element number `dst_pos`. It works correctly even if `src` and `dst` are the same floatarray, and the source and destination chunks overlap. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if src\_pos and len do not designate a valid subarray of src, or if dst\_pos and len do not designate a valid subarray of dst. -``` -val to_list : t -> float list -``` -`to_list a` returns the list of all the elements of `a`. - -``` -val of_list : float list -> t -``` -`of_list l` returns a fresh floatarray containing the elements of `l`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the length of l is greater than Sys.max\_floatarray\_length. - -## Iterators - -``` -val iter : (float -> unit) -> t -> unit -``` -`iter f a` applies function `f` in turn to all the elements of `a`. It is equivalent to `f a.(0); f a.(1); ...; f a.(length a - 1); ()`. - -``` -val iteri : (int -> float -> unit) -> t -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied with the index of the element as first argument, and the element itself as second argument. - -``` -val map : (float -> float) -> t -> t -``` -`map f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. - -``` -val map_inplace : (float -> float) -> t -> unit -``` -`map_inplace f a` applies function `f` to all elements of `a`, and updates their values in place. - -since 5.1 -``` -val mapi : (int -> float -> float) -> t -> t -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -``` -val mapi_inplace : (int -> float -> float) -> t -> unit -``` -Same as [`map_inplace`](./#val-map_inplace), but the function is applied to the index of the element as first argument, and the element itself as second argument. - -since 5.1 -``` -val fold_left : ('acc -> float -> 'acc) -> 'acc -> t -> 'acc -``` -`fold_left f x init` computes `f (... (f (f x init.(0)) init.(1)) ...) init.(n-1)`, where `n` is the length of the floatarray `init`. - -``` -val fold_right : (float -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold_right f a init` computes `f a.(0) (f a.(1) ( ... (f a.(n-1) init) ...))`, where `n` is the length of the floatarray `a`. - - -## Iterators on two arrays - -``` -val iter2 : (float -> float -> unit) -> t -> t -> unit -``` -`Array.iter2 f a b` applies function `f` to all the elements of `a` and `b`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. -``` -val map2 : (float -> float -> float) -> t -> t -> t -``` -`map2 f a b` applies function `f` to all the elements of `a` and `b`, and builds a floatarray with the results returned by `f`: `[| f a.(0) b.(0); ...; f a.(length a - 1) b.(length b - 1)|]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the floatarrays are not the same size. - -## Array scanning - -``` -val for_all : (float -> bool) -> t -> bool -``` -`for_all f [|a1; ...; an|]` checks if all elements of the floatarray satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)`. - -``` -val exists : (float -> bool) -> t -> bool -``` -`exists f [|a1; ...; an|]` checks if at least one element of the floatarray satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)`. - -``` -val mem : float -> t -> bool -``` -`mem a set` is true if and only if there is an element of `set` that is structurally equal to `a`, i.e. there is an `x` in `set` such that `compare a x = 0`. - -``` -val mem_ieee : float -> t -> bool -``` -Same as [`mem`](./#val-mem), but uses IEEE equality instead of structural equality. - - -## Array searching - -``` -val find_opt : (float -> bool) -> t -> float option -``` -``` -val find_index : (float -> bool) -> t -> int option -``` -`find_index f a` returns `Some i`, where `i` is the index of the first element of the array `a` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : (float -> 'a option) -> t -> 'a option -``` -``` -val find_mapi : (int -> float -> 'a option) -> t -> 'a option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 - -## Sorting and shuffling - -``` -val sort : (float -> float -> int) -> t -> unit -``` -Sort a floatarray in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see below for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. After calling `sort`, the array is sorted in place in increasing order. `sort` is guaranteed to run in constant heap space and (at most) logarithmic stack space. - -The current implementation uses Heap Sort. It runs in constant stack space. - -Specification of the comparison function: Let `a` be the floatarray and `cmp` the comparison function. The following must be true for all `x`, `y`, `z` in `a` : - -- `cmp x y` \> 0 if and only if `cmp y x` \< 0 -- if `cmp x y` \>= 0 and `cmp y z` \>= 0 then `cmp x z` \>= 0 -When `sort` returns, `a` contains the same elements as before, reordered in such a way that for all i and j valid indices of `a` : - -- `cmp a.(i) a.(j)` \>= 0 if i \>= j -``` -val stable_sort : (float -> float -> int) -> t -> unit -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is stable (i.e. elements that compare equal are kept in their original order) and not guaranteed to run in constant heap space. - -The current implementation uses Merge Sort. It uses a temporary floatarray of length `n/2`, where `n` is the length of the floatarray. It is usually faster than the current implementation of [`sort`](./#val-sort). - -``` -val fast_sort : (float -> float -> int) -> t -> unit -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val shuffle : rand:(int -> int) -> t -> unit -``` -`shuffle rand a` randomly permutes `a`'s elements using `rand` for randomness. The distribution of permutations is uniform. - -`rand` must be such that a call to `rand n` returns a uniformly distributed random number in the range \[`0`;`n-1`\]. [`Random.int`](./Stdlib-Random.md#val-int) can be used for this (do not forget to [initialize](./Stdlib-Random.md#val-self_init) the generator). - -since 5.2 - -## Float arrays and Sequences - -``` -val to_seq : t -> float Seq.t -``` -Iterate on the floatarray, in increasing order. Modifications of the floatarray during iteration will be reflected in the sequence. - -``` -val to_seqi : t -> (int * float) Seq.t -``` -Iterate on the floatarray, in increasing order, yielding indices along elements. Modifications of the floatarray during iteration will be reflected in the sequence. - -``` -val of_seq : float Seq.t -> t -``` -Create an array from the generator. - -``` -val map_to_array : (float -> 'a) -> t -> 'a array -``` -`map_to_array f a` applies function `f` to all the elements of `a`, and builds an array with the results returned by `f`: `[| f a.(0); f a.(1); ...; f a.(length a - 1) |]`. - -``` -val map_from_array : ('a -> float) -> 'a array -> t -``` -`map_from_array f a` applies function `f` to all the elements of `a`, and builds a floatarray with the results returned by `f`. - - -## Arrays and concurrency safety - -Care must be taken when concurrently accessing float arrays from multiple domains: accessing an array will never crash a program, but unsynchronized accesses might yield surprising (non-sequentially-consistent) results. - - -### Atomicity - -Every float array operation that accesses more than one array element is not atomic. This includes iteration, scanning, sorting, splitting and combining arrays. - -For example, consider the following program: - -```ocaml -let size = 100_000_000 -let a = Float.Array.make size 1. -let update a f () = - Float.Array.iteri (fun i x -> Float.Array.set a i (f x)) a -let d1 = Domain.spawn (update a (fun x -> x +. 1.)) -let d2 = Domain.spawn (update a (fun x -> 2. *. x +. 1.)) -let () = Domain.join d1; Domain.join d2 -``` -After executing this code, each field of the float array `a` is either `2.`, `3.`, `4.` or `5.`. If atomicity is required, then the user must implement their own synchronization (for example, using [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -### Data races - -If two domains only access disjoint parts of the array, then the observed behaviour is the equivalent to some sequential interleaving of the operations from the two domains. - -A data race is said to occur when two domains access the same array element without synchronization and at least one of the accesses is a write. In the absence of data races, the observed behaviour is equivalent to some sequential interleaving of the operations from different domains. - -Whenever possible, data races should be avoided by using synchronization to mediate the accesses to the array elements. - -Indeed, in the presence of data races, programs will not crash but the observed behaviour may not be equivalent to any sequential interleaving of operations from different domains. Nevertheless, even in the presence of data races, a read operation will return the value of some prior write to that location with a few exceptions. - - -### Tearing - -Float arrays have two supplementary caveats in the presence of data races. - -First, the blit operation might copy an array byte-by-byte. Data races between such a blit operation and another operation might produce surprising values due to tearing: partial writes interleaved with other operations can create float values that would not exist with a sequential execution. - -For instance, at the end of - -```ocaml -let zeros = Float.Array.make size 0. -let max_floats = Float.Array.make size Float.max_float -let res = Float.Array.copy zeros -let d1 = Domain.spawn (fun () -> Float.Array.blit zeros 0 res 0 size) -let d2 = Domain.spawn (fun () -> Float.Array.blit max_floats 0 res 0 size) -let () = Domain.join d1; Domain.join d2 -``` -the `res` float array might contain values that are neither `0.` nor `max_float`. - -Second, on 32-bit architectures, getting or setting a field involves two separate memory accesses. In the presence of data races, the user may observe tearing on any operation. diff --git a/docs/api/re/melange/Stdlib-Float.md b/docs/api/re/melange/Stdlib-Float.md deleted file mode 100644 index 29ecfd718..000000000 --- a/docs/api/re/melange/Stdlib-Float.md +++ /dev/null @@ -1,482 +0,0 @@ - -# Module `Stdlib.Float` - -Floating-point arithmetic. - -OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... - -since 4.07 -``` -val zero : float -``` -The floating point 0. - -since 4.08 -``` -val one : float -``` -The floating-point 1\. - -since 4.08 -``` -val minus_one : float -``` -The floating-point \-1. - -since 4.08 -``` -val neg : float -> float -``` -Unary negation. - -``` -val add : float -> float -> float -``` -Floating-point addition. - -``` -val sub : float -> float -> float -``` -Floating-point subtraction. - -``` -val mul : float -> float -> float -``` -Floating-point multiplication. - -``` -val div : float -> float -> float -``` -Floating-point division. - -``` -val fma : float -> float -> float -> float -``` -`fma x y z` returns `x * y + z`, with a best effort for computing this expression with a single rounding, using either hardware instructions (providing full IEEE compliance) or a software emulation. - -On 64-bit Cygwin, 64-bit mingw-w64 and MSVC 2017 and earlier, this function may be emulated owing to known bugs on limitations on these platforms. Note: since software emulation of the fma is costly, make sure that you are using hardware fma support if performance matters. - -since 4.08 -``` -val rem : float -> float -> float -``` -`rem a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. - -``` -val succ : float -> float -``` -`succ x` returns the floating point number right after `x` i.e., the smallest floating-point number greater than `x`. See also [`next_after`](./#val-next_after). - -since 4.08 -``` -val pred : float -> float -``` -`pred x` returns the floating-point number right before `x` i.e., the greatest floating-point number smaller than `x`. See also [`next_after`](./#val-next_after). - -since 4.08 -``` -val abs : float -> float -``` -`abs f` returns the absolute value of `f`. - -``` -val infinity : float -``` -Positive infinity. - -``` -val neg_infinity : float -``` -Negative infinity. - -``` -val nan : float -``` -A special floating-point value denoting the result of an undefined operation such as `0.0 /. 0.0`. Stands for 'not a number'. Any floating-point operation with `nan` as argument returns `nan` as result, unless otherwise specified in IEEE 754 standard. As for floating-point comparisons, `=`, `<`, `<=`, `>` and `>=` return `false` and `<>` returns `true` if one or both of their arguments is `nan`. - -`nan` is `quiet_nan` since 5.1; it was a signaling NaN before. - -``` -val signaling_nan : float -``` -Signaling NaN. The corresponding signals do not raise OCaml exception, but the value can be useful for interoperability with C libraries. - -since 5.1 -``` -val quiet_nan : float -``` -Quiet NaN. - -since 5.1 -``` -val pi : float -``` -The constant pi. - -``` -val max_float : float -``` -The largest positive finite value of type `float`. - -``` -val min_float : float -``` -The smallest positive, non-zero, non-denormalized value of type `float`. - -``` -val epsilon : float -``` -The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. - -``` -val is_finite : float -> bool -``` -`is_finite x` is `true` if and only if `x` is finite i.e., not infinite and not [`nan`](./#val-nan). - -since 4.08 -``` -val is_infinite : float -> bool -``` -`is_infinite x` is `true` if and only if `x` is [`infinity`](./#val-infinity) or [`neg_infinity`](./#val-neg_infinity). - -since 4.08 -``` -val is_nan : float -> bool -``` -`is_nan x` is `true` if and only if `x` is not a number (see [`nan`](./#val-nan)). - -since 4.08 -``` -val is_integer : float -> bool -``` -`is_integer x` is `true` if and only if `x` is an integer. - -since 4.08 -``` -val of_int : int -> float -``` -Convert an integer to floating-point. - -``` -val to_int : float -> int -``` -Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. - -``` -val of_string : string -> float -``` -Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. The `_` (underscore) character can appear anywhere in the string and is ignored. Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of a float. -``` -val of_string_opt : string -> float option -``` -Same as `of_string`, but returns `None` instead of raising. - -``` -val to_string : float -> string -``` -Return a string representation of a floating-point number. - -This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). - -This function is an alias for [`Stdlib.string_of_float`](./Stdlib.md#val-string_of_float). - -``` -type fpclass = fpclass = -``` -``` -| FP_normal -``` -Normal number, none of the below - -``` -| FP_subnormal -``` -Number very close to 0.0, has reduced precision - -``` -| FP_zero -``` -Number is 0.0 or \-0.0 - -``` -| FP_infinite -``` -Number is positive or negative infinity - -``` -| FP_nan -``` -Not a number: result of an undefined operation - -``` - -``` -The five classes of floating-point numbers, as determined by the [`classify_float`](./#val-classify_float) function. - -``` -val classify_float : float -> fpclass -``` -Return the class of the given floating-point number: normal, subnormal, zero, infinite, or not a number. - -``` -val pow : float -> float -> float -``` -Exponentiation. - -``` -val sqrt : float -> float -``` -Square root. - -``` -val cbrt : float -> float -``` -Cube root. - -since 4.13 -``` -val exp : float -> float -``` -Exponential. - -``` -val exp2 : float -> float -``` -Base 2 exponential function. - -since 4.13 -``` -val log : float -> float -``` -Natural logarithm. - -``` -val log10 : float -> float -``` -Base 10 logarithm. - -``` -val log2 : float -> float -``` -Base 2 logarithm. - -since 4.13 -``` -val expm1 : float -> float -``` -`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. - -``` -val log1p : float -> float -``` -`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. - -``` -val cos : float -> float -``` -Cosine. Argument is in radians. - -``` -val sin : float -> float -``` -Sine. Argument is in radians. - -``` -val tan : float -> float -``` -Tangent. Argument is in radians. - -``` -val acos : float -> float -``` -Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. - -``` -val asin : float -> float -``` -Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan : float -> float -``` -Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan2 : float -> float -> float -``` -`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. - -``` -val hypot : float -> float -> float -``` -`hypot x y` returns `sqrt(x *. x +. y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. If one of `x` or `y` is infinite, returns `infinity` even if the other is `nan`. - -``` -val cosh : float -> float -``` -Hyperbolic cosine. Argument is in radians. - -``` -val sinh : float -> float -``` -Hyperbolic sine. Argument is in radians. - -``` -val tanh : float -> float -``` -Hyperbolic tangent. Argument is in radians. - -``` -val acosh : float -> float -``` -Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. - -since 4.13 -``` -val asinh : float -> float -``` -Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. - -since 4.13 -``` -val atanh : float -> float -``` -Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. - -since 4.13 -``` -val erf : float -> float -``` -Error function. The argument ranges over the entire real line. The result is always within `[-1.0, 1.0]`. - -since 4.13 -``` -val erfc : float -> float -``` -Complementary error function (`erfc x = 1 - erf x`). The argument ranges over the entire real line. The result is always within `[0.0, 2.0]`. - -since 4.13 -``` -val trunc : float -> float -``` -`trunc x` rounds `x` to the nearest integer whose absolute value is less than or equal to `x`. - -since 4.08 -``` -val round : float -> float -``` -`round x` rounds `x` to the nearest integer with ties (fractional values of 0.5) rounded away from zero, regardless of the current rounding direction. If `x` is an integer, `+0.`, `-0.`, `nan`, or infinite, `x` itself is returned. - -On 64-bit mingw-w64, this function may be emulated owing to a bug in the C runtime library (CRT) on this platform. - -since 4.08 -``` -val ceil : float -> float -``` -Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. - -``` -val floor : float -> float -``` -Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. - -``` -val next_after : float -> float -> float -``` -`next_after x y` returns the next representable floating-point value following `x` in the direction of `y`. More precisely, if `y` is greater (resp. less) than `x`, it returns the smallest (resp. largest) representable number greater (resp. less) than `x`. If `x` equals `y`, the function returns `y`. If `x` or `y` is `nan`, a `nan` is returned. Note that `next_after max_float infinity = infinity` and that `next_after 0. infinity` is the smallest denormalized positive number. If `x` is the smallest denormalized positive number, `next_after x 0. = 0.` - -since 4.08 -``` -val copy_sign : float -> float -> float -``` -`copy_sign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. - -``` -val sign_bit : float -> bool -``` -`sign_bit x` is `true` if and only if the sign bit of `x` is set. For example `sign_bit 1.` and `signbit 0.` are `false` while `sign_bit (-1.)` and `sign_bit (-0.)` are `true`. - -since 4.08 -``` -val frexp : float -> float * int -``` -`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. - -``` -val ldexp : float -> int -> float -``` -`ldexp x n` returns `x *. 2 ** n`. - -``` -val modf : float -> float * float -``` -`modf f` returns the pair of the fractional and integral part of `f`. - -``` -type t = float -``` -An alias for the type of floating-point numbers. - -``` -val compare : t -> t -> int -``` -`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. - -``` -val equal : t -> t -> bool -``` -The equal function for floating-point numbers, compared using [`compare`](./#val-compare). - -``` -val min : t -> t -> t -``` -`min x y` returns the minimum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `min (-0.) (+0.) = -0.` - -since 4.08 -``` -val max : float -> float -> float -``` -`max x y` returns the maximum of `x` and `y`. It returns `nan` when `x` or `y` is `nan`. Moreover `max (-0.) (+0.) = +0.` - -since 4.08 -``` -val min_max : float -> float -> float * float -``` -`min_max x y` is `(min x y, max x y)`, just more efficient. - -since 4.08 -``` -val min_num : t -> t -> t -``` -`min_num x y` returns the minimum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan`, `nan` is returned. Moreover `min_num (-0.) (+0.) = -0.` - -since 4.08 -``` -val max_num : t -> t -> t -``` -`max_num x y` returns the maximum of `x` and `y` treating `nan` as missing values. If both `x` and `y` are `nan` `nan` is returned. Moreover `max_num (-0.) (+0.) = +0.` - -since 4.08 -``` -val min_max_num : float -> float -> float * float -``` -`min_max_num x y` is `(min_num x y, max_num x y)`, just more efficient. Note that in particular `min_max_num x nan = (x, x)` and `min_max_num nan y = (y, y)`. - -since 4.08 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for floats, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for floats, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -``` -module Array : sig ... end -``` -Float arrays with packed representation. diff --git a/docs/api/re/melange/Stdlib-Format.md b/docs/api/re/melange/Stdlib-Format.md deleted file mode 100644 index 92440e239..000000000 --- a/docs/api/re/melange/Stdlib-Format.md +++ /dev/null @@ -1,1401 +0,0 @@ - -# Module `Stdlib.Format` - -Pretty-printing. - -If you are new to this module, see the [examples](./#examples) below. - -This module implements a pretty-printing facility to format values within ['pretty-printing boxes'](./#boxes) and ['semantic tags'](./#tags) combined with a set of [printf-like functions](./#fpp). The pretty-printer splits lines at specified [break hints](./#breaks), and indents lines according to the box structure. Similarly, [semantic tags](./#tags) can be used to decouple text presentation from its contents. - -This pretty-printing facility is implemented as an overlay on top of abstract [formatters](./#formatter) which provide basic output functions. Some formatters are predefined, notably: - -- [`std_formatter`](./#val-std_formatter) outputs to [stdout](./Stdlib.md#val-stdout) -- [`err_formatter`](./#val-err_formatter) outputs to [stderr](./Stdlib.md#val-stderr) -Most functions in the [`Format`](#) module come in two variants: a short version that operates on the current domain's standard formatter as obtained using [`get_std_formatter`](./#val-get_std_formatter) and the generic version prefixed by `pp_` that takes a formatter as its first argument. For the version that operates on the current domain's standard formatter, the call to [`get_std_formatter`](./#val-get_std_formatter) is delayed until the last argument is received. - -More formatters can be created with [`formatter_of_out_channel`](./#val-formatter_of_out_channel), [`formatter_of_buffer`](./#val-formatter_of_buffer), [`formatter_of_symbolic_output_buffer`](./#val-formatter_of_symbolic_output_buffer) or using [custom formatters](./#formatter). - -**Warning**: Since [formatters](./#formatter) contain mutable state, it is not thread-safe to use the same formatter on multiple domains in parallel without synchronization. - -If multiple domains write to the same output channel using the predefined formatters (as obtained by [`get_std_formatter`](./#val-get_std_formatter) or [`get_err_formatter`](./#val-get_err_formatter)), the output from the domains will be interleaved with each other at points where the formatters are flushed, such as with [`print_flush`](./#val-print_flush). This synchronization is not performed by formatters obtained from [`formatter_of_out_channel`](./#val-formatter_of_out_channel) (on the standard out channels or others). - - -## Introduction - -You may consider this module as providing an extension to the `printf` facility to provide automatic line splitting. The addition of pretty-printing annotations to your regular `printf` format strings gives you fancy indentation and line breaks. Pretty-printing annotations are described below in the documentation of the function [`Format.fprintf`](./#val-fprintf). - -You may also use the explicit pretty-printing box management and printing functions provided by this module. This style is more basic but more verbose than the concise `fprintf` format strings. - -For instance, the sequence `open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()` that prints `x = 1` within a pretty-printing box, can be abbreviated as `printf "@[%s@ %i@]@." "x =" 1`, or even shorter `printf "@[x =@ %i@]@." 1`. - -Rule of thumb for casual users of this library: - -- use simple pretty-printing boxes (as obtained by `open_box 0`); -- use simple break hints as obtained by `print_cut ()` that outputs a simple break hint, or by `print_space ()` that outputs a space indicating a break hint; -- once a pretty-printing box is open, display its material with basic printing functions (e. g. `print_int` and `print_string`); -- when the material for a pretty-printing box has been printed, call `close_box ()` to close the box; -- at the end of pretty-printing, flush the pretty-printer to display all the remaining material, e.g. evaluate `print_newline ()`. -The behavior of pretty-printing commands is unspecified if there is no open pretty-printing box. Each box opened by one of the `open_` functions below must be closed using `close_box` for proper formatting. Otherwise, some of the material printed in the boxes may not be output, or may be formatted incorrectly. - -In case of interactive use, each phrase is executed in the initial state of the standard pretty-printer: after each phrase execution, the interactive system closes all open pretty-printing boxes, flushes all pending text, and resets the standard pretty-printer. - -Warning: mixing calls to pretty-printing functions of this module with calls to [`Stdlib`](./Stdlib.md) low level output functions is error prone. - -The pretty-printing functions output material that is delayed in the pretty-printer queue and stacks in order to compute proper line splitting. In contrast, basic I/O output functions write directly in their output device. As a consequence, the output of a basic I/O function may appear before the output of a pretty-printing function that has been called before. For instance, ` Stdlib.print_string "<"; Format.print_string "PRETTY"; Stdlib.print_string ">"; Format.print_string "TEXT"; ` leads to output `<>PRETTYTEXT`. - - -## Formatters - -``` -type formatter -``` -Abstract data corresponding to a pretty-printer (also called a formatter) and all its machinery. See also [Defining formatters](./#formatter). - - -## Pretty-printing boxes - -The pretty-printing engine uses the concepts of pretty-printing box and break hint to drive indentation and line splitting behavior of the pretty-printer. - -Each different pretty-printing box kind introduces a specific line splitting policy: - -- within an *horizontal* box, break hints never split the line (but the line may be split in a box nested deeper), -- within a *vertical* box, break hints always split the line, -- within an *horizontal/vertical* box, if the box fits on the current line then break hints never split the line, otherwise break hint always split the line, -- within a *compacting* box, a break hint never splits the line, unless there is no more room on the current line. -Note that line splitting policy is box specific: the policy of a box does not rule the policy of inner boxes. For instance, if a vertical box is nested in an horizontal box, all break hints within the vertical box will split the line. - -Moreover, opening a box after the [maximum indentation limit](./#maxindent) splits the line whether or not the box would end up fitting on the line. - -``` -val pp_open_box : formatter -> int -> unit -``` -``` -val open_box : int -> unit -``` -`pp_open_box ppf d` opens a new compacting pretty-printing box with offset `d` in the formatter `ppf`. - -Within this box, the pretty-printer prints as much as possible material on every line. - -A break hint splits the line if there is no more room on the line to print the remainder of the box. - -Within this box, the pretty-printer emphasizes the box structure: if a structural box does not fit fully on a simple line, a break hint also splits the line if the splitting \``moves to the left'' (i.e. the new line gets an indentation smaller than the one of the current line). - -This box is the general purpose pretty-printing box. - -If the pretty-printer splits the line in the box, offset `d` is added to the current indentation. - -``` -val pp_close_box : formatter -> unit -> unit -``` -``` -val close_box : unit -> unit -``` -Closes the most recently open pretty-printing box. - -``` -val pp_open_hbox : formatter -> unit -> unit -``` -``` -val open_hbox : unit -> unit -``` -`pp_open_hbox ppf ()` opens a new 'horizontal' pretty-printing box. - -This box prints material on a single line. - -Break hints in a horizontal box never split the line. (Line splitting may still occur inside boxes nested deeper). - -``` -val pp_open_vbox : formatter -> int -> unit -``` -``` -val open_vbox : int -> unit -``` -`pp_open_vbox ppf d` opens a new 'vertical' pretty-printing box with offset `d`. - -This box prints material on as many lines as break hints in the box. - -Every break hint in a vertical box splits the line. - -If the pretty-printer splits the line in the box, `d` is added to the current indentation. - -``` -val pp_open_hvbox : formatter -> int -> unit -``` -``` -val open_hvbox : int -> unit -``` -`pp_open_hvbox ppf d` opens a new 'horizontal/vertical' pretty-printing box with offset `d`. - -This box behaves as an horizontal box if it fits on a single line, otherwise it behaves as a vertical box. - -If the pretty-printer splits the line in the box, `d` is added to the current indentation. - -``` -val pp_open_hovbox : formatter -> int -> unit -``` -``` -val open_hovbox : int -> unit -``` -`pp_open_hovbox ppf d` opens a new 'horizontal-or-vertical' pretty-printing box with offset `d`. - -This box prints material as much as possible on every line. - -A break hint splits the line if there is no more room on the line to print the remainder of the box. - -If the pretty-printer splits the line in the box, `d` is added to the current indentation. - - -## Formatting functions - -``` -val pp_print_string : formatter -> string -> unit -``` -``` -val print_string : string -> unit -``` -`pp_print_string ppf s` prints `s` in the current pretty-printing box. - -``` -val pp_print_substring : pos:int -> len:int -> formatter -> string -> unit -``` -``` -val print_substring : pos:int -> len:int -> string -> unit -``` -`pp_print_substring ~pos ~len ppf s` prints the substring of `s` that starts at position `pos` and stops at position `pos+len` in the current pretty-printing box. - -since 5.3 -``` -val pp_print_bytes : formatter -> bytes -> unit -``` -``` -val print_bytes : bytes -> unit -``` -`pp_print_bytes ppf b` prints `b` in the current pretty-printing box. - -since 4.13 -``` -val pp_print_as : formatter -> int -> string -> unit -``` -``` -val print_as : int -> string -> unit -``` -`pp_print_as ppf len s` prints `s` in the current pretty-printing box. The pretty-printer formats `s` as if it were of length `len`. - -``` -val pp_print_substring_as : - pos:int -> - len:int -> - formatter -> - int -> - string -> - unit -``` -``` -val print_substring_as : pos:int -> len:int -> int -> string -> unit -``` -`pp_print_substring_as ~first ~len ppf len_as s` prints the substring of `s` that starts at position `pos` and stop at position `pos+len` in the current pretty-printing box as if it were of length `len_as`. - -since 5.1 -``` -val pp_print_int : formatter -> int -> unit -``` -``` -val print_int : int -> unit -``` -Print an integer in the current pretty-printing box. - -``` -val pp_print_float : formatter -> float -> unit -``` -``` -val print_float : float -> unit -``` -Print a floating point number in the current pretty-printing box. - -``` -val pp_print_char : formatter -> char -> unit -``` -``` -val print_char : char -> unit -``` -Print a character in the current pretty-printing box. - -``` -val pp_print_bool : formatter -> bool -> unit -``` -``` -val print_bool : bool -> unit -``` -Print a boolean in the current pretty-printing box. - -``` -val pp_print_nothing : formatter -> unit -> unit -``` -Print nothing. - -since 5.2 - -## Break hints - -A 'break hint' tells the pretty-printer to output some space or split the line whichever way is more appropriate to the current pretty-printing box splitting rules. - -Break hints are used to separate printing items and are mandatory to let the pretty-printer correctly split lines and indent items. - -Simple break hints are: - -- the 'space': output a space or split the line if appropriate, -- the 'cut': split the line if appropriate. -Note: the notions of space and line splitting are abstract for the pretty-printing engine, since those notions can be completely redefined by the programmer. However, in the pretty-printer default setting, \``output a space'' simply means printing a space character (ASCII code 32) and \``split the line'' means printing a newline character (ASCII code 10). - -``` -val pp_print_space : formatter -> unit -> unit -``` -``` -val print_space : unit -> unit -``` -`pp_print_space ppf ()` emits a 'space' break hint: the pretty-printer may split the line at this point, otherwise it prints one space. - -`pp_print_space ppf ()` is equivalent to `pp_print_break ppf 1 0`. - -``` -val pp_print_cut : formatter -> unit -> unit -``` -``` -val print_cut : unit -> unit -``` -`pp_print_cut ppf ()` emits a 'cut' break hint: the pretty-printer may split the line at this point, otherwise it prints nothing. - -`pp_print_cut ppf ()` is equivalent to `pp_print_break ppf 0 0`. - -``` -val pp_print_break : formatter -> int -> int -> unit -``` -``` -val print_break : int -> int -> unit -``` -`pp_print_break ppf nspaces offset` emits a 'full' break hint: the pretty-printer may split the line at this point, otherwise it prints `nspaces` spaces. - -If the pretty-printer splits the line, `offset` is added to the current indentation. - -``` -val pp_print_custom_break : - formatter -> - fits:(string * int * string) -> - breaks:(string * int * string) -> - unit -``` -`pp_print_custom_break ppf ~fits:(s1, n, s2) ~breaks:(s3, m, s4)` emits a custom break hint: the pretty-printer may split the line at this point. - -If it does not split the line, then the `s1` is emitted, then `n` spaces, then `s2`. - -If it splits the line, then it emits the `s3` string, then an indent (according to the box rules), then an offset of `m` spaces, then the `s4` string. - -While `n` and `m` are handled by `formatter_out_functions.out_indent`, the strings will be handled by `formatter_out_functions.out_string`. This allows for a custom formatter that handles indentation distinctly, for example, outputs `
` tags or ` ` entities. - -The custom break is useful if you want to change which visible (non-whitespace) characters are printed in case of break or no break. For example, when printing a list ` [a; b; c] `, you might want to add a trailing semicolon when it is printed vertically: - -```ocaml -[ - a; - b; - c; -] -``` -You can do this as follows: - -```ocaml -printf "@[[@;<0 2>@[a;@,b;@,c@]%t]@]@\n" - (pp_print_custom_break ~fits:("", 0, "") ~breaks:(";", 0, "")) -``` -since 4.08 -``` -val pp_force_newline : formatter -> unit -> unit -``` -``` -val force_newline : unit -> unit -``` -Force a new line in the current pretty-printing box. - -The pretty-printer must split the line at this point, - -Not the normal way of pretty-printing, since imperative line splitting may interfere with current line counters and box size calculation. Using break hints within an enclosing vertical box is a better alternative. - -``` -val pp_print_if_newline : formatter -> unit -> unit -``` -``` -val print_if_newline : unit -> unit -``` -Execute the next formatting command if the preceding line has just been split. Otherwise, ignore the next formatting command. - - -## Pretty-printing termination - -``` -val pp_print_flush : formatter -> unit -> unit -``` -``` -val print_flush : unit -> unit -``` -End of pretty-printing: resets the pretty-printer to initial state. - -All open pretty-printing boxes are closed, all pending text is printed. In addition, the pretty-printer low level output device is flushed to ensure that all pending text is really displayed. - -Note: never use `print_flush` in the normal course of a pretty-printing routine, since the pretty-printer uses a complex buffering machinery to properly indent the output; manually flushing those buffers at random would conflict with the pretty-printer strategy and result to poor rendering. - -Only consider using `print_flush` when displaying all pending material is mandatory (for instance in case of interactive use when you want the user to read some text) and when resetting the pretty-printer state will not disturb further pretty-printing. - -Warning: If the output device of the pretty-printer is an output channel, repeated calls to `print_flush` means repeated calls to [`Stdlib.flush`](./Stdlib.md#val-flush) to flush the out channel; these explicit flush calls could foil the buffering strategy of output channels and could dramatically impact efficiency. - -``` -val pp_print_newline : formatter -> unit -> unit -``` -``` -val print_newline : unit -> unit -``` -End of pretty-printing: resets the pretty-printer to initial state. - -All open pretty-printing boxes are closed, all pending text is printed. - -Equivalent to [`print_flush`](./#val-print_flush) with a new line emitted on the pretty-printer low-level output device immediately before the device is flushed. See corresponding words of caution for [`print_flush`](./#val-print_flush). - -Note: this is not the normal way to output a new line; the preferred method is using break hints within a vertical pretty-printing box. - - -## Margin - -``` -val pp_infinity : int -``` -`pp_infinity` is the maximal size of the margin. Its exact value is implementation dependent but is guaranteed to be greater than 109. - -since 5.2 -``` -val pp_set_margin : formatter -> int -> unit -``` -``` -val set_margin : int -> unit -``` -`pp_set_margin ppf d` sets the right margin to `d` (in characters): the pretty-printer splits lines that overflow the right margin according to the break hints given. Setting the margin to `d` means that the formatting engine aims at printing at most `d-1` characters per line. Nothing happens if `d` is smaller than 2. If `d >= `[`pp_infinity`](./#val-pp_infinity), the right margin is set to [`pp_infinity`](./#val-pp_infinity)` - 1`. If `d` is less than the current maximum indentation limit, the maximum indentation limit is decreased while trying to preserve a minimal ratio `max_indent/margin>=50%` and if possible the current difference `margin - max_indent`. - -See also [`pp_set_geometry`](./#val-pp_set_geometry). - -``` -val pp_get_margin : formatter -> unit -> int -``` -``` -val get_margin : unit -> int -``` -Returns the position of the right margin. - - -## Maximum indentation limit - -``` -val pp_set_max_indent : formatter -> int -> unit -``` -``` -val set_max_indent : int -> unit -``` -`pp_set_max_indent ppf d` sets the maximum indentation limit of lines to `d` (in characters): once this limit is reached, new pretty-printing boxes are rejected to the left, unless the enclosing box fully fits on the current line. As an illustration, - -```ocaml - set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." -``` -yields - -```ocaml - 123456 - 789A -``` -because the nested box `"@[7@]"` is opened after the maximum indentation limit (`7>5`) and its parent box does not fit on the current line. Either decreasing the length of the parent box to make it fit on a line: - -```ocaml - printf "@[123456@[7@]89@]@." -``` -or opening an intermediary box before the maximum indentation limit which fits on the current line - -```ocaml - printf "@[123@[456@[7@]89@]A@]@." -``` -avoids the rejection to the left of the inner boxes and print respectively `"123456789"` and `"123456789A"` . Note also that vertical boxes never fit on a line whereas horizontal boxes always fully fit on the current line. Opening a box may split a line whereas the contents may have fit. If this behavior is problematic, it can be curtailed by setting the maximum indentation limit to `margin - 1`. Note that setting the maximum indentation limit to `margin` is invalid. - -Nothing happens if `d` is smaller than 2. - -If `d` is greater than the current margin, it is ignored, and the current maximum indentation limit is kept. - -See also [`pp_set_geometry`](./#val-pp_set_geometry). - -``` -val pp_get_max_indent : formatter -> unit -> int -``` -``` -val get_max_indent : unit -> int -``` -Return the maximum indentation limit (in characters). - - -## Geometry - -Geometric functions can be used to manipulate simultaneously the coupled variables, margin and maximum indentation limit. - -``` -type geometry = { -``` -`max_indent : int;` -`margin : int;` -``` -} -``` -since 4.08 -``` -val check_geometry : geometry -> bool -``` -Check if the formatter geometry is valid: `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity) - -since 4.08 -``` -val pp_set_geometry : formatter -> max_indent:int -> margin:int -> unit -``` -``` -val set_geometry : max_indent:int -> margin:int -> unit -``` -``` -val pp_safe_set_geometry : formatter -> max_indent:int -> margin:int -> unit -``` -``` -val safe_set_geometry : max_indent:int -> margin:int -> unit -``` -`pp_set_geometry ppf ~max_indent ~margin` sets both the margin and maximum indentation limit for `ppf`. - -When `1 < max_indent < margin < `[`pp_infinity`](./#val-pp_infinity), `pp_set_geometry ppf ~max_indent ~margin` is equivalent to `pp_set_margin ppf margin; pp_set_max_indent ppf max_indent`; and avoids the subtly incorrect `pp_set_max_indent ppf max_indent; pp_set_margin ppf margin`; - -Outside of this domain, `pp_set_geometry` raises an invalid argument exception whereas `pp_safe_set_geometry` does nothing. - -since 4.08 -``` -val pp_update_geometry : formatter -> (geometry -> geometry) -> unit -``` -`pp_update_geometry ppf (fun geo -> { geo with ... })` lets you update a formatter's geometry in a way that is robust to extension of the `geometry` record with new fields. - -Raises an invalid argument exception if the returned geometry does not satisfy [`check_geometry`](./#val-check_geometry). - -since 4.11 -``` -val update_geometry : (geometry -> geometry) -> unit -``` -``` -val pp_get_geometry : formatter -> unit -> geometry -``` -``` -val get_geometry : unit -> geometry -``` -Return the current geometry of the formatter - -since 4.08 - -## Maximum formatting depth - -The maximum formatting depth is the maximum number of pretty-printing boxes simultaneously open. - -Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). - -``` -val pp_set_max_boxes : formatter -> int -> unit -``` -``` -val set_max_boxes : int -> unit -``` -`pp_set_max_boxes ppf max` sets the maximum number of pretty-printing boxes simultaneously open. - -Material inside boxes nested deeper is printed as an ellipsis (more precisely as the text returned by [`get_ellipsis_text`](./#val-get_ellipsis_text) `()`). - -Nothing happens if `max` is smaller than 2. - -``` -val pp_get_max_boxes : formatter -> unit -> int -``` -``` -val get_max_boxes : unit -> int -``` -Returns the maximum number of pretty-printing boxes allowed before ellipsis. - -``` -val pp_over_max_boxes : formatter -> unit -> bool -``` -``` -val over_max_boxes : unit -> bool -``` -Tests if the maximum number of pretty-printing boxes allowed have already been opened. - - -## Tabulation boxes - -A *tabulation box* prints material on lines divided into cells of fixed length. A tabulation box provides a simple way to display vertical columns of left adjusted text. - -This box features command `set_tab` to define cell boundaries, and command `print_tab` to move from cell to cell and split the line when there is no more cells to print on the line. - -Note: printing within tabulation box is line directed, so arbitrary line splitting inside a tabulation box leads to poor rendering. Yet, controlled use of tabulation boxes allows simple printing of columns within module [`Format`](#). - -``` -val pp_open_tbox : formatter -> unit -> unit -``` -``` -val open_tbox : unit -> unit -``` -`open_tbox ()` opens a new tabulation box. - -This box prints lines separated into cells of fixed width. - -Inside a tabulation box, special *tabulation markers* defines points of interest on the line (for instance to delimit cell boundaries). Function [`Format.set_tab`](./#val-set_tab) sets a tabulation marker at insertion point. - -A tabulation box features specific *tabulation breaks* to move to next tabulation marker or split the line. Function [`Format.print_tbreak`](./#val-print_tbreak) prints a tabulation break. - -``` -val pp_close_tbox : formatter -> unit -> unit -``` -``` -val close_tbox : unit -> unit -``` -Closes the most recently opened tabulation box. - -``` -val pp_set_tab : formatter -> unit -> unit -``` -``` -val set_tab : unit -> unit -``` -Sets a tabulation marker at current insertion point. - -``` -val pp_print_tab : formatter -> unit -> unit -``` -``` -val print_tab : unit -> unit -``` -`print_tab ()` emits a 'next' tabulation break hint: if not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right, or the pretty-printer splits the line and insertion point moves to the leftmost tabulation marker. - -It is equivalent to `print_tbreak 0 0`. - -``` -val pp_print_tbreak : formatter -> int -> int -> unit -``` -``` -val print_tbreak : int -> int -> unit -``` -`print_tbreak nspaces offset` emits a 'full' tabulation break hint. - -If not already set on a tabulation marker, the insertion point moves to the first tabulation marker on the right and the pretty-printer prints `nspaces` spaces. - -If there is no next tabulation marker on the right, the pretty-printer splits the line at this point, then insertion point moves to the leftmost tabulation marker of the box. - -If the pretty-printer splits the line, `offset` is added to the current indentation. - - -## Ellipsis - -``` -val pp_set_ellipsis_text : formatter -> string -> unit -``` -``` -val set_ellipsis_text : string -> unit -``` -Set the text of the ellipsis printed when too many pretty-printing boxes are open (a single dot, `.`, by default). - -``` -val pp_get_ellipsis_text : formatter -> unit -> string -``` -``` -val get_ellipsis_text : unit -> string -``` -Return the text of the ellipsis. - - -## Semantic tags - -``` -type stag = .. -``` -*Semantic tags* (or simply *tags*) are user's defined annotations to associate user's specific operations to printed entities. - -Common usage of semantic tags is text decoration to get specific font or text size rendering for a display device, or marking delimitation of entities (e.g. HTML or TeX elements or terminal escape sequences). More sophisticated usage of semantic tags could handle dynamic modification of the pretty-printer behavior to properly print the material within some specific tags. For instance, we can define an RGB tag like so: - -```ocaml -type stag += RGB of {r:int;g:int;b:int} -``` -In order to properly delimit printed entities, a semantic tag must be opened before and closed after the entity. Semantic tags must be properly nested like parentheses using [`pp_open_stag`](./#val-pp_open_stag) and [`pp_close_stag`](./#val-pp_close_stag). - -Tag specific operations occur any time a tag is opened or closed, At each occurrence, two kinds of operations are performed *tag-marking* and *tag-printing*: - -- The tag-marking operation is the simpler tag specific operation: it simply writes a tag specific string into the output device of the formatter. Tag-marking does not interfere with line-splitting computation. -- The tag-printing operation is the more involved tag specific operation: it can print arbitrary material to the formatter. Tag-printing is tightly linked to the current pretty-printer operations. -Roughly speaking, tag-marking is commonly used to get a better rendering of texts in the rendering device, while tag-printing allows fine tuning of printing routines to print the same entity differently according to the semantic tags (i.e. print additional material or even omit parts of the output). - -More precisely: when a semantic tag is opened or closed then both and successive 'tag-printing' and 'tag-marking' operations occur: - -- Tag-printing a semantic tag means calling the formatter specific function `print_open_stag` (resp. `print_close_stag`) with the name of the tag as argument: that tag-printing function can then print any regular material to the formatter (so that this material is enqueued as usual in the formatter queue for further line splitting computation). -- Tag-marking a semantic tag means calling the formatter specific function `mark_open_stag` (resp. `mark_close_stag`) with the name of the tag as argument: that tag-marking function can then return the 'tag-opening marker' (resp. \`tag-closing marker') for direct output into the output device of the formatter. -Being written directly into the output device of the formatter, semantic tag marker strings are not considered as part of the printing material that drives line splitting (in other words, the length of the strings corresponding to tag markers is considered as zero for line splitting). - -Thus, semantic tag handling is in some sense transparent to pretty-printing and does not interfere with usual indentation. Hence, a single pretty-printing routine can output both simple 'verbatim' material or richer decorated output depending on the treatment of tags. By default, tags are not active, hence the output is not decorated with tag information. Once `set_tags` is set to `true`, the pretty-printer engine honors tags and decorates the output accordingly. - -Default tag-marking functions behave the HTML way: [string tags](./#type-tag) are enclosed in "\<" and "\>" while other tags are ignored; hence, opening marker for tag string `"t"` is `""` and closing marker is `""`. - -Default tag-printing functions just do nothing. - -Tag-marking and tag-printing functions are user definable and can be set by calling [`set_formatter_stag_functions`](./#val-set_formatter_stag_functions). - -Semantic tag operations may be set on or off with [`set_tags`](./#val-set_tags). Tag-marking operations may be set on or off with [`set_mark_tags`](./#val-set_mark_tags). Tag-printing operations may be set on or off with [`set_print_tags`](./#val-set_print_tags). - -since 4.08 -``` -type tag = string -``` -``` -type stag += -``` -``` -| String_tag of tag -``` -`String_tag s` is a string tag `s`. String tags can be inserted either by explicitly using the constructor `String_tag` or by using the dedicated format syntax `"@{ ... @}"`. - -since 4.08 -``` - -``` -``` -val pp_open_stag : formatter -> stag -> unit -``` -``` -val open_stag : stag -> unit -``` -`pp_open_stag ppf t` opens the semantic tag named `t`. - -The `print_open_stag` tag-printing function of the formatter is called with `t` as argument; then the opening tag marker for `t`, as given by `mark_open_stag t`, is written into the output device of the formatter. - -since 4.08 -``` -val pp_close_stag : formatter -> unit -> unit -``` -``` -val close_stag : unit -> unit -``` -`pp_close_stag ppf ()` closes the most recently opened semantic tag `t`. - -The closing tag marker, as given by `mark_close_stag t`, is written into the output device of the formatter; then the `print_close_stag` tag-printing function of the formatter is called with `t` as argument. - -since 4.08 -``` -val pp_set_tags : formatter -> bool -> unit -``` -``` -val set_tags : bool -> unit -``` -`pp_set_tags ppf b` turns on or off the treatment of semantic tags (default is off). - -``` -val pp_set_print_tags : formatter -> bool -> unit -``` -``` -val set_print_tags : bool -> unit -``` -`pp_set_print_tags ppf b` turns on or off the tag-printing operations. - -``` -val pp_set_mark_tags : formatter -> bool -> unit -``` -``` -val set_mark_tags : bool -> unit -``` -`pp_set_mark_tags ppf b` turns on or off the tag-marking operations. - -``` -val pp_get_print_tags : formatter -> unit -> bool -``` -``` -val get_print_tags : unit -> bool -``` -Return the current status of tag-printing operations. - -``` -val pp_get_mark_tags : formatter -> unit -> bool -``` -``` -val get_mark_tags : unit -> bool -``` -Return the current status of tag-marking operations. - -``` -val pp_set_formatter_out_channel : formatter -> out_channel -> unit -``` -Redirecting the standard formatter output - -``` -val set_formatter_out_channel : out_channel -> unit -``` -Redirect the standard pretty-printer output to the given channel. (All the output functions of the standard formatter are set to the default output functions printing to the given channel.) - -`set_formatter_out_channel` is equivalent to [`pp_set_formatter_out_channel`](./#val-pp_set_formatter_out_channel) `std_formatter`. - -``` -val pp_set_formatter_output_functions : - formatter -> - (string -> int -> int -> unit) -> - (unit -> unit) -> - unit -``` -``` -val set_formatter_output_functions : - (string -> int -> int -> unit) -> - (unit -> unit) -> - unit -``` -`pp_set_formatter_output_functions ppf out flush` redirects the standard pretty-printer output functions to the functions `out` and `flush`. - -The `out` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. - -The `flush` function is called whenever the pretty-printer is flushed (via conversion `%!`, or pretty-printing indications `@?` or `@.`, or using low level functions `print_flush` or `print_newline`). - -``` -val pp_get_formatter_output_functions : - formatter -> - unit -> - (string -> int -> int -> unit) * (unit -> unit) -``` -``` -val get_formatter_output_functions : - unit -> - (string -> int -> int -> unit) * (unit -> unit) -``` -Return the current output functions of the standard pretty-printer. - - -## Redefining formatter output - -The `Format` module is versatile enough to let you completely redefine the meaning of pretty-printing output: you may provide your own functions to define how to handle indentation, line splitting, and even printing of all the characters that have to be printed\! - - -### Redefining output functions - -``` -type formatter_out_functions = { -``` -`out_string : string -> int -> int -> unit;` -`out_flush : unit -> unit;` -`out_newline : unit -> unit;` -`out_spaces : int -> unit;` -`out_indent : int -> unit;` -since 4.06 -``` -} -``` -The set of output functions specific to a formatter: - -- the `out_string` function performs all the pretty-printer string output. It is called with a string `s`, a start position `p`, and a number of characters `n`; it is supposed to output characters `p` to `p + n - 1` of `s`. -- the `out_flush` function flushes the pretty-printer output device. -- `out_newline` is called to open a new line when the pretty-printer splits the line. -- the `out_spaces` function outputs spaces when a break hint leads to spaces instead of a line split. It is called with the number of spaces to output. -- the `out_indent` function performs new line indentation when the pretty-printer splits the line. It is called with the indentation value of the new line. -By default: - -- fields `out_string` and `out_flush` are output device specific; (e.g. [`Stdlib.output_string`](./Stdlib.md#val-output_string) and [`Stdlib.flush`](./Stdlib.md#val-flush) for a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) device, or `Buffer.add_substring` and [`Stdlib.ignore`](./Stdlib.md#val-ignore) for a `Buffer.t` output device), -- field `out_newline` is equivalent to `out_string "\n" 0 1`; -- fields `out_spaces` and `out_indent` are equivalent to `out_string (String.make n ' ') 0 n`. -since 4.01 -``` -val pp_set_formatter_out_functions : - formatter -> - formatter_out_functions -> - unit -``` -``` -val set_formatter_out_functions : formatter_out_functions -> unit -``` -`pp_set_formatter_out_functions ppf out_funs` Set all the pretty-printer output functions of `ppf` to those of argument `out_funs`, - -This way, you can change the meaning of indentation (which can be something else than just printing space characters) and the meaning of new lines opening (which can be connected to any other action needed by the application at hand). - -Reasonable defaults for functions `out_spaces` and `out_newline` are respectively `out_funs.out_string (String.make n ' ') 0 n` and `out_funs.out_string "\n" 0 1`. - -since 4.01 -``` -val pp_get_formatter_out_functions : - formatter -> - unit -> - formatter_out_functions -``` -``` -val get_formatter_out_functions : unit -> formatter_out_functions -``` -Return the current output functions of the pretty-printer, including line splitting and indentation functions. Useful to record the current setting and restore it afterwards. - -since 4.01 - -## Redefining semantic tag operations - -``` -type formatter_stag_functions = { -``` -`mark_open_stag : stag -> string;` -`mark_close_stag : stag -> string;` -`print_open_stag : stag -> unit;` -`print_close_stag : stag -> unit;` -``` -} -``` -The semantic tag handling functions specific to a formatter: `mark` versions are the 'tag-marking' functions that associate a string marker to a tag in order for the pretty-printing engine to write those markers as 0 length tokens in the output device of the formatter. `print` versions are the 'tag-printing' functions that can perform regular printing when a tag is closed or opened. - -since 4.08 -``` -val pp_set_formatter_stag_functions : - formatter -> - formatter_stag_functions -> - unit -``` -``` -val set_formatter_stag_functions : formatter_stag_functions -> unit -``` -`pp_set_formatter_stag_functions ppf tag_funs` changes the meaning of opening and closing semantic tag operations to use the functions in `tag_funs` when printing on `ppf`. - -When opening a semantic tag with name `t`, the string `t` is passed to the opening tag-marking function (the `mark_open_stag` field of the record `tag_funs`), that must return the opening tag marker for that name. When the next call to `close_stag ()` happens, the semantic tag name `t` is sent back to the closing tag-marking function (the `mark_close_stag` field of record `tag_funs`), that must return a closing tag marker for that name. - -The `print_` field of the record contains the tag-printing functions that are called at tag opening and tag closing time, to output regular material in the pretty-printer queue. - -since 4.08 -``` -val pp_get_formatter_stag_functions : - formatter -> - unit -> - formatter_stag_functions -``` -``` -val get_formatter_stag_functions : unit -> formatter_stag_functions -``` -Return the current semantic tag operation functions of the standard pretty-printer. - -since 4.08 - -## Defining formatters - -Defining new formatters permits unrelated output of material in parallel on several output devices. All the parameters of a formatter are local to the formatter: right margin, maximum indentation limit, maximum number of pretty-printing boxes simultaneously open, ellipsis, and so on, are specific to each formatter and may be fixed independently. - -For instance, given a [`Buffer.t`](./Stdlib-Buffer.md#type-t) buffer `b`, [`formatter_of_buffer`](./#val-formatter_of_buffer) `b` returns a new formatter using buffer `b` as its output device. Similarly, given a [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) output channel `oc`, [`formatter_of_out_channel`](./#val-formatter_of_out_channel) `oc` returns a new formatter using channel `oc` as its output device. - -Alternatively, given `out_funs`, a complete set of output functions for a formatter, then [`formatter_of_out_functions`](./#val-formatter_of_out_functions) `out_funs` computes a new formatter using those functions for output. - -``` -val formatter_of_out_channel : out_channel -> formatter -``` -`formatter_of_out_channel oc` returns a new formatter writing to the corresponding output channel `oc`. - -``` -val synchronized_formatter_of_out_channel : - out_channel -> - formatter Domain.DLS.key -``` -`synchronized_formatter_of_out_channel oc` returns the key to the domain-local state that holds the domain-local formatter for writing to the corresponding output channel `oc`. - -When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -alert unstable -``` -val std_formatter : formatter -``` -The initial domain's standard formatter to write to standard output. - -It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stdout`](./Stdlib.md#val-stdout). - -``` -val get_std_formatter : unit -> formatter -``` -`get_std_formatter ()` returns the current domain's standard formatter used to write to standard output. - -since 5.0 -``` -val err_formatter : formatter -``` -The initial domain's formatter to write to standard error. - -It is defined as [`formatter_of_out_channel`](./#val-formatter_of_out_channel) [`Stdlib.stderr`](./Stdlib.md#val-stderr). - -``` -val get_err_formatter : unit -> formatter -``` -`get_err_formatter ()` returns the current domain's formatter used to write to standard error. - -since 5.0 -``` -val formatter_of_buffer : Buffer.t -> formatter -``` -`formatter_of_buffer b` returns a new formatter writing to buffer `b`. At the end of pretty-printing, the formatter must be flushed using [`pp_print_flush`](./#val-pp_print_flush) or [`pp_print_newline`](./#val-pp_print_newline), to print all the pending material into the buffer. - -``` -val stdbuf : Buffer.t -``` -The initial domain's string buffer in which `str_formatter` writes. - -``` -val get_stdbuf : unit -> Buffer.t -``` -`get_stdbuf ()` returns the current domain's string buffer in which the current domain's string formatter writes. - -since 5.0 -``` -val str_formatter : formatter -``` -The initial domain's formatter to output to the [`stdbuf`](./#val-stdbuf) string buffer. - -`str_formatter` is defined as [`formatter_of_buffer`](./#val-formatter_of_buffer) [`stdbuf`](./#val-stdbuf). - -``` -val get_str_formatter : unit -> formatter -``` -The current domain's formatter to output to the current domains string buffer. - -since 5.0 -``` -val flush_str_formatter : unit -> string -``` -Returns the material printed with `str_formatter` of the current domain, flushes the formatter and resets the corresponding buffer. - -``` -val make_formatter : - (string -> int -> int -> unit) -> - (unit -> unit) -> - formatter -``` -`make_formatter out flush` returns a new formatter that outputs with function `out`, and flushes with function `flush`. - -For instance, - -```ocaml - make_formatter - (Stdlib.output_substring oc) - (fun () -> Stdlib.flush oc) -``` -returns a formatter to the [`Stdlib.out_channel`](./Stdlib.md#type-out_channel) `oc`. - -``` -val make_synchronized_formatter : - (string -> int -> int -> unit) -> - (unit -> unit) -> - formatter Domain.DLS.key -``` -`make_synchronized_formatter out flush` returns the key to the domain-local state that holds the domain-local formatter that outputs with function `out`, and flushes with function `flush`. - -When the formatter is used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -since 5.0 -alert unstable -``` -val formatter_of_out_functions : formatter_out_functions -> formatter -``` -`formatter_of_out_functions out_funs` returns a new formatter that writes with the set of output functions `out_funs`. - -See definition of type [`formatter_out_functions`](./#type-formatter_out_functions) for the meaning of argument `out_funs`. - -since 4.06 - -### Symbolic pretty-printing - -Symbolic pretty-printing is pretty-printing using a symbolic formatter, i.e. a formatter that outputs symbolic pretty-printing items. - -When using a symbolic formatter, all regular pretty-printing activities occur but output material is symbolic and stored in a buffer of output items. At the end of pretty-printing, flushing the output buffer allows post-processing of symbolic output before performing low level output operations. - -In practice, first define a symbolic output buffer `b` using: - -- `let sob = make_symbolic_output_buffer ()`. Then define a symbolic formatter with: -- `let ppf = formatter_of_symbolic_output_buffer sob` -Use symbolic formatter `ppf` as usual, and retrieve symbolic items at end of pretty-printing by flushing symbolic output buffer `sob` with: - -- `flush_symbolic_output_buffer sob`. -``` -type symbolic_output_item = -``` -``` -| Output_flush -``` -symbolic flush command - -``` -| Output_newline -``` -symbolic newline command - -``` -| Output_string of string -``` -`Output_string s`: symbolic output for string `s` - -``` -| Output_spaces of int -``` -`Output_spaces n`: symbolic command to output `n` spaces - -``` -| Output_indent of int -``` -`Output_indent i`: symbolic indentation of size `i` - -``` - -``` -Items produced by symbolic pretty-printers - -since 4.06 -``` -type symbolic_output_buffer -``` -The output buffer of a symbolic pretty-printer. - -since 4.06 -``` -val make_symbolic_output_buffer : unit -> symbolic_output_buffer -``` -`make_symbolic_output_buffer ()` returns a fresh buffer for symbolic output. - -since 4.06 -``` -val clear_symbolic_output_buffer : symbolic_output_buffer -> unit -``` -`clear_symbolic_output_buffer sob` resets buffer `sob`. - -since 4.06 -``` -val get_symbolic_output_buffer : - symbolic_output_buffer -> - symbolic_output_item list -``` -`get_symbolic_output_buffer sob` returns the contents of buffer `sob`. - -since 4.06 -``` -val flush_symbolic_output_buffer : - symbolic_output_buffer -> - symbolic_output_item list -``` -`flush_symbolic_output_buffer sob` returns the contents of buffer `sob` and resets buffer `sob`. `flush_symbolic_output_buffer sob` is equivalent to `let items = get_symbolic_output_buffer sob in clear_symbolic_output_buffer sob; items` - -since 4.06 -``` -val add_symbolic_output_item : - symbolic_output_buffer -> - symbolic_output_item -> - unit -``` -`add_symbolic_output_item sob itm` adds item `itm` to buffer `sob`. - -since 4.06 -``` -val formatter_of_symbolic_output_buffer : symbolic_output_buffer -> formatter -``` -`formatter_of_symbolic_output_buffer sob` returns a symbolic formatter that outputs to `symbolic_output_buffer` `sob`. - -since 4.06 - -## Convenience formatting functions. - -``` -val pp_print_iter : - ?pp_sep:(formatter -> unit -> unit) -> - (('a -> unit) -> 'b -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'b -> - unit -``` -`pp_print_iter ~pp_sep iter pp_v ppf v` formats on `ppf` the iterations of `iter` over a collection `v` of values using `pp_v`. Iterations are separated by `pp_sep` (defaults to [`pp_print_cut`](./#val-pp_print_cut)). - -since 5.1 -``` -val pp_print_list : - ?pp_sep:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a list -> - unit -``` -`pp_print_list ?pp_sep pp_v ppf l` prints items of list `l`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty lists. - -since 4.02 -``` -val pp_print_array : - ?pp_sep:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a array -> - unit -``` -`pp_print_array ?pp_sep pp_v ppf a` prints items of array `a`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut)). Does nothing on empty arrays. - -If `a` is mutated after `pp_print_array` is called, the printed values may not be what is expected because `Format` can delay the printing. This can be avoided by flushing `ppf`. - -since 5.1 -``` -val pp_print_seq : - ?pp_sep:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a Seq.t -> - unit -``` -`pp_print_seq ?pp_sep pp_v ppf s` prints items of sequence `s`, using `pp_v` to print each item, and calling `pp_sep` between items (`pp_sep` defaults to [`pp_print_cut`](./#val-pp_print_cut). Does nothing on empty sequences. - -This function does not terminate on infinite sequences. - -since 4.12 -``` -val pp_print_text : formatter -> string -> unit -``` -`pp_print_text ppf s` prints `s` with spaces and newlines respectively printed using [`pp_print_space`](./#val-pp_print_space) and [`pp_force_newline`](./#val-pp_force_newline). - -since 4.02 -``` -val pp_print_option : - ?none:(formatter -> unit -> unit) -> - (formatter -> 'a -> unit) -> - formatter -> - 'a option -> - unit -``` -`pp_print_option ?none pp_v ppf o` prints `o` on `ppf` using `pp_v` if `o` is `Some v` and `none` if it is `None`. `none` prints nothing by default. - -since 4.08 -``` -val pp_print_result : - ok:(formatter -> 'a -> unit) -> - error:(formatter -> 'e -> unit) -> - formatter -> - ('a, 'e) result -> - unit -``` -`pp_print_result ~ok ~error ppf r` prints `r` on `ppf` using `ok` if `r` is `Ok _` and `error` if `r` is `Error _`. - -since 4.08 -``` -val pp_print_either : - left:(formatter -> 'a -> unit) -> - right:(formatter -> 'b -> unit) -> - formatter -> - ('a, 'b) Either.t -> - unit -``` -`pp_print_either ~left ~right ppf e` prints `e` on `ppf` using `left` if `e` is `Either.Left _` and `right` if `e` is `Either.Right _`. - -since 4.13 - -## Formatted pretty-printing - -Module `Format` provides a complete set of `printf` like functions for pretty-printing using format string specifications. - -Specific annotations may be added in the format strings to give pretty-printing commands to the pretty-printing engine. - -Those annotations are introduced in the format strings using the `@` character. For instance, `@ ` means a space break, `@,` means a cut, `@[` opens a new box, and `@]` closes the last open box. - -``` -val fprintf : formatter -> ('a, formatter, unit) format -> 'a -``` -`fprintf ff fmt arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `fmt`, and outputs the resulting string on the formatter `ff`. - -The format string `fmt` is a character string which contains three types of objects: plain characters and conversion specifications as specified in the [`Printf`](./Stdlib-Printf.md) module, and pretty-printing indications specific to the `Format` module. - -The pretty-printing indication characters are introduced by a `@` character, and their meanings are: - -- `@[`: open a pretty-printing box. The type and offset of the box may be optionally specified with the following syntax: the `<` character, followed by an optional box type indication, then an optional integer offset, and the closing `>` character. Pretty-printing box type is one of `h`, `v`, `hv`, `b`, or `hov`. '`h`' stands for an 'horizontal' pretty-printing box, '`v`' stands for a 'vertical' pretty-printing box, '`hv`' stands for an 'horizontal/vertical' pretty-printing box, '`b`' stands for an 'horizontal-or-vertical' pretty-printing box demonstrating indentation, '`hov`' stands a simple 'horizontal-or-vertical' pretty-printing box. For instance, `@[` opens an 'horizontal-or-vertical' pretty-printing box with indentation 2 as obtained with `open_hovbox 2`. For more details about pretty-printing boxes, see the various box opening functions `open_*box`. -- `@]`: close the most recently opened pretty-printing box. -- `@,`: output a 'cut' break hint, as with `print_cut ()`. -- `@ `: output a 'space' break hint, as with `print_space ()`. -- `@;`: output a 'full' break hint as with `print_break`. The `nspaces` and `offset` parameters of the break hint may be optionally specified with the following syntax: the `<` character, followed by an integer `nspaces` value, then an integer `offset`, and a closing `>` character. If no parameters are provided, the full break defaults to a 'space' break hint. -- `@.`: flush the pretty-printer and split the line, as with `print_newline ()`. -- `@`: print the following item as if it were of length `n`. Hence, `printf "@<0>%s" arg` prints `arg` as a zero length string. If `@` is not followed by a conversion specification, then the following character of the format is printed as if it were of length `n`. -- `@\{`: open a semantic tag. The name of the tag may be optionally specified with the following syntax: the `<` character, followed by an optional string specification, and the closing `>` character. The string specification is any character string that does not contain the closing character `'>'`. If omitted, the tag name defaults to the empty string. For more details about semantic tags, see the functions [`open_stag`](./#val-open_stag) and [`close_stag`](./#val-close_stag). -- `@\}`: close the most recently opened semantic tag. -- `@?`: flush the pretty-printer as with `print_flush ()`. This is equivalent to the conversion `%!`. -- `@\n`: force a newline, as with `force_newline ()`, not the normal way of pretty-printing, you should prefer using break hints inside a vertical pretty-printing box. -Note: To prevent the interpretation of a `@` character as a pretty-printing indication, escape it with a `%` character. Old quotation mode `@@` is deprecated since it is not compatible with formatted input interpretation of character `'@'`. - -Example: `printf "@[%s@ %d@]@." "x =" 1` is equivalent to `open_box (); print_string "x ="; print_space (); print_int 1; close_box (); print_newline ()`. It prints `x = 1` within a pretty-printing 'horizontal-or-vertical' box. - -``` -val printf : ('a, formatter, unit) format -> 'a -``` -Same as `fprintf` above, but output on `get_std_formatter ()`. - -It is defined similarly to `fun fmt -> fprintf (get_std_formatter ()) fmt` but delays calling `get_std_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -``` -val eprintf : ('a, formatter, unit) format -> 'a -``` -Same as `fprintf` above, but output on `get_err_formatter ()`. - -It is defined similarly to `fun fmt -> fprintf (get_err_formatter ()) fmt` but delays calling `get_err_formatter` until after the final argument required by the `format` is received. When used with multiple domains, the output from the domains will be interleaved with each other at points where the formatter is flushed, such as with [`print_flush`](./#val-print_flush). - -``` -val sprintf : ('a, unit, string) format -> 'a -``` -Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. Note that the pretty-printer queue is flushed at the end of *each call* to `sprintf`. Note that if your format string contains a `%a`, you should use `asprintf`. - -In case of multiple and related calls to `sprintf` to output material on a single string, you should consider using `fprintf` with the predefined formatter `str_formatter` and call `flush_str_formatter ()` to get the final result. - -Alternatively, you can use `Format.fprintf` with a formatter writing to a buffer of your own: flushing the formatter and the buffer at the end of pretty-printing returns the desired string. - -``` -val asprintf : ('a, formatter, unit, string) format4 -> 'a -``` -Same as `printf` above, but instead of printing on a formatter, returns a string containing the result of formatting the arguments. The type of `asprintf` is general enough to interact nicely with `%a` conversions. - -since 4.01 -``` -val dprintf : ('a, formatter, unit, formatter -> unit) format4 -> 'a -``` -Same as [`fprintf`](./#val-fprintf), except the formatter is the last argument. `dprintf "..." a b c` is a function of type `formatter -> unit` which can be given to a format specifier `%t`. - -This can be used as a replacement for [`asprintf`](./#val-asprintf) to delay formatting decisions. Using the string returned by [`asprintf`](./#val-asprintf) in a formatting context forces formatting decisions to be taken in isolation, and the final string may be created prematurely. [`dprintf`](./#val-dprintf) allows delay of formatting decisions until the final formatting context is known. For example: - -```ocaml - let t = Format.dprintf "%i@ %i@ %i" 1 2 3 in - ... - Format.printf "@[%t@]" t -``` -since 4.08 -``` -val ifprintf : formatter -> ('a, formatter, unit) format -> 'a -``` -Same as `fprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 3.10 -Formatted Pretty-Printing with continuations. - -``` -val kfprintf : - (formatter -> 'a) -> - formatter -> - ('b, formatter, unit, 'a) format4 -> - 'b -``` -Same as `fprintf` above, but instead of returning immediately, passes the formatter to its first argument at the end of printing. - -``` -val kdprintf : - ((formatter -> unit) -> 'a) -> - ('b, formatter, unit, 'a) format4 -> - 'b -``` -Same as [`dprintf`](./#val-dprintf) above, but instead of returning immediately, passes the suspended printer to its first argument at the end of printing. - -since 4.08 -``` -val ikfprintf : - (formatter -> 'a) -> - formatter -> - ('b, formatter, unit, 'a) format4 -> - 'b -``` -Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 3.12 -``` -val ksprintf : (string -> 'a) -> ('b, unit, string, 'a) format4 -> 'b -``` -Same as `sprintf` above, but instead of returning the string, passes it to the first argument. - -``` -val kasprintf : (string -> 'a) -> ('b, formatter, unit, 'a) format4 -> 'b -``` -Same as `asprintf` above, but instead of returning the string, passes it to the first argument. - -since 4.03 - -## Examples - -A few warmup examples to get an idea of how Format is used. - -We have a list `l` of pairs `(int * bool)`, which the toplevel prints for us: - -```ocaml -# let l = List.init 20 (fun n -> n, n mod 2 = 0) -val l : (int * bool) list = -[(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); - (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); - (12, true); (13, false); (14, true); (15, false); (16, true); (17, false); - (18, true); (19, false)] -``` -If we want to print it ourself without the toplevel magic, we can try this: - -```ocaml -# let pp_pair out (x,y) = Format.fprintf out "(%d, %b)" x y -val pp_pair : Format.formatter -> int * bool -> unit = -# Format.printf "l: [@[%a@]]@." - Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out ";@ ") pp_pair) l - l: [(0, true); (1, false); (2, true); (3, false); (4, true); (5, false); - (6, true); (7, false); (8, true); (9, false); (10, true); (11, false); - (12, true); (13, false); (14, true); (15, false); (16, true); - (17, false); (18, true); (19, false)] - -``` -What this does, briefly, is: - -- `pp_pair` prints a pair `bool*int` surrounded in "(" ")". It takes a formatter (into which formatting happens), and the pair itself. When printing is done it returns `()`. -- `Format.printf "l = [@[%a@]]@." ... l` is like `printf`, but with additional formatting instructions (denoted with "@"). The pair "`@[`" and "`@]`" is a "horizontal-or-vertical box". -- "@." ends formatting with a newline. It is similar to "\\n" but is also aware of the `Format.formatter`'s state. Do not use "\\n" with `Format`. -- "%a" is a formatting instruction, like "%d" or "%s" for `printf`. However, where "%d" prints an integer and "%s" prints a string, "%a" takes a printer (of type `Format.formatter -> 'a -> unit`) and a value (of type `'a`) and applies the printer to the value. This is key to compositionality of printers. -- We build a list printer using `Format.pp_print_list ~pp_sep:(...) pp_pair`. `pp_print_list` takes an element printer and returns a list printer. The `?pp_sep` optional argument, if provided, is called in between each element to print a separator. -- Here, for a separator, we use `(fun out () -> Format.fprintf out ";@ ")`. It prints ";", and then "@ " which is a breaking space (either it prints " ", or it prints a newline if the box is about to overflow). This "@ " is responsible for the list printing splitting into several lines. -If we omit "@ ", we get an ugly single-line print: - -```ocaml - # Format.printf "l: [@[%a@]]@." - Format.(pp_print_list ~pp_sep:(fun out () -> fprintf out "; ") pp_pair) l - l: [(0, true); (1, false); (2, true); (* ... *); (18, true); (19, false)] -- : unit = () -``` -Generally, it is good practice to define custom printers for important types in your program. If, for example, you were to define basic geometry types like so: - -```ocaml -type point = { - x: float; - y: float; -} - -type rectangle = { - ll: point; (* lower left *) - ur: point; (* upper right *) -} -``` -For debugging purpose, or to display information in logs, or on the console, it would be convenient to define printers for these types. Here is an example of to do it. Note that "%.3f" is a `float` printer up to 3 digits of precision after the dot; "%f" would print as many digits as required, which is somewhat verbose; "%h" is an hexadecimal float printer. - -```ocaml -let pp_point out (p:point) = - Format.fprintf out "{ @[x=%.3f;@ y=%.3f@] }" p.x p.y - -let pp_rectangle out (r:rectangle) = - Format.fprintf out "{ @[ll=%a;@ ur=%a@] }" - pp_point r.ll pp_point r.ur -``` -In the `.mli` file, we could have: - -```ocaml - val pp_point : Format.formatter -> point -> unit - - val pp_rectangle : Format.formatter -> rectangle -> unit -``` -These printers can now be used with "%a" inside other printers. - -```ocaml - # Format.printf "some rectangle: %a@." - (Format.pp_print_option pp_rectangle) - (Some {ll={x=1.; y=2.}; ur={x=42.; y=500.12345}}) -some rectangle: { l={ x=1.000; y=2.000 }; ur={ x=42.000; y=500.123 } } - -# Format.printf "no rectangle: %a@." - (Format.pp_option pp_rectangle) - None -no rectangle: -``` -See how we combine `pp_print_option` (option printer) and our newly defined rectangle printer, like we did with `pp_print_list` earlier. - -For a more extensive tutorial, see ["Using the Format module"](https://caml.inria.fr/resources/doc/guides/format.en.html). - -A final note: the `Format` module is a starting point. The OCaml ecosystem has libraries that makes formatting easier and more expressive, with more combinators, more concise names, etc. An example of such a library is [Fmt](https://erratique.ch/software/fmt). - -Automatic deriving of pretty-printers from type definitions is also possible, using [https://github.com/ocaml-ppx/ppx\_deriving](ppx_deriving.show) or similar ppx derivers. diff --git a/docs/api/re/melange/Stdlib-Fun.md b/docs/api/re/melange/Stdlib-Fun.md deleted file mode 100644 index ce11eb91e..000000000 --- a/docs/api/re/melange/Stdlib-Fun.md +++ /dev/null @@ -1,51 +0,0 @@ - -# Module `Stdlib.Fun` - -Function manipulation. - -since 4.08 - -## Combinators - -``` -val id : 'a -> 'a -``` -`id` is the identity function. For any argument `x`, `id x` is `x`. - -``` -val const : 'a -> _ -> 'a -``` -`const c` is a function that always returns the value `c`. For any argument `x`, `(const c) x` is `c`. - -``` -val compose : ('b -> 'c) -> ('a -> 'b) -> 'a -> 'c -``` -`compose f g` is a function composition of applying `g` then `f`. For any arguments `f`, `g`, and `x`, `compose f g x` is `f (g x)`. - -since 5.2 -``` -val flip : ('a -> 'b -> 'c) -> 'b -> 'a -> 'c -``` -`flip f` reverses the argument order of the binary function `f`. For any arguments `x` and `y`, `(flip f) x y` is `f y x`. - -``` -val negate : ('a -> bool) -> 'a -> bool -``` -`negate p` is the negation of the predicate function `p`. For any argument `x`, `(negate p) x` is `not (p x)`. - - -## Exception handling - -``` -val protect : finally:(unit -> unit) -> (unit -> 'a) -> 'a -``` -`protect ~finally work` invokes `work ()` and then `finally ()` before `work ()` returns with its value or an exception. In the latter case the exception is re-raised after `finally ()`. If `finally ()` raises an exception, then the exception [`Finally_raised`](./#exception-Finally_raised) is raised instead. - -`protect` can be used to enforce local invariants whether `work ()` returns normally or raises an exception. However, it does not protect against unexpected exceptions raised inside `finally ()` such as [`Stdlib.Out_of_memory`](./Stdlib.md#exception-Out_of_memory), [`Stdlib.Stack_overflow`](./Stdlib.md#exception-Stack_overflow), or asynchronous exceptions raised by signal handlers (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)). - -Note: It is a *programming error* if other kinds of exceptions are raised by `finally`, as any exception raised in `work ()` will be lost in the event of a [`Finally_raised`](./#exception-Finally_raised) exception. Therefore, one should make sure to handle those inside the finally. - -``` -exception Finally_raised of exn -``` -`Finally_raised exn` is raised by `protect ~finally work` when `finally` raises an exception `exn`. This exception denotes either an unexpected exception or a programming error. As a general rule, one should not catch a `Finally_raised` exception except as part of a catch-all handler. diff --git a/docs/api/re/melange/Stdlib-Gc-Memprof.md b/docs/api/re/melange/Stdlib-Gc-Memprof.md deleted file mode 100644 index 4258d4511..000000000 --- a/docs/api/re/melange/Stdlib-Gc-Memprof.md +++ /dev/null @@ -1,113 +0,0 @@ - -# Module `Gc.Memprof` - -`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. - -Since blocks are composed of several words, a block can potentially be sampled several times. If a block is sampled several times, then each of the callbacks is called once for each event of this block: the multiplicity is given in the `n_samples` field of the `allocation` structure. - -This engine makes it possible to implement a low-overhead memory profiler as an OCaml library. - -Note: this API is EXPERIMENTAL. It may change without prior notice. - -``` -type t -``` -the type of a profile - -``` -type allocation_source = -``` -``` -| Normal -``` -``` -| Marshal -``` -``` -| Custom -``` -``` - -``` -``` -type allocation = private { -``` -`n_samples : int;` -The number of samples in this block (\>= 1\). - -`size : int;` -The size of the block, in words, excluding the header. - -`source : allocation_source;` -The cause of the allocation. - -`callstack : Printexc.raw_backtrace;` -The callstack for the allocation. - -``` -} -``` -The type of metadata associated with allocations. This is the type of records passed to the callback triggered by the sampling of an allocation. - -``` -type ('minor, 'major) tracker = { -``` -`alloc_minor : allocation -> 'minor option;` -`alloc_major : allocation -> 'major option;` -`promote : 'minor -> 'major option;` -`dealloc_minor : 'minor -> unit;` -`dealloc_major : 'major -> unit;` -``` -} -``` -A `('minor, 'major) tracker` describes how memprof should track sampled blocks over their lifetime, keeping a user-defined piece of metadata for each of them: `'minor` is the type of metadata to keep for minor blocks, and `'major` the type of metadata for major blocks. - -The member functions in a `tracker` are called callbacks. - -If an allocation or promotion callback raises an exception or returns `None`, memprof stops tracking the corresponding block. - -``` -val null_tracker : ('minor, 'major) tracker -``` -Default callbacks simply return `None` or `()` - -``` -val start : - sampling_rate:float -> - ?callstack_size:int -> - ('minor, 'major) tracker -> - t -``` -Start a profile with the given parameters. Raises an exception if a profile is already sampling in the current domain. - -Sampling begins immediately. The parameter `sampling_rate` is the sampling rate in samples per word (including headers). Usually, with cheap callbacks, a rate of 1e-4 has no visible effect on performance, and 1e-3 causes the program to run a few percent slower. 0.0 \<= sampling\_rate \<= 1\.0. - -The parameter `callstack_size` is the length of the callstack recorded at every sample. Its default is `max_int`. - -The parameter `tracker` determines how to track sampled blocks over their lifetime in the minor and major heap. - -Sampling and running callbacks are temporarily disabled on the current thread when calling a callback, so callbacks do not need to be re-entrant if the program is single-threaded and single-domain. However, if threads or multiple domains are used, it is possible that several callbacks will run in parallel. In this case, callback functions must be re-entrant. - -Note that a callback may be postponed slightly after the actual event. The callstack passed to an allocation callback always accurately reflects the allocation, but the program state may have evolved between the allocation and the call to the callback. - -If a new thread or domain is created when the current domain is sampling for a profile, the child thread or domain joins that profile (using the same `sampling_rate`, `callstack_size`, and `tracker` callbacks). - -An allocation callback is always run by the thread which allocated the block. If the thread exits or the profile is stopped before the callback is called, the allocation callback is not called and the block is not tracked. - -Each subsequent callback is generally run by the domain which allocated the block. If the domain terminates or the profile is stopped before the callback is called, the callback may be run by a different domain. - -Different domains may sample for different profiles simultaneously. - -``` -val stop : unit -> unit -``` -Stop sampling for the current profile. Fails if no profile is sampling in the current domain. Stops sampling in all threads and domains sharing the profile. - -Promotion and deallocation callbacks from a profile may run after `stop` is called, until `discard` is applied to the profile. - -A profile is implicitly stopped (but not discarded) if all domains and threads sampling for it are terminated. - -``` -val discard : t -> unit -``` -Discards all profiling state for a stopped profile, which prevents any more callbacks for it. Raises an exception if called on a profile which has not been stopped. diff --git a/docs/api/re/melange/Stdlib-Gc.md b/docs/api/re/melange/Stdlib-Gc.md deleted file mode 100644 index 37e04a556..000000000 --- a/docs/api/re/melange/Stdlib-Gc.md +++ /dev/null @@ -1,295 +0,0 @@ - -# Module `Stdlib.Gc` - -Memory management control and statistics; finalised values. - -``` -type stat = { -``` -`minor_words : float;` -Number of words allocated in the minor heap since the program was started. - -`promoted_words : float;` -Number of words allocated in the minor heap that survived a minor collection and were moved to the major heap since the program was started. - -`major_words : float;` -Number of words allocated in the major heap, including the promoted words, since the program was started. - -`minor_collections : int;` -Number of minor collections since the program was started. - -`major_collections : int;` -Number of major collection cycles completed since the program was started. - -`heap_words : int;` -Total size of the major heap, in words. - -`heap_chunks : int;` -Number of contiguous pieces of memory that make up the major heap. This metric is currently not available in OCaml 5: the field value is always `0`. - -`live_words : int;` -Number of words of live data in the major heap, including the header words. - -Note that "live" words refers to every word in the major heap that isn't currently known to be collectable, which includes words that have become unreachable by the program after the start of the previous gc cycle. It is typically much simpler and more predictable to call [`Gc.full_major`](./#val-full_major) (or [`Gc.compact`](./#val-compact)) then computing gc stats, as then "live" words has the simple meaning of "reachable by the program". One caveat is that a single call to [`Gc.full_major`](./#val-full_major) will not reclaim values that have a finaliser from [`Gc.finalise`](./#val-finalise) (this does not apply to [`Gc.finalise_last`](./#val-finalise_last)). If this caveat matters, simply call [`Gc.full_major`](./#val-full_major) twice instead of once. - -`live_blocks : int;` -Number of live blocks in the major heap. - -See `live_words` for a caveat about what "live" means. - -`free_words : int;` -Number of words in the free list. - -`free_blocks : int;` -Number of blocks in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. - -`largest_free : int;` -Size (in words) of the largest block in the free list. This metric is currently not available in OCaml 5: the field value is always `0`. - -`fragments : int;` -Number of wasted words due to fragmentation. These are 1-words free blocks placed between two live blocks. They are not available for allocation. - -`compactions : int;` -Number of heap compactions since the program was started. - -`top_heap_words : int;` -Maximum size reached by the major heap, in words. - -`stack_size : int;` -Current size of the stack, in words. This metric is currently not available in OCaml 5: the field value is always `0`. - -since 3.12 -`forced_major_collections : int;` -Number of forced full major collections completed since the program was started. - -since 4.12 -``` -} -``` -The memory management counters are returned in a `stat` record. These counters give values for the whole program. - -The total amount of memory allocated by the program since it was started is (in words) `minor_words + major_words - promoted_words`. Multiply by the word size (4 on a 32-bit machine, 8 on a 64-bit machine) to get the number of bytes. - -``` -type control = { -``` -`minor_heap_size : int;` -The size (in words) of the minor heap. Changing this parameter will trigger a minor collection. The total size of the minor heap used by this program is the sum of the heap sizes of the active domains. Default: 256k. - -`major_heap_increment : int;` -How much to add to the major heap when increasing it. If this number is less than or equal to 1000, it is a percentage of the current heap size (i.e. setting it to 100 will double the heap size at each increase). If it is more than 1000, it is a fixed number of words that will be added to the heap. - -This field is currently not available in OCaml 5: the field value is always `0`. - -`space_overhead : int;` -The major GC speed is computed from this parameter. This is the memory that will be "wasted" because the GC does not immediately collect unreachable blocks. It is expressed as a percentage of the memory used for live data. The GC will work more (use more CPU time and collect blocks more eagerly) if `space_overhead` is smaller. Default: 120. - -`verbose : int;` -This value controls the GC messages on standard error output. It is a sum of some of the following flags, to print messages on the corresponding events: - -- `0x001` Start and end of major GC cycle. -- `0x002` Minor collection and major GC slice. -- `0x004` Growing and shrinking of the heap. -- `0x008` Resizing of stacks and memory manager tables. -- `0x010` Heap compaction. -- `0x020` Change of GC parameters. -- `0x040` Computation of major GC slice size. -- `0x080` Calling of finalisation functions. -- `0x100` Bytecode executable and shared library search at start-up. -- `0x200` Computation of compaction-triggering condition. -- `0x400` Output GC statistics at program exit. Default: 0. -`max_overhead : int;` -Heap compaction is triggered when the estimated amount of "wasted" memory is more than `max_overhead` percent of the amount of live data. If `max_overhead` is set to 0, heap compaction is triggered at the end of each major GC cycle (this setting is intended for testing purposes only). If `max_overhead >= 1000000`, compaction is never triggered. - -This field is currently not available in OCaml 5: the field value is always `0`. - -`stack_limit : int;` -The maximum size of the fiber stacks (in words). Default: 128M. - -`allocation_policy : int;` -The policy used for allocating in the major heap. - -This field is currently not available in OCaml 5: the field value is always `0`. - -Prior to OCaml 5.0, possible values were 0, 1 and 2. - -- 0 was the next-fit policy -- 1 was the first-fit policy (since OCaml 3.11) -- 2 was the best-fit policy (since OCaml 4.10) -since 3.11 -`window_size : int;` -The size of the window used by the major GC for smoothing out variations in its workload. This is an integer between 1 and 50. - -since 4.03 -This field is currently not available in OCaml 5: the field value is always `0`. - -`custom_major_ratio : int;` -Target ratio of floating garbage to major heap size for out-of-heap memory held by custom values located in the major heap. The GC speed is adjusted to try to use this much memory for dead values that are not yet collected. Expressed as a percentage of major heap size. The default value keeps the out-of-heap floating garbage about the same size as the in-heap overhead. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 44. - -since 4.08 -`custom_minor_ratio : int;` -Bound on floating garbage for out-of-heap memory held by custom values in the minor heap. A minor GC is triggered when this much memory is held by custom values located in the minor heap. Expressed as a percentage of minor heap size. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 100. - -since 4.08 -`custom_minor_max_size : int;` -Maximum amount of out-of-heap memory for each custom value allocated in the minor heap. Custom values that hold more than this many bytes are allocated on the major heap. Note: this only applies to values allocated with `caml_alloc_custom_mem` (e.g. bigarrays). Default: 70000 bytes. - -since 4.08 -``` -} -``` -The GC parameters are given as a `control` record. Note that these parameters can also be initialised by setting the OCAMLRUNPARAM environment variable. See the documentation of `ocamlrun`. - -``` -val stat : unit -> stat -``` -Return the current values of the memory management counters in a `stat` record that represents the program's total memory stats. The `heap_chunks`, `free_blocks`, `largest_free`, and `stack_size` metrics are currently not available in OCaml 5: their returned field values are therefore `0`. This function causes a full major collection. - -``` -val quick_stat : unit -> stat -``` -Returns a record with the current values of the memory management counters like `stat`. Unlike `stat`, `quick_stat` does not perform a full major collection, and hence, is much faster. However, `quick_stat` reports the counters sampled at the last minor collection or at the end of the last major collection cycle (whichever is the latest). Hence, the memory stats returned by `quick_stat` are not instantaneously accurate. - -``` -val counters : unit -> float * float * float -``` -Return `(minor_words, promoted_words, major_words)` for the current domain or potentially previous domains. This function is as fast as `quick_stat`. - -``` -val minor_words : unit -> float -``` -Number of words allocated in the minor heap by this domain or potentially previous domains. This number is accurate in byte-code programs, but only an approximation in programs compiled to native code. - -In native code this function does not allocate. - -since 4.04 -``` -val get : unit -> control -``` -Return the current values of the GC parameters in a `control` record. - -The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: their returned field values are therefore `0`. - -alert unsynchronized\_access GC parameters are a mutable global state. -``` -val set : control -> unit -``` -`set r` changes the GC parameters according to the `control` record `r`. The normal usage is: `Gc.set { (Gc.get()) with Gc.verbose = 0x00d }` - -The `major_heap_increment`, `max_overhead`, `allocation_policy`, and `window_size` fields are currently not available in OCaml 5: setting them therefore has no effect. - -alert unsynchronized\_access GC parameters are a mutable global state. -``` -val minor : unit -> unit -``` -Trigger a minor collection. - -``` -val major_slice : int -> int -``` -`major_slice n` Do a minor collection and a slice of major collection. `n` is the size of the slice: the GC will do enough work to free (on average) `n` words of memory. If `n` \= 0, the GC will try to do enough work to ensure that the next automatic slice has no work to do. This function returns an unspecified integer (currently: 0). - -``` -val major : unit -> unit -``` -Do a minor collection and finish the current major collection cycle. - -``` -val full_major : unit -> unit -``` -Do a minor collection, finish the current major collection cycle, and perform a complete new cycle. This will collect all currently unreachable blocks. - -``` -val compact : unit -> unit -``` -Perform a full major collection and compact the heap. Note that heap compaction is a lengthy operation. - -``` -val print_stat : out_channel -> unit -``` -Print the current values of the memory management counters (in human-readable form) of the total program into the channel argument. - -``` -val allocated_bytes : unit -> float -``` -Return the number of bytes allocated by this domain and potentially a previous domain. It is returned as a `float` to avoid overflow problems with `int` on 32-bit machines. - -``` -val get_minor_free : unit -> int -``` -Return the current size of the free space inside the minor heap of this domain. - -since 4.03 -``` -val finalise : ('a -> unit) -> 'a -> unit -``` -`finalise f v` registers `f` as a finalisation function for `v`. `v` must be heap-allocated. `f` will be called with `v` as argument at some point between the first time `v` becomes unreachable (including through weak pointers) and the time `v` is collected by the GC. Several functions can be registered for the same value, or even several instances of the same function. Each instance will be called once (or never, if the program terminates before `v` becomes unreachable). - -The GC will call the finalisation functions in the order of deallocation. When several values become unreachable at the same time (i.e. during the same GC cycle), the finalisation functions will be called in the reverse order of the corresponding calls to `finalise`. If `finalise` is called in the same order as the values are allocated, that means each value is finalised before the values it depends upon. Of course, this becomes false if additional dependencies are introduced by assignments. - -In the presence of multiple OCaml threads it should be assumed that any particular finaliser may be executed in any of the threads. - -Anything reachable from the closure of finalisation functions is considered reachable, so the following code will not work as expected: - -- ` let v = ... in Gc.finalise (fun _ -> ...v...) v ` -Instead you should make sure that `v` is not in the closure of the finalisation function by writing: - -- ` let f = fun x -> ... let v = ... in Gc.finalise f v ` -The `f` function can use all features of OCaml, including assignments that make the value reachable again. It can also loop forever (in this case, the other finalisation functions will not be called during the execution of f, unless it calls `finalise_release`). It can call `finalise` on `v` or other values to register other functions or even itself. It can raise an exception; in this case the exception will interrupt whatever the program was doing when the function was called. - -`finalise` will raise `Invalid_argument` if `v` is not guaranteed to be heap-allocated. Some examples of values that are not heap-allocated are integers, constant constructors, booleans, the empty array, the empty list, the unit value. The exact list of what is heap-allocated or not is implementation-dependent. Some constant values can be heap-allocated but never deallocated during the lifetime of the program, for example a list of integer constants; this is also implementation-dependent. Note that values of types `float` are sometimes allocated and sometimes not, so finalising them is unsafe, and `finalise` will also raise `Invalid_argument` for them. Values of type `'a Lazy.t` (for any `'a`) are like `float` in this respect, except that the compiler sometimes optimizes them in a way that prevents `finalise` from detecting them. In this case, it will not raise `Invalid_argument`, but you should still avoid calling `finalise` on lazy values. - -The results of calling [`String.make`](./Stdlib-String.md#val-make), [`Bytes.make`](./Stdlib-Bytes.md#val-make), [`Bytes.create`](./Stdlib-Bytes.md#val-create), [`Array.make`](./Stdlib-Array.md#val-make), and [`Stdlib.ref`](./Stdlib.md#val-ref) are guaranteed to be heap-allocated and non-constant except when the length argument is `0`. - -``` -val finalise_last : (unit -> unit) -> 'a -> unit -``` -same as [`finalise`](./#val-finalise) except the value is not given as argument. So you can't use the given value for the computation of the finalisation function. The benefit is that the function is called after the value is unreachable for the last time instead of the first time. So contrary to [`finalise`](./#val-finalise) the value will never be reachable again or used again. In particular every weak pointer and ephemeron that contained this value as key or data is unset before running the finalisation function. Moreover the finalisation functions attached with [`finalise`](./#val-finalise) are always called before the finalisation functions attached with [`finalise_last`](./#val-finalise_last). - -since 4.04 -``` -val finalise_release : unit -> unit -``` -A finalisation function may call `finalise_release` to tell the GC that it can launch the next finalisation function without waiting for the current one to return. - -``` -type alarm -``` -An alarm is a piece of data that calls a user function at the end of major GC cycle. The following functions are provided to create and delete alarms. - -``` -val create_alarm : (unit -> unit) -> alarm -``` -`create_alarm f` will arrange for `f` to be called at the end of major GC cycles, not caused by `f` itself, starting with the current cycle or the next one. `f` will run on the same domain that created the alarm, until the domain exits or `delete_alarm` is called. A value of type `alarm` is returned that you can use to call `delete_alarm`. - -It is not guaranteed that the Gc alarm runs at the end of every major GC cycle, but it is guaranteed that it will run eventually. - -As an example, here is a crude way to interrupt a function if the memory consumption of the program exceeds a given `limit` in MB, suitable for use in the toplevel: - -```ocaml -let run_with_memory_limit (limit : int) (f : unit -> 'a) : 'a = - let limit_memory () = - let mem = Gc.(quick_stat ()).heap_words in - if mem / (1024 * 1024) > limit / (Sys.word_size / 8) then - raise Out_of_memory - in - let alarm = Gc.create_alarm limit_memory in - Fun.protect f ~finally:(fun () -> Gc.delete_alarm alarm ; Gc.compact ()) -``` -``` -val delete_alarm : alarm -> unit -``` -`delete_alarm a` will stop the calls to the function associated to `a`. Calling `delete_alarm a` again has no effect. - -``` -val eventlog_pause : unit -> unit -``` -deprecated Use Runtime\_events.pause instead. -``` -val eventlog_resume : unit -> unit -``` -deprecated Use Runtime\_events.resume instead. -``` -module Memprof : sig ... end -``` -`Memprof` is a profiling engine which randomly samples allocated memory words. Every allocated word has a probability of being sampled equal to a configurable sampling rate. Once a block is sampled, it becomes tracked. A tracked block triggers a user-defined callback as soon as it is allocated, promoted or deallocated. diff --git a/docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md b/docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md deleted file mode 100644 index 80efdc53c..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-Make-argument-1-H.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Parameter `Make.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-Make.md b/docs/api/re/melange/Stdlib-Hashtbl-Make.md deleted file mode 100644 index ec79c26fe..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-Make.md +++ /dev/null @@ -1,96 +0,0 @@ - -# Module `Hashtbl.Make` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - - -## Parameters - -``` -module H : HashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type !'a t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md deleted file mode 100644 index 66eb409ed..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded-argument-1-H.md +++ /dev/null @@ -1,17 +0,0 @@ - -# Parameter `MakeSeeded.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md b/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md deleted file mode 100644 index 23f14bd52..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-MakeSeeded.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Hashtbl.MakeSeeded` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-Hashtbl.md#val-randomize)). - -since 4.00 - -## Parameters - -``` -module H : SeededHashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type !'a t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md deleted file mode 100644 index 6c2dc6de5..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-module-type-HashedType.md +++ /dev/null @@ -1,23 +0,0 @@ - -# Module type `Hashtbl.HashedType` - -The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md deleted file mode 100644 index c4d7f8b23..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-module-type-S.md +++ /dev/null @@ -1,87 +0,0 @@ - -# Module type `Hashtbl.S` - -The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -type key -``` -``` -type !'a t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md deleted file mode 100644 index 63efb5650..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededHashedType.md +++ /dev/null @@ -1,20 +0,0 @@ - -# Module type `Hashtbl.SeededHashedType` - -The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md b/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md deleted file mode 100644 index da23d5c25..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl-module-type-SeededS.md +++ /dev/null @@ -1,86 +0,0 @@ - -# Module type `Hashtbl.SeededS` - -The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type key -``` -``` -type !'a t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key -> 'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key -> 'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : (key -> 'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Hashtbl.md b/docs/api/re/melange/Stdlib-Hashtbl.md deleted file mode 100644 index cd0022e7f..000000000 --- a/docs/api/re/melange/Stdlib-Hashtbl.md +++ /dev/null @@ -1,388 +0,0 @@ - -# Module `Stdlib.Hashtbl` - -Hash tables and hash functions. - -Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-Map.md). - -The functors [`Make`](./Stdlib-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. - -**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. - -The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. - -See [the examples section](./#examples). - -**Unsynchronized accesses** - -Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -## Generic interface - -``` -type (!'a, !'b) t -``` -The type of hash tables from type `'a` to type `'b`. - -``` -val create : ?random:bool -> int -> ('a, 'b) t -``` -`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. - -A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. - -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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. - -before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. -``` -val clear : ('a, 'b) t -> unit -``` -Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. - -``` -val reset : ('a, 'b) t -> unit -``` -Empty a hash table and shrink the size of the bucket table to its initial size. - -since 4.00 -``` -val copy : ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. - -``` -val add : ('a, 'b) t -> 'a -> 'b -> unit -``` -`Hashtbl.add tbl key data` adds a binding of `key` to `data` in table `tbl`. - -**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) - -If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). - -``` -val find : ('a, 'b) t -> 'a -> 'b -``` -`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. - -``` -val find_opt : ('a, 'b) t -> 'a -> 'b option -``` -`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. - -since 4.05 -``` -val find_all : ('a, 'b) t -> 'a -> 'b list -``` -`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. - -``` -val mem : ('a, 'b) t -> 'a -> bool -``` -`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. - -``` -val remove : ('a, 'b) t -> 'a -> unit -``` -`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. - -``` -val replace : ('a, 'b) t -> 'a -> 'b -> unit -``` -`Hashtbl.replace tbl key data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. - -``` -val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit -``` -`Hashtbl.iter f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit -``` -`Hashtbl.filter_map_inplace f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. - -Other comments for [`iter`](./#val-iter) apply as well. - -since 4.03 -``` -val fold : ('a -> 'b -> 'acc -> 'acc) -> ('a, 'b) t -> 'acc -> 'acc -``` -`Hashtbl.fold f tbl init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val length : ('a, 'b) t -> int -``` -`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. - -``` -val randomize : unit -> unit -``` -After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. - -It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. - -Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. - -since 4.00 -``` -val is_randomized : unit -> bool -``` -Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. - -since 4.03 -``` -val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. - -[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. - -since 4.12 -``` -type statistics = { -``` -`num_bindings : int;` -Number of bindings present in the table. Same value as returned by [`length`](./#val-length). - -`num_buckets : int;` -Number of buckets in the table. - -`max_bucket_length : int;` -Maximal number of bindings per bucket. - -`bucket_histogram : int array;` -Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. - -``` -} -``` -since 4.00 -``` -val stats : ('a, 'b) t -> statistics -``` -`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. - -since 4.00 - -## Hash tables and Sequences - -``` -val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t -``` -Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. - -The behavior is not specified if the hash table is modified during the iteration. - -since 4.07 -``` -val to_seq_keys : ('a, _) t -> 'a Seq.t -``` -Same as `Seq.map fst (to_seq m)` - -since 4.07 -``` -val to_seq_values : (_, 'b) t -> 'b Seq.t -``` -Same as `Seq.map snd (to_seq m)` - -since 4.07 -``` -val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`add`](./#val-add) - -since 4.07 -``` -val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`replace`](./#val-replace) - -since 4.07 -``` -val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t -``` -Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. - -since 4.07 - -## Functorial interface - -The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. - -For instance, one might want to specialize a table for integer keys: - -```ocaml - module IntHash = - struct - type t = int - let equal i j = i=j - let hash i = i land max_int - end - - module IntHashtbl = Hashtbl.Make(IntHash) - - let h = IntHashtbl.create 17 in - IntHashtbl.add h 12 "hello" -``` -This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. - -Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. - -``` -module type HashedType = sig ... end -``` -The input signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -module type S = sig ... end -``` -The output signature of the functor [`Make`](./Stdlib-Hashtbl-Make.md). - -``` -module Make (H : HashedType) : S with type key = H.t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - -``` -module type SeededHashedType = sig ... end -``` -The input signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -``` -module type SeededS = sig ... end -``` -The output signature of the functor [`MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -``` -module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). - - -## The polymorphic hash functions - -``` -val hash : 'a -> int -``` -`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. - -``` -val seeded_hash : int -> 'a -> int -``` -A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. - -since 4.00 -``` -val hash_param : int -> int -> 'a -> int -``` -`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. - -``` -val seeded_hash_param : int -> int -> int -> 'a -> int -``` -A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. - -since 4.00 - -## 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 - 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 -``` - -### Counting Elements - -Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. - -Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. - -```ocaml - # module Char_tbl = Hashtbl.Make(struct - type t = char - let equal = Char.equal - let hash = Hashtbl.hash - end) - - (* count distinct occurrences of chars in [seq] *) - # let count_chars (seq : char Seq.t) : _ list = - let counts = Char_tbl.create 16 in - Seq.iter - (fun c -> - let count_c = - Char_tbl.find_opt counts c - |> Option.value ~default:0 - in - Char_tbl.replace counts c (count_c + 1)) - seq; - (* turn into a list *) - Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] - |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) - val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = - - (* basic seq from a string *) - # let seq = String.to_seq "hello world, and all the camels in it!" - val seq : char Seq.t = - - # count_chars seq - - : (Char.t * int) list = - [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); - ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); - ('s', 1); ('t', 2); ('w', 1)] - - (* "abcabcabc..." *) - # let seq2 = - Seq.cycle (String.to_seq "abc") |> Seq.take 31 - val seq2 : char Seq.t = - - # String.of_seq seq2 - - : String.t = "abcabcabcabcabcabcabcabcabcabca" - - # count_chars seq2 - - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] - -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-In_channel.md b/docs/api/re/melange/Stdlib-In_channel.md deleted file mode 100644 index 7f2f9497e..000000000 --- a/docs/api/re/melange/Stdlib-In_channel.md +++ /dev/null @@ -1,238 +0,0 @@ - -# Module `Stdlib.In_channel` - -Input channels. - -This module provides functions for working with input channels. - -See [the example section](./#examples) below. - -since 4.14 - -## Channels - -``` -type t = in_channel -``` -The type of input channel. - -``` -type open_flag = open_flag = -``` -``` -| Open_rdonly -``` -open for reading. - -``` -| Open_wronly -``` -open for writing. - -``` -| Open_append -``` -open for appending: always write at end of file. - -``` -| Open_creat -``` -create the file if it does not exist. - -``` -| Open_trunc -``` -empty the file if it already exists. - -``` -| Open_excl -``` -fail if Open\_creat and the file already exists. - -``` -| Open_binary -``` -open in binary mode (no conversion). - -``` -| Open_text -``` -open in text mode (may perform conversions). - -``` -| Open_nonblock -``` -open in non-blocking mode. - -``` - -``` -Opening modes for [`open_gen`](./#val-open_gen). - -``` -val stdin : t -``` -The standard input for the process. - -``` -val open_bin : string -> t -``` -Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. - -``` -val open_text : string -> t -``` -Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). - -``` -val open_gen : open_flag list -> int -> string -> t -``` -`open_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. - -``` -val with_open_bin : string -> (t -> 'a) -> 'a -``` -`with_open_bin fn f` opens a channel `ic` on file `fn` and returns `f ic`. After `f` returns, either with a value or by raising an exception, `ic` is guaranteed to be closed. - -``` -val with_open_text : string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). - -``` -val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). - -``` -val close : t -> unit -``` -Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except [`close`](./#val-close), which does nothing when applied to an already closed channel. - -``` -val close_noerr : t -> unit -``` -Same as [`close`](./#val-close), but ignore all errors. - - -## Input - -``` -val input_char : t -> char option -``` -Read one character from the given input channel. Returns `None` if there are no more characters to read. - -``` -val input_byte : t -> int option -``` -Same as [`input_char`](./#val-input_char), but return the 8-bit integer representing the character. Returns `None` if the end of file was reached. - -``` -val input_line : t -> string option -``` -`input_line ic` reads characters from `ic` until a newline or the end of file is reached. Returns the string of all characters read, without the newline (if any). Returns `None` if the end of the file has been reached. In particular, this will be the case if the last line of input is empty. - -A newline is the character `\n` unless the file is open in text mode and [`Sys.win32`](./Stdlib-Sys.md#val-win32) is `true` in which case it is the sequence of characters `\r\n`. - -``` -val really_input_string : t -> int -> string option -``` -`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. Returns `None` if the end of file is reached before `len` characters have been read. - -If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. - -``` -val input_all : t -> string -``` -`input_all ic` reads all remaining data from `ic`. - -If the same channel is read concurrently by multiple threads, the returned string is not guaranteed to contain contiguous characters from the input. - -``` -val input_lines : t -> string list -``` -`input_lines ic` reads lines using [`input_line`](./#val-input_line) until the end of file is reached. It returns the list of all lines read, in the order they were read. The newline characters that terminate lines are not included in the returned strings. Empty lines produce empty strings. - -since 5.1 - -## Advanced input - -``` -val input : t -> bytes -> int -> int -> int -``` -`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. - -Use [`really_input`](./#val-really_input) to read exactly `len` characters. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val really_input : t -> bytes -> int -> int -> unit option -``` -`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. - -Returns `None` if the end of file is reached before `len` characters have been read. - -If the same channel is read concurrently by multiple threads, the bytes read by `really_input` are not guaranteed to be contiguous. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val fold_lines : ('acc -> string -> 'acc) -> 'acc -> t -> 'acc -``` -`fold_lines f init ic` reads lines from `ic` using [`input_line`](./#val-input_line) until the end of file is reached, and successively passes each line to function `f` in the style of a fold. More precisely, if lines `l1, ..., lN` are read, `fold_lines f init ic` computes `f (... (f (f init l1) l2) ...) lN`. If `f` has no side effects, this is equivalent to `List.fold_left f init (In_channel.input_lines ic)`, but is more efficient since it does not construct the list of all lines read. - -since 5.1 - -## Seeking - -``` -val seek : t -> int64 -> unit -``` -`seek chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. - -``` -val pos : t -> int64 -``` -Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - - -## Attributes - -``` -val length : t -> int64 -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. - -``` -val set_binary_mode : t -> bool -> unit -``` -`set_binary_mode ic true` sets the channel `ic` to binary mode: no translations take place during input. - -`set_binary_mode ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. - -This function has no effect under operating systems that do not distinguish between text mode and binary mode. - -``` -val is_binary_mode : t -> bool -``` -`is_binary_mode ic` returns whether the channel `ic` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). - -since 5.2 -``` -val isatty : t -> bool -``` -`isatty ic` is `true` if `ic` refers to a terminal or console window, `false` otherwise. - -since 5.1 - -## Examples - -Reading the contents of a file: - -```ocaml - let read_file file = In_channel.with_open_bin file In_channel.input_all -``` -Reading a line from stdin: - -```ocaml - let user_input () = In_channel.input_line In_channel.stdin -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Int.md b/docs/api/re/melange/Stdlib-Int.md deleted file mode 100644 index cf5344cce..000000000 --- a/docs/api/re/melange/Stdlib-Int.md +++ /dev/null @@ -1,176 +0,0 @@ - -# Module `Stdlib.Int` - -Integer values. - -Integers are [`Sys.int_size`](./Stdlib-Sys.md#val-int_size) bits wide and use two's complement representation. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. - -since 4.08 - -## Integers - -``` -type t = int -``` -The type for integer values. - -``` -val zero : int -``` -`zero` is the integer `0`. - -``` -val one : int -``` -`one` is the integer `1`. - -``` -val minus_one : int -``` -`minus_one` is the integer `-1`. - -``` -val neg : int -> int -``` -`neg x` is `~-x`. - -``` -val add : int -> int -> int -``` -`add x y` is the addition `x + y`. - -``` -val sub : int -> int -> int -``` -`sub x y` is the subtraction `x - y`. - -``` -val mul : int -> int -> int -``` -`mul x y` is the multiplication `x * y`. - -``` -val div : int -> int -> int -``` -`div x y` is the division `x / y`. See [`Stdlib.(/)`](./Stdlib.md#val-\(/\)) for details. - -``` -val rem : int -> int -> int -``` -`rem x y` is the remainder `x mod y`. See [`Stdlib.(mod)`](./Stdlib.md#val-\(mod\)) for details. - -``` -val succ : int -> int -``` -`succ x` is `add x 1`. - -``` -val pred : int -> int -``` -`pred x` is `sub x 1`. - -``` -val abs : int -> int -``` -`abs x` is the absolute value of `x`. That is `x` if `x` is positive and `neg x` if `x` is negative. **Warning.** This may be negative if the argument is [`min_int`](./#val-min_int). - -``` -val max_int : int -``` -`max_int` is the greatest representable integer, `2``Sys.int_size - 1``-1`. - -``` -val min_int : int -``` -`min_int` is the smallest representable integer, `-2``Sys.int_size - 1`. - -``` -val logand : int -> int -> int -``` -`logand x y` is the bitwise logical and of `x` and `y`. - -``` -val logor : int -> int -> int -``` -`logor x y` is the bitwise logical or of `x` and `y`. - -``` -val logxor : int -> int -> int -``` -`logxor x y` is the bitwise logical exclusive or of `x` and `y`. - -``` -val lognot : int -> int -``` -`lognot x` is the bitwise logical negation of `x`. - -``` -val shift_left : int -> int -> int -``` -`shift_left x n` shifts `x` to the left by `n` bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). - -``` -val shift_right : int -> int -> int -``` -`shift_right x n` shifts `x` to the right by `n` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). - -``` -val shift_right_logical : int -> int -> int -``` -`shift_right x n` shifts `x` to the right by `n` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `n < 0` or `n > `[`Sys.int_size`](./Stdlib-Sys.md#val-int_size). - - -## Predicates and comparisons - -``` -val equal : int -> int -> bool -``` -`equal x y` is `true` if and only if `x = y`. - -``` -val compare : int -> int -> int -``` -`compare x y` is [`Stdlib.compare`](./Stdlib.md#val-compare)` x y` but more efficient. - -``` -val min : int -> int -> int -``` -Return the smaller of the two arguments. - -since 4.13 -``` -val max : int -> int -> int -``` -Return the greater of the two arguments. - -since 4.13 - -## Converting - -``` -val to_float : int -> float -``` -`to_float x` is `x` as a floating point number. - -``` -val of_float : float -> int -``` -`of_float x` truncates `x` to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. - -``` -val to_string : int -> string -``` -`to_string x` is the written representation of `x` in decimal. - -``` -val seeded_hash : int -> int -> int -``` -A seeded hash function for ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : int -> int -``` -An unseeded hash function for ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Int32.md b/docs/api/re/melange/Stdlib-Int32.md deleted file mode 100644 index 0f3011b3a..000000000 --- a/docs/api/re/melange/Stdlib-Int32.md +++ /dev/null @@ -1,237 +0,0 @@ - -# Module `Stdlib.Int32` - -32-bit integers. - -This module provides operations on the type `int32` of signed 32-bit integers. Unlike the built-in `int` type, the type `int32` is guaranteed to be exactly 32-bit wide on all platforms. All arithmetic operations over `int32` are taken modulo 232. - -Performance notice: values of type `int32` occupy more memory space than values of type `int`, and arithmetic operations on `int32` are generally slower than those on `int`. Use `int32` only when the application requires exact 32-bit arithmetic. - -Literals for 32-bit integers are suffixed by l: - -```ocaml - let zero: int32 = 0l - let one: int32 = 1l - let m_one: int32 = -1l -``` -``` -val zero : int32 -``` -The 32-bit integer 0. - -``` -val one : int32 -``` -The 32-bit integer 1\. - -``` -val minus_one : int32 -``` -The 32-bit integer \-1. - -``` -val neg : int32 -> int32 -``` -Unary negation. - -``` -val add : int32 -> int32 -> int32 -``` -Addition. - -``` -val sub : int32 -> int32 -> int32 -``` -Subtraction. - -``` -val mul : int32 -> int32 -> int32 -``` -Multiplication. - -``` -val div : int32 -> int32 -> int32 -``` -Integer division. This division rounds the real quotient of its arguments towards zero, as specified for [`Stdlib.(/)`](./Stdlib.md#val-\(/\)). - -raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. -``` -val unsigned_div : int32 -> int32 -> int32 -``` -Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 32-bit integers. - -since 4.08 -``` -val rem : int32 -> int32 -> int32 -``` -Integer remainder. If `y` is not zero, the result of `Int32.rem x y` satisfies the following property: `x = Int32.add (Int32.mul (Int32.div x y) y) (Int32.rem x y)`. If `y = 0`, `Int32.rem x y` raises `Division_by_zero`. - -``` -val unsigned_rem : int32 -> int32 -> int32 -``` -Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 32-bit integers. - -since 4.08 -``` -val succ : int32 -> int32 -``` -Successor. `Int32.succ x` is `Int32.add x Int32.one`. - -``` -val pred : int32 -> int32 -``` -Predecessor. `Int32.pred x` is `Int32.sub x Int32.one`. - -``` -val abs : int32 -> int32 -``` -`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. - -``` -val max_int : int32 -``` -The greatest representable 32-bit integer, 231 \- 1\. - -``` -val min_int : int32 -``` -The smallest representable 32-bit integer, \-231. - -``` -val logand : int32 -> int32 -> int32 -``` -Bitwise logical and. - -``` -val logor : int32 -> int32 -> int32 -``` -Bitwise logical or. - -``` -val logxor : int32 -> int32 -> int32 -``` -Bitwise logical exclusive or. - -``` -val lognot : int32 -> int32 -``` -Bitwise logical negation. - -``` -val shift_left : int32 -> int -> int32 -``` -`Int32.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 32`. - -``` -val shift_right : int32 -> int -> int32 -``` -`Int32.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 32`. - -``` -val shift_right_logical : int32 -> int -> int32 -``` -`Int32.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 32`. - -``` -val of_int : int -> int32 -``` -Convert the given integer (type `int`) to a 32-bit integer (type `int32`). On 64-bit platforms, the argument is taken modulo 232. - -``` -val to_int : int32 -> int -``` -Convert the given 32-bit integer (type `int32`) to an integer (type `int`). On 32-bit platforms, the 32-bit integer is taken modulo 231, i.e. the high-order bit is lost during the conversion. On 64-bit platforms, the conversion is exact. - -``` -val unsigned_to_int : int32 -> int option -``` -Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. - -since 4.08 -``` -val of_float : float -> int32 -``` -Convert the given floating-point number to a 32-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int32.min_int`](./#val-min_int), [`Int32.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. - -``` -val to_float : int32 -> float -``` -Convert the given 32-bit integer to a floating-point number. - -``` -val of_string : string -> int32 -``` -Convert the given string to a 32-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. - -The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int32.max_int+1]`. If the input exceeds [`Int32.max_int`](./#val-max_int) it is converted to the signed integer `Int32.min_int + input - Int32.max_int - 1`. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int32. -``` -val of_string_opt : string -> int32 option -``` -Same as `of_string`, but return `None` instead of raising. - -since 4.05 -``` -val to_string : int32 -> string -``` -Return the string representation of its argument, in signed decimal. - -``` -val bits_of_float : float -> int32 -``` -Return the internal representation of the given float according to the IEEE 754 floating-point 'single format' bit layout. Bit 31 of the result represents the sign of the float; bits 30 to 23 represent the (biased) exponent; bits 22 to 0 represent the mantissa. - -``` -val float_of_bits : int32 -> float -``` -Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'single format' bit layout, is the given `int32`. - -``` -type t = int32 -``` -An alias for the type of 32-bit integers. - -``` -val compare : t -> t -> int -``` -The comparison function for 32-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int32` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val unsigned_compare : t -> t -> int -``` -Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 32-bit integers. - -since 4.08 -``` -val equal : t -> t -> bool -``` -The equal function for int32s. - -since 4.03 -``` -val min : t -> t -> t -``` -Return the smaller of the two arguments. - -since 4.13 -``` -val max : t -> t -> t -``` -Return the greater of the two arguments. - -since 4.13 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for 32-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for 32-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Int64.md b/docs/api/re/melange/Stdlib-Int64.md deleted file mode 100644 index f7d334e83..000000000 --- a/docs/api/re/melange/Stdlib-Int64.md +++ /dev/null @@ -1,257 +0,0 @@ - -# Module `Stdlib.Int64` - -64-bit integers. - -This module provides operations on the type `int64` of signed 64-bit integers. Unlike the built-in `int` type, the type `int64` is guaranteed to be exactly 64-bit wide on all platforms. All arithmetic operations over `int64` are taken modulo 264 - -Performance notice: values of type `int64` occupy more memory space than values of type `int`, and arithmetic operations on `int64` are generally slower than those on `int`. Use `int64` only when the application requires exact 64-bit arithmetic. - -Literals for 64-bit integers are suffixed by L: - -```ocaml - let zero: int64 = 0L - let one: int64 = 1L - let m_one: int64 = -1L -``` -``` -val zero : int64 -``` -The 64-bit integer 0. - -``` -val one : int64 -``` -The 64-bit integer 1\. - -``` -val minus_one : int64 -``` -The 64-bit integer \-1. - -``` -val neg : int64 -> int64 -``` -Unary negation. - -``` -val add : int64 -> int64 -> int64 -``` -Addition. - -``` -val sub : int64 -> int64 -> int64 -``` -Subtraction. - -``` -val mul : int64 -> int64 -> int64 -``` -Multiplication. - -``` -val div : int64 -> int64 -> int64 -``` -Integer division. - -raises [`Division_by_zero`](./Stdlib.md#exception-Division_by_zero) if the second argument is zero. This division rounds the real quotient of its arguments towards zero, as specified for Stdlib.(/). -``` -val unsigned_div : int64 -> int64 -> int64 -``` -Same as [`div`](./#val-div), except that arguments and result are interpreted as *unsigned* 64-bit integers. - -since 4.08 -``` -val rem : int64 -> int64 -> int64 -``` -Integer remainder. If `y` is not zero, the result of `Int64.rem x y` satisfies the following property: `x = Int64.add (Int64.mul (Int64.div x y) y) (Int64.rem x y)`. If `y = 0`, `Int64.rem x y` raises `Division_by_zero`. - -``` -val unsigned_rem : int64 -> int64 -> int64 -``` -Same as [`rem`](./#val-rem), except that arguments and result are interpreted as *unsigned* 64-bit integers. - -since 4.08 -``` -val succ : int64 -> int64 -``` -Successor. `Int64.succ x` is `Int64.add x Int64.one`. - -``` -val pred : int64 -> int64 -``` -Predecessor. `Int64.pred x` is `Int64.sub x Int64.one`. - -``` -val abs : int64 -> int64 -``` -`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. - -``` -val max_int : int64 -``` -The greatest representable 64-bit integer, 263 \- 1\. - -``` -val min_int : int64 -``` -The smallest representable 64-bit integer, \-263. - -``` -val logand : int64 -> int64 -> int64 -``` -Bitwise logical and. - -``` -val logor : int64 -> int64 -> int64 -``` -Bitwise logical or. - -``` -val logxor : int64 -> int64 -> int64 -``` -Bitwise logical exclusive or. - -``` -val lognot : int64 -> int64 -``` -Bitwise logical negation. - -``` -val shift_left : int64 -> int -> int64 -``` -`Int64.shift_left x y` shifts `x` to the left by `y` bits. The result is unspecified if `y < 0` or `y >= 64`. - -``` -val shift_right : int64 -> int -> int64 -``` -`Int64.shift_right x y` shifts `x` to the right by `y` bits. This is an arithmetic shift: the sign bit of `x` is replicated and inserted in the vacated bits. The result is unspecified if `y < 0` or `y >= 64`. - -``` -val shift_right_logical : int64 -> int -> int64 -``` -`Int64.shift_right_logical x y` shifts `x` to the right by `y` bits. This is a logical shift: zeroes are inserted in the vacated bits regardless of the sign of `x`. The result is unspecified if `y < 0` or `y >= 64`. - -``` -val of_int : int -> int64 -``` -Convert the given integer (type `int`) to a 64-bit integer (type `int64`). - -``` -val to_int : int64 -> int -``` -Convert the given 64-bit integer (type `int64`) to an integer (type `int`). On 64-bit platforms, the 64-bit integer is taken modulo 263, i.e. the high-order bit is lost during the conversion. On 32-bit platforms, the 64-bit integer is taken modulo 231, i.e. the top 33 bits are lost during the conversion. - -``` -val unsigned_to_int : int64 -> int option -``` -Same as [`to_int`](./#val-to_int), but interprets the argument as an *unsigned* integer. Returns `None` if the unsigned value of the argument cannot fit into an `int`. - -since 4.08 -``` -val of_float : float -> int64 -``` -Convert the given floating-point number to a 64-bit integer, discarding the fractional part (truncate towards 0). If the truncated floating-point number is outside the range \[[`Int64.min_int`](./#val-min_int), [`Int64.max_int`](./#val-max_int)\], no exception is raised, and an unspecified, platform-dependent integer is returned. - -``` -val to_float : int64 -> float -``` -Convert the given 64-bit integer to a floating-point number. - -``` -val of_int32 : int32 -> int64 -``` -Convert the given 32-bit integer (type `int32`) to a 64-bit integer (type `int64`). - -``` -val to_int32 : int64 -> int32 -``` -Convert the given 64-bit integer (type `int64`) to a 32-bit integer (type `int32`). The 64-bit integer is taken modulo 232, i.e. the top 32 bits are lost during the conversion. - -``` -val of_nativeint : nativeint -> int64 -``` -Convert the given native integer (type `nativeint`) to a 64-bit integer (type `int64`). - -``` -val to_nativeint : int64 -> nativeint -``` -Convert the given 64-bit integer (type `int64`) to a native integer. On 32-bit platforms, the 64-bit integer is taken modulo 232. On 64-bit platforms, the conversion is exact. - -``` -val of_string : string -> int64 -``` -Convert the given string to a 64-bit integer. The string is read in decimal (by default, or if the string begins with `0u`) or in hexadecimal, octal or binary if the string begins with `0x`, `0o` or `0b` respectively. - -The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*Int64.max_int+1]`. If the input exceeds [`Int64.max_int`](./#val-max_int) it is converted to the signed integer `Int64.min_int + input - Int64.max_int - 1`. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type int64. -``` -val of_string_opt : string -> int64 option -``` -Same as `of_string`, but return `None` instead of raising. - -since 4.05 -``` -val to_string : int64 -> string -``` -Return the string representation of its argument, in decimal. - -``` -val bits_of_float : float -> int64 -``` -Return the internal representation of the given float according to the IEEE 754 floating-point 'double format' bit layout. Bit 63 of the result represents the sign of the float; bits 62 to 52 represent the (biased) exponent; bits 51 to 0 represent the mantissa. - -``` -val float_of_bits : int64 -> float -``` -Return the floating-point number whose internal representation, according to the IEEE 754 floating-point 'double format' bit layout, is the given `int64`. - -``` -type t = int64 -``` -An alias for the type of 64-bit integers. - -``` -val compare : t -> t -> int -``` -The comparison function for 64-bit integers, with the same specification as [`Stdlib.compare`](./Stdlib.md#val-compare). Along with the type `t`, this function `compare` allows the module `Int64` to be passed as argument to the functors [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md). - -``` -val unsigned_compare : t -> t -> int -``` -Same as [`compare`](./#val-compare), except that arguments are interpreted as *unsigned* 64-bit integers. - -since 4.08 -``` -val equal : t -> t -> bool -``` -The equal function for int64s. - -since 4.03 -``` -val min : t -> t -> t -``` -Return the smaller of the two arguments. - -since 4.13 -``` -val max : t -> t -> t -``` -Return the greater of the two arguments. - -since 4.13 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for 64-bit ints, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.1 -``` -val hash : t -> int -``` -An unseeded hash function for 64-bit ints, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-LargeFile.md b/docs/api/re/melange/Stdlib-LargeFile.md deleted file mode 100644 index b4e663dc2..000000000 --- a/docs/api/re/melange/Stdlib-LargeFile.md +++ /dev/null @@ -1,23 +0,0 @@ - -# Module `Stdlib.LargeFile` - -Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. - -``` -val seek_out : out_channel -> int64 -> unit -``` -``` -val pos_out : out_channel -> int64 -``` -``` -val out_channel_length : out_channel -> int64 -``` -``` -val seek_in : in_channel -> int64 -> unit -``` -``` -val pos_in : in_channel -> int64 -``` -``` -val in_channel_length : in_channel -> int64 -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Lazy.md b/docs/api/re/melange/Stdlib-Lazy.md deleted file mode 100644 index 519b7cec5..000000000 --- a/docs/api/re/melange/Stdlib-Lazy.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Stdlib.Lazy` - -Deferred computations. - -``` -type 'a t = 'a CamlinternalLazy.t -``` -A value of type `'a Lazy.t` is a deferred computation, called a suspension, that has a result of type `'a`. The special expression syntax `lazy (expr)` makes a suspension of the computation of `expr`, without computing `expr` itself yet. "Forcing" the suspension will then compute `expr` and return its result. Matching a suspension with the special pattern syntax `lazy(pattern)` also computes the underlying expression and tries to bind it to `pattern`: - -```ocaml - let lazy_option_map f x = - match x with - | lazy (Some x) -> Some (Lazy.force f x) - | _ -> None -``` -Note: If lazy patterns appear in multiple cases in a pattern-matching, lazy expressions may be forced even outside of the case ultimately selected by the pattern matching. In the example above, the suspension `x` is always computed. - -Note: `lazy_t` is the built-in type constructor used by the compiler for the `lazy` keyword. You should not use it directly. Always use `Lazy.t` instead. - -Note: `Lazy.force` is not concurrency-safe. If you use this module with multiple fibers, systhreads or domains, then you will need to add some locks. The module however ensures memory-safety, and hence, concurrently accessing this module will not lead to a crash but the behaviour is unspecified. - -Note: if the program is compiled with the `-rectypes` option, ill-founded recursive definitions of the form `let rec x = lazy x` or `let rec x = lazy(lazy(...(lazy x)))` are accepted by the type-checker and lead, when forced, to ill-formed values that trigger infinite loops in the garbage collector and other parts of the run-time system. Without the `-rectypes` option, such ill-founded recursive definitions are rejected by the type-checker. - -``` -exception Undefined -``` -Raised when forcing a suspension concurrently from multiple fibers, systhreads or domains, or when the suspension tries to force itself recursively. - -``` -val force : 'a t -> 'a -``` -`force x` forces the suspension `x` and returns its result. If `x` has already been forced, `Lazy.force x` returns the same value again without recomputing it. If it raised an exception, the same exception is raised again. - -raises [`Undefined`](./#exception-Undefined) (see Undefined). - -## Iterators - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f x` returns a suspension that, when forced, forces `x` and applies `f` to its value. - -It is equivalent to `lazy (f (Lazy.force x))`. - -since 4.13 - -## Reasoning on already-forced suspensions - -``` -val is_val : 'a t -> bool -``` -`is_val x` returns `true` if `x` has already been forced and did not raise an exception. - -since 4.00 -``` -val from_val : 'a -> 'a t -``` -`from_val v` evaluates `v` first (as any function would) and returns an already-forced suspension of its result. It is the same as `let x = v in lazy x`, but uses dynamic tests to optimize suspension creation in some cases. - -since 4.00 -``` -val map_val : ('a -> 'b) -> 'a t -> 'b t -``` -`map_val f x` applies `f` directly if `x` is already forced, otherwise it behaves as `map f x`. - -When `x` is already forced, this behavior saves the construction of a suspension, but on the other hand it performs more work eagerly that may not be useful if you never force the function result. - -If `f` raises an exception, it will be raised immediately when `is_val x`, or raised only when forcing the thunk otherwise. - -If `map_val f x` does not raise an exception, then `is_val (map_val f x)` is equal to `is_val x`. - -since 4.13 - -## Advanced - -The following definitions are for advanced uses only; they require familiarity with the lazy compilation scheme to be used appropriately. - -``` -val from_fun : (unit -> 'a) -> 'a t -``` -`from_fun f` is the same as `lazy (f ())` but slightly more efficient. - -It should only be used if the function `f` is already defined. In particular it is always less efficient to write `from_fun (fun () -> expr)` than `lazy expr`. - -since 4.00 -``` -val force_val : 'a t -> 'a -``` -`force_val x` forces the suspension `x` and returns its result. If `x` has already been forced, `force_val x` returns the same value again without recomputing it. - -If the computation of `x` raises an exception, it is unspecified whether `force_val x` raises the same exception or [`Undefined`](./#exception-Undefined). - -raises [`Undefined`](./#exception-Undefined) if the forcing of x tries to force x itself recursively. -raises [`Undefined`](./#exception-Undefined) (see Undefined). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Lexing.md b/docs/api/re/melange/Stdlib-Lexing.md deleted file mode 100644 index 44ca6045c..000000000 --- a/docs/api/re/melange/Stdlib-Lexing.md +++ /dev/null @@ -1,136 +0,0 @@ - -# Module `Stdlib.Lexing` - -The run-time library for lexers generated by `ocamllex`. - - -## Positions - -``` -type position = { -``` -`pos_fname : string;` -`pos_lnum : int;` -`pos_bol : int;` -`pos_cnum : int;` -``` -} -``` -A value of type `position` describes a point in a source file. `pos_fname` is the file name; `pos_lnum` is the line number; `pos_bol` is the offset of the beginning of the line (number of characters between the beginning of the lexbuf and the beginning of the line); `pos_cnum` is the offset of the position (number of characters between the beginning of the lexbuf and the position). The difference between `pos_cnum` and `pos_bol` is the character offset within the line (i.e. the column number, assuming each character is one column wide). - -See the documentation of type `lexbuf` for information about how the lexing engine will manage positions. - -``` -val dummy_pos : position -``` -A value of type `position`, guaranteed to be different from any valid position. - - -## Lexer buffers - -``` -type lexbuf = { -``` -`refill_buff : lexbuf -> unit;` -`mutable lex_buffer : bytes;` -`mutable lex_buffer_len : int;` -`mutable lex_abs_pos : int;` -`mutable lex_start_pos : int;` -`mutable lex_curr_pos : int;` -`mutable lex_last_pos : int;` -`mutable lex_last_action : int;` -`mutable lex_eof_reached : bool;` -`mutable lex_mem : int array;` -`mutable lex_start_p : position;` -`mutable lex_curr_p : position;` -``` -} -``` -The type of lexer buffers. A lexer buffer is the argument passed to the scanning functions defined by the generated scanners. The lexer buffer holds the current state of the scanner, plus a function to refill the buffer from the input. - -Lexers can optionally maintain the `lex_curr_p` and `lex_start_p` position fields. This "position tracking" mode is the default, and it corresponds to passing `~with_position:true` to functions that create lexer buffers. In this mode, the lexing engine and lexer actions are co-responsible for properly updating the position fields, as described in the next paragraph. When the mode is explicitly disabled (with `~with_position:false`), the lexing engine will not touch the position fields and the lexer actions should be careful not to do it either; the `lex_curr_p` and `lex_start_p` field will then always hold the `dummy_pos` invalid position. Not tracking positions avoids allocations and memory writes and can significantly improve the performance of the lexer in contexts where `lex_start_p` and `lex_curr_p` are not needed. - -Position tracking mode works as follows. At each token, the lexing engine will copy `lex_curr_p` to `lex_start_p`, then change the `pos_cnum` field of `lex_curr_p` by updating it with the number of characters read since the start of the `lexbuf`. The other fields are left unchanged by the lexing engine. In order to keep them accurate, they must be initialised before the first use of the lexbuf, and updated by the relevant lexer actions (i.e. at each end of line \-- see also `new_line`). - -``` -val from_channel : ?with_positions:bool -> in_channel -> lexbuf -``` -Create a lexer buffer on the given input channel. `Lexing.from_channel inchan` returns a lexer buffer which reads from the input channel `inchan`, at the current reading position. - -``` -val from_string : ?with_positions:bool -> string -> lexbuf -``` -Create a lexer buffer which reads from the given string. Reading starts from the first character in the string. An end-of-input condition is generated when the end of the string is reached. - -``` -val from_function : ?with_positions:bool -> (bytes -> int -> int) -> lexbuf -``` -Create a lexer buffer with the given function as its reading method. When the scanner needs more characters, it will call the given function, giving it a byte sequence `s` and a byte count `n`. The function should put `n` bytes or fewer in `s`, starting at index 0, and return the number of bytes provided. A return value of 0 means end of input. - -``` -val set_position : lexbuf -> position -> unit -``` -Set the initial tracked input position for `lexbuf` to a custom value. Ignores `pos_fname`. See [`set_filename`](./#val-set_filename) for changing this field. - -since 4.11 -``` -val set_filename : lexbuf -> string -> unit -``` -Set filename in the initial tracked position to `file` in `lexbuf`. - -since 4.11 -``` -val with_positions : lexbuf -> bool -``` -Tell whether the lexer buffer keeps track of position fields `lex_curr_p` / `lex_start_p`, as determined by the corresponding optional argument for functions that create lexer buffers (whose default value is `true`). - -When `with_positions` is `false`, lexer actions should not modify position fields. Doing it nevertheless could re-enable the `with_position` mode and degrade performances. - - -## Functions for lexer semantic actions - -The following functions can be called from the semantic actions of lexer definitions (the ML code enclosed in braces that computes the value returned by lexing functions). They give access to the character string matched by the regular expression associated with the semantic action. These functions must be applied to the argument `lexbuf`, which, in the code generated by `ocamllex`, is bound to the lexer buffer passed to the parsing function. - -``` -val lexeme : lexbuf -> string -``` -`Lexing.lexeme lexbuf` returns the string matched by the regular expression. - -``` -val lexeme_char : lexbuf -> int -> char -``` -`Lexing.lexeme_char lexbuf i` returns character number `i` in the matched string. - -``` -val lexeme_start : lexbuf -> int -``` -`Lexing.lexeme_start lexbuf` returns the offset in the input stream of the first character of the matched string. The first character of the stream has offset 0. - -``` -val lexeme_end : lexbuf -> int -``` -`Lexing.lexeme_end lexbuf` returns the offset in the input stream of the character following the last character of the matched string. The first character of the stream has offset 0. - -``` -val lexeme_start_p : lexbuf -> position -``` -Like `lexeme_start`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. - -``` -val lexeme_end_p : lexbuf -> position -``` -Like `lexeme_end`, but return a complete `position` instead of an offset. When position tracking is disabled, the function returns `dummy_pos`. - -``` -val new_line : lexbuf -> unit -``` -Update the `lex_curr_p` field of the lexbuf to reflect the start of a new line. You can call this function in the semantic action of the rule that matches the end-of-line character. The function does nothing when position tracking is disabled. - -since 3.11 - -## Miscellaneous functions - -``` -val flush_input : lexbuf -> unit -``` -Discard the contents of the buffer and reset the current position to 0. The next use of the lexbuf will trigger a refill. diff --git a/docs/api/re/melange/Stdlib-List.md b/docs/api/re/melange/Stdlib-List.md deleted file mode 100644 index 448c79785..000000000 --- a/docs/api/re/melange/Stdlib-List.md +++ /dev/null @@ -1,482 +0,0 @@ - -# Module `Stdlib.List` - -List operations. - -Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. - -The above considerations can usually be ignored if your lists are not longer than about 10000 elements. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a list = -``` -``` -| [] -``` -``` -| :: of 'a * 'a list -``` -``` - -``` -An alias for the type of lists. - -``` -val length : 'a list -> int -``` -Return the length (number of elements) of the given list. - -``` -val compare_lengths : 'a list -> 'b list -> int -``` -Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. - -since 4.05 -``` -val compare_length_with : 'a list -> int -> int -``` -Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. - -since 4.05 -``` -val is_empty : 'a list -> bool -``` -`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. - -since 5.1 -``` -val cons : 'a -> 'a list -> 'a list -``` -`cons x xs` is `x :: xs` - -since 4.03 (4.05 in ListLabels) -``` -val hd : 'a list -> 'a -``` -Return the first element of the given list. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val tl : 'a list -> 'a list -``` -Return the given list without its first element. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val nth : 'a list -> int -> 'a -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -``` -val nth_opt : 'a list -> int -> 'a option -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.05 -``` -val rev : 'a list -> 'a list -``` -List reversal. - -``` -val init : int -> (int -> 'a) -> 'a list -``` -`init len f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. -since 4.06 -``` -val append : 'a list -> 'a list -> 'a list -``` -`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. - -since 5.1 this function is tail-recursive. -``` -val rev_append : 'a list -> 'a list -> 'a list -``` -`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. - -``` -val concat : 'a list list -> 'a list -``` -Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). - -``` -val flatten : 'a list list -> 'a list -``` -Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). - - -## Comparison - -``` -val equal : ('a -> 'a -> bool) -> 'a list -> 'a list -> bool -``` -`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. - -Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. - -since 4.12 -``` -val compare : ('a -> 'a -> int) -> 'a list -> 'a list -> int -``` -`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): - -- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` -- the empty list `[]` is strictly smaller than non-empty lists -Note: the `cmp` function will be called even if the lists have different lengths. - -since 4.12 - -## Iterators - -``` -val iter : ('a -> unit) -> 'a list -> unit -``` -`iter f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. - -``` -val iteri : (int -> 'a -> unit) -> 'a list -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val map : ('a -> 'b) -> 'a list -> 'b list -``` -`map f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. - -``` -val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val rev_map : ('a -> 'b) -> 'a list -> 'b list -``` -`rev_map f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. - -``` -val filter_map : ('a -> 'b option) -> 'a list -> 'b list -``` -`filter_map f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. - -since 4.08 -``` -val concat_map : ('a -> 'b list) -> 'a list -> 'b list -``` -`concat_map f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. - -since 4.10 -``` -val fold_left_map : - ('acc -> 'a -> 'acc * 'b) -> - 'acc -> - 'a list -> - 'acc * 'b list -``` -`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. - -since 4.11 -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a list -> 'acc -``` -`fold_left f init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. - -``` -val fold_right : ('a -> 'acc -> 'acc) -> 'a list -> 'acc -> 'acc -``` -`fold_right f [a1; ...; an] init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. - - -## Iterators on two lists - -``` -val iter2 : ('a -> 'b -> unit) -> 'a list -> 'b list -> unit -``` -`iter2 f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`map2 f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val rev_map2 : ('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`rev_map2 f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. - -``` -val fold_left2 : - ('acc -> 'a -> 'b -> 'acc) -> - 'acc -> - 'a list -> - 'b list -> - 'acc -``` -`fold_left2 f init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val fold_right2 : - ('a -> 'b -> 'acc -> 'acc) -> - 'a list -> - 'b list -> - 'acc -> - 'acc -``` -`fold_right2 f [a1; ...; an] [b1; ...; bn] init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. - -## List scanning - -``` -val for_all : ('a -> bool) -> 'a list -> bool -``` -`for_all f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. - -``` -val exists : ('a -> bool) -> 'a list -> bool -``` -`exists f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. - -``` -val for_all2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val exists2 : ('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val mem : 'a -> 'a list -> bool -``` -`mem a set` is true if and only if `a` is equal to an element of `set`. - -``` -val memq : 'a -> 'a list -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. - - -## List searching - -``` -val find : ('a -> bool) -> 'a list -> 'a -``` -`find f l` returns the first element of the list `l` that satisfies the predicate `f`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. -``` -val find_opt : ('a -> bool) -> 'a list -> 'a option -``` -`find f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. - -since 4.05 -``` -val find_index : ('a -> bool) -> 'a list -> int option -``` -`find_index f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : ('a -> 'b option) -> 'a list -> 'b option -``` -`find_map f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.10 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a list -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 -``` -val filter : ('a -> bool) -> 'a list -> 'a list -``` -`filter f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. - -``` -val find_all : ('a -> bool) -> 'a list -> 'a list -``` -`find_all` is another name for [`filter`](./#val-filter). - -``` -val filteri : (int -> 'a -> bool) -> 'a list -> 'a list -``` -Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.11 - -## List manipulation - -``` -val take : int -> 'a list -> 'a list -``` -`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val drop : int -> 'a list -> 'a list -``` -`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val take_while : ('a -> bool) -> 'a list -> 'a list -``` -`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. - -since 5.3 -``` -val drop_while : ('a -> bool) -> 'a list -> 'a list -``` -`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. - -since 5.3 -``` -val partition : ('a -> bool) -> 'a list -> 'a list * 'a list -``` -`partition f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. - -``` -val partition_map : ('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list -``` -`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: - -- if `f x` is `Left y1`, then `y1` is in `l1`, and -- if `f x` is `Right y2`, then `y2` is in `l2`. -The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. - -In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. - -since 4.12 - -## Association lists - -``` -val assoc : 'a -> ('a * 'b) list -> 'b -``` -`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. -``` -val assoc_opt : 'a -> ('a * 'b) list -> 'b option -``` -`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. - -since 4.05 -``` -val assq : 'a -> ('a * 'b) list -> 'b -``` -Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val assq_opt : 'a -> ('a * 'b) list -> 'b option -``` -Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. - -since 4.05 -``` -val mem_assoc : 'a -> ('a * 'b) list -> bool -``` -Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. - -``` -val mem_assq : 'a -> ('a * 'b) list -> bool -``` -Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. - -``` -val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. - - -## Lists of pairs - -``` -val split : ('a * 'b) list -> 'a list * 'b list -``` -Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. - -``` -val combine : 'a list -> 'b list -> ('a * 'b) list -``` -Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. - -## Sorting - -``` -val sort : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val stable_sort : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val fast_sort : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val sort_uniq : ('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but also remove duplicates. - -since 4.02 (4.03 in ListLabels) -``` -val merge : ('a -> 'a -> int) -> 'a list -> 'a list -> 'a list -``` -Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). - - -## Lists and Sequences - -``` -val to_seq : 'a list -> 'a Seq.t -``` -Iterate on the list. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a list -``` -Create a list from a sequence. - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-ListLabels.md b/docs/api/re/melange/Stdlib-ListLabels.md deleted file mode 100644 index 03b11df1f..000000000 --- a/docs/api/re/melange/Stdlib-ListLabels.md +++ /dev/null @@ -1,482 +0,0 @@ - -# Module `Stdlib.ListLabels` - -List operations. - -Some functions are flagged as not tail-recursive. A tail-recursive function uses constant stack space, while a non-tail-recursive function uses stack space proportional to the length of its list argument, which can be a problem with very long lists. When the function takes several list arguments, an approximate formula giving stack usage (in some unspecified constant unit) is shown in parentheses. - -The above considerations can usually be ignored if your lists are not longer than about 10000 elements. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - -``` -type 'a t = 'a list = -``` -``` -| [] -``` -``` -| :: of 'a * 'a list -``` -``` - -``` -An alias for the type of lists. - -``` -val length : 'a list -> int -``` -Return the length (number of elements) of the given list. - -``` -val compare_lengths : 'a list -> 'b list -> int -``` -Compare the lengths of two lists. `compare_lengths l1 l2` is equivalent to `compare (length l1) (length l2)`, except that the computation stops after reaching the end of the shortest list. - -since 4.05 -``` -val compare_length_with : 'a list -> len:int -> int -``` -Compare the length of a list to an integer. `compare_length_with l len` is equivalent to `compare (length l) len`, except that the computation stops after at most `len` iterations on the list. - -since 4.05 -``` -val is_empty : 'a list -> bool -``` -`is_empty l` is true if and only if `l` has no elements. It is equivalent to `compare_length_with l 0 = 0`. - -since 5.1 -``` -val cons : 'a -> 'a list -> 'a list -``` -`cons x xs` is `x :: xs` - -since 4.03 (4.05 in ListLabels) -``` -val hd : 'a list -> 'a -``` -Return the first element of the given list. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val tl : 'a list -> 'a list -``` -Return the given list without its first element. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is empty. -``` -val nth : 'a list -> int -> 'a -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. - -raises [`Failure`](./Stdlib.md#exception-Failure) if the list is too short. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -``` -val nth_opt : 'a list -> int -> 'a option -``` -Return the `n`\-th element of the given list. The first element (head of the list) is at position 0. Return `None` if the list is too short. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.05 -``` -val rev : 'a list -> 'a list -``` -List reversal. - -``` -val init : len:int -> f:(int -> 'a) -> 'a list -``` -`init ~len ~f` is `[f 0; f 1; ...; f (len-1)]`, evaluated left to right. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if len \< 0. -since 4.06 -``` -val append : 'a list -> 'a list -> 'a list -``` -`append l0 l1` appends `l1` to `l0`. Same function as the infix operator `@`. - -since 5.1 this function is tail-recursive. -``` -val rev_append : 'a list -> 'a list -> 'a list -``` -`rev_append l1 l2` reverses `l1` and concatenates it with `l2`. This is equivalent to `(`[`rev`](./#val-rev)` l1) @ l2`. - -``` -val concat : 'a list list -> 'a list -``` -Concatenate a list of lists. The elements of the argument are all concatenated together (in the same order) to give the result. Not tail-recursive (length of the argument \+ length of the longest sub-list). - -``` -val flatten : 'a list list -> 'a list -``` -Same as [`concat`](./#val-concat). Not tail-recursive (length of the argument \+ length of the longest sub-list). - - -## Comparison - -``` -val equal : eq:('a -> 'a -> bool) -> 'a list -> 'a list -> bool -``` -`equal eq [a1; ...; an] [b1; ..; bm]` holds when the two input lists have the same length, and for each pair of elements `ai`, `bi` at the same position we have `eq ai bi`. - -Note: the `eq` function may be called even if the lists have different length. If you know your equality function is costly, you may want to check [`compare_lengths`](./#val-compare_lengths) first. - -since 4.12 -``` -val compare : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> int -``` -`compare cmp [a1; ...; an] [b1; ...; bm]` performs a lexicographic comparison of the two input lists, using the same `'a -> 'a -> int` interface as [`Stdlib.compare`](./Stdlib.md#val-compare): - -- `a1 :: l1` is smaller than `a2 :: l2` (negative result) if `a1` is smaller than `a2`, or if they are equal (0 result) and `l1` is smaller than `l2` -- the empty list `[]` is strictly smaller than non-empty lists -Note: the `cmp` function will be called even if the lists have different lengths. - -since 4.12 - -## Iterators - -``` -val iter : f:('a -> unit) -> 'a list -> unit -``` -`iter ~f [a1; ...; an]` applies function `f` in turn to `[a1; ...; an]`. It is equivalent to `f a1; f a2; ...; f an`. - -``` -val iteri : f:(int -> 'a -> unit) -> 'a list -> unit -``` -Same as [`iter`](./#val-iter), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val map : f:('a -> 'b) -> 'a list -> 'b list -``` -`map ~f [a1; ...; an]` applies function `f` to `a1, ..., an`, and builds the list `[f a1; ...; f an]` with the results returned by `f`. - -``` -val mapi : f:(int -> 'a -> 'b) -> 'a list -> 'b list -``` -Same as [`map`](./#val-map), but the function is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.00 -``` -val rev_map : f:('a -> 'b) -> 'a list -> 'b list -``` -`rev_map ~f l` gives the same result as [`rev`](./#val-rev)` (`[`map`](./#val-map)` f l)`, but is more efficient. - -``` -val filter_map : f:('a -> 'b option) -> 'a list -> 'b list -``` -`filter_map ~f l` applies `f` to every element of `l`, filters out the `None` elements and returns the list of the arguments of the `Some` elements. - -since 4.08 -``` -val concat_map : f:('a -> 'b list) -> 'a list -> 'b list -``` -`concat_map ~f l` gives the same result as [`concat`](./#val-concat)` (`[`map`](./#val-map)` f l)`. Tail-recursive. - -since 4.10 -``` -val fold_left_map : - f:('acc -> 'a -> 'acc * 'b) -> - init:'acc -> - 'a list -> - 'acc * 'b list -``` -`fold_left_map` is a combination of `fold_left` and `map` that threads an accumulator through calls to `f`. - -since 4.11 -``` -val fold_left : f:('acc -> 'a -> 'acc) -> init:'acc -> 'a list -> 'acc -``` -`fold_left ~f ~init [b1; ...; bn]` is `f (... (f (f init b1) b2) ...) bn`. - -``` -val fold_right : f:('a -> 'acc -> 'acc) -> 'a list -> init:'acc -> 'acc -``` -`fold_right ~f [a1; ...; an] ~init` is `f a1 (f a2 (... (f an init) ...))`. Not tail-recursive. - - -## Iterators on two lists - -``` -val iter2 : f:('a -> 'b -> unit) -> 'a list -> 'b list -> unit -``` -`iter2 ~f [a1; ...; an] [b1; ...; bn]` calls in turn `f a1 b1; ...; f an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`map2 ~f [a1; ...; an] [b1; ...; bn]` is `[f a1 b1; ...; f an bn]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val rev_map2 : f:('a -> 'b -> 'c) -> 'a list -> 'b list -> 'c list -``` -`rev_map2 ~f l1 l2` gives the same result as [`rev`](./#val-rev)` (`[`map2`](./#val-map2)` f l1 l2)`, but is more efficient. - -``` -val fold_left2 : - f:('acc -> 'a -> 'b -> 'acc) -> - init:'acc -> - 'a list -> - 'b list -> - 'acc -``` -`fold_left2 ~f ~init [a1; ...; an] [b1; ...; bn]` is `f (... (f (f init a1 b1) a2 b2) ...) an bn`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val fold_right2 : - f:('a -> 'b -> 'acc -> 'acc) -> - 'a list -> - 'b list -> - init:'acc -> - 'acc -``` -`fold_right2 ~f [a1; ...; an] [b1; ...; bn] ~init` is `f a1 b1 (f a2 b2 (... (f an bn init) ...))`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. Not tail-recursive. - -## List scanning - -``` -val for_all : f:('a -> bool) -> 'a list -> bool -``` -`for_all ~f [a1; ...; an]` checks if all elements of the list satisfy the predicate `f`. That is, it returns `(f a1) && (f a2) && ... && (f an)` for a non-empty list and `true` if the list is empty. - -``` -val exists : f:('a -> bool) -> 'a list -> bool -``` -`exists ~f [a1; ...; an]` checks if at least one element of the list satisfies the predicate `f`. That is, it returns `(f a1) || (f a2) || ... || (f an)` for a non-empty list and `false` if the list is empty. - -``` -val for_all2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`for_all`](./#val-for_all), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val exists2 : f:('a -> 'b -> bool) -> 'a list -> 'b list -> bool -``` -Same as [`exists`](./#val-exists), but for a two-argument predicate. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists are determined to have different lengths. -``` -val mem : 'a -> set:'a list -> bool -``` -`mem a ~set` is true if and only if `a` is equal to an element of `set`. - -``` -val memq : 'a -> set:'a list -> bool -``` -Same as [`mem`](./#val-mem), but uses physical equality instead of structural equality to compare list elements. - - -## List searching - -``` -val find : f:('a -> bool) -> 'a list -> 'a -``` -`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value that satisfies f in the list l. -``` -val find_opt : f:('a -> bool) -> 'a list -> 'a option -``` -`find ~f l` returns the first element of the list `l` that satisfies the predicate `f`. Returns `None` if there is no value that satisfies `f` in the list `l`. - -since 4.05 -``` -val find_index : f:('a -> bool) -> 'a list -> int option -``` -`find_index ~f xs` returns `Some i`, where `i` is the index of the first element of the list `xs` that satisfies `f x`, if there is such an element. - -It returns `None` if there is no such element. - -since 5.1 -``` -val find_map : f:('a -> 'b option) -> 'a list -> 'b option -``` -`find_map ~f l` applies `f` to the elements of `l` in order, and returns the first result of the form `Some v`, or `None` if none exist. - -since 4.10 -``` -val find_mapi : f:(int -> 'a -> 'b option) -> 'a list -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 5.1 -``` -val filter : f:('a -> bool) -> 'a list -> 'a list -``` -`filter ~f l` returns all the elements of the list `l` that satisfy the predicate `f`. The order of the elements in the input list is preserved. - -``` -val find_all : f:('a -> bool) -> 'a list -> 'a list -``` -`find_all` is another name for [`filter`](./#val-filter). - -``` -val filteri : f:(int -> 'a -> bool) -> 'a list -> 'a list -``` -Same as [`filter`](./#val-filter), but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -since 4.11 - -## List manipulation - -``` -val take : int -> 'a list -> 'a list -``` -`take n l` returns the prefix of `l` of length `n`, or a copy of `l` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val drop : int -> 'a list -> 'a list -``` -`drop n l` returns the suffix of `l` after `n` elements, or `[]` if `n > length l`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 5.3 -``` -val take_while : f:('a -> bool) -> 'a list -> 'a list -``` -`take_while p l` is the longest (possibly empty) prefix of `l` containing only elements that satisfy `p`. - -since 5.3 -``` -val drop_while : f:('a -> bool) -> 'a list -> 'a list -``` -`drop_while p l` is the longest (possibly empty) suffix of `l` starting at the first element that does not satisfy `p`. - -since 5.3 -``` -val partition : f:('a -> bool) -> 'a list -> 'a list * 'a list -``` -`partition ~f l` returns a pair of lists `(l1, l2)`, where `l1` is the list of all the elements of `l` that satisfy the predicate `f`, and `l2` is the list of all the elements of `l` that do not satisfy `f`. The order of the elements in the input list is preserved. - -``` -val partition_map : f:('a -> ('b, 'c) Either.t) -> 'a list -> 'b list * 'c list -``` -`partition_map f l` returns a pair of lists `(l1, l2)` such that, for each element `x` of the input list `l`: - -- if `f x` is `Left y1`, then `y1` is in `l1`, and -- if `f x` is `Right y2`, then `y2` is in `l2`. -The output elements are included in `l1` and `l2` in the same relative order as the corresponding input elements in `l`. - -In particular, `partition_map (fun x -> if f x then Left x else Right x) l` is equivalent to `partition f l`. - -since 4.12 - -## Association lists - -``` -val assoc : 'a -> ('a * 'b) list -> 'b -``` -`assoc a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc a [ ...; (a,b); ...] = b` if `(a,b)` is the leftmost binding of `a` in list `l`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no value associated with a in the list l. -``` -val assoc_opt : 'a -> ('a * 'b) list -> 'b option -``` -`assoc_opt a l` returns the value associated with key `a` in the list of pairs `l`. That is, `assoc_opt a [ ...; (a,b); ...] = Some b` if `(a,b)` is the leftmost binding of `a` in list `l`. Returns `None` if there is no value associated with `a` in the list `l`. - -since 4.05 -``` -val assq : 'a -> ('a * 'b) list -> 'b -``` -Same as [`assoc`](./#val-assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val assq_opt : 'a -> ('a * 'b) list -> 'b option -``` -Same as [`assoc_opt`](./#val-assoc_opt), but uses physical equality instead of structural equality to compare keys. - -since 4.05 -``` -val mem_assoc : 'a -> map:('a * 'b) list -> bool -``` -Same as [`assoc`](./#val-assoc), but simply return `true` if a binding exists, and `false` if no bindings exist for the given key. - -``` -val mem_assq : 'a -> map:('a * 'b) list -> bool -``` -Same as [`mem_assoc`](./#val-mem_assoc), but uses physical equality instead of structural equality to compare keys. - -``` -val remove_assoc : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -`remove_assoc a l` returns the list of pairs `l` without the first pair with key `a`, if any. Not tail-recursive. - -``` -val remove_assq : 'a -> ('a * 'b) list -> ('a * 'b) list -``` -Same as [`remove_assoc`](./#val-remove_assoc), but uses physical equality instead of structural equality to compare keys. Not tail-recursive. - - -## Lists of pairs - -``` -val split : ('a * 'b) list -> 'a list * 'b list -``` -Transform a list of pairs into a pair of lists: `split [(a1,b1); ...; (an,bn)]` is `([a1; ...; an], [b1; ...; bn])`. Not tail-recursive. - -``` -val combine : 'a list -> 'b list -> ('a * 'b) list -``` -Transform a pair of lists into a list of pairs: `combine [a1; ...; an] [b1; ...; bn]` is `[(a1,b1); ...; (an,bn)]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the two lists have different lengths. Not tail-recursive. - -## Sorting - -``` -val sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Sort a list in increasing order according to a comparison function. The comparison function must return 0 if its arguments compare as equal, a positive integer if the first is greater, and a negative integer if the first is smaller (see Array.sort for a complete specification). For example, [`Stdlib.compare`](./Stdlib.md#val-compare) is a suitable comparison function. The resulting list is sorted in increasing order. [`sort`](./#val-sort) is guaranteed to run in constant heap space (in addition to the size of the result list) and logarithmic stack space. - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val stable_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but the sorting algorithm is guaranteed to be stable (i.e. elements that compare equal are kept in their original order). - -The current implementation uses Merge Sort. It runs in constant heap space and logarithmic stack space. - -``` -val fast_sort : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort) or [`stable_sort`](./#val-stable_sort), whichever is faster on typical input. - -``` -val sort_uniq : cmp:('a -> 'a -> int) -> 'a list -> 'a list -``` -Same as [`sort`](./#val-sort), but also remove duplicates. - -since 4.02 (4.03 in ListLabels) -``` -val merge : cmp:('a -> 'a -> int) -> 'a list -> 'a list -> 'a list -``` -Merge two lists: Assuming that `l1` and `l2` are sorted according to the comparison function `cmp`, `merge ~cmp l1 l2` will return a sorted list containing all the elements of `l1` and `l2`. If several elements compare equal, the elements of `l1` will be before the elements of `l2`. Not tail-recursive (sum of the lengths of the arguments). - - -## Lists and Sequences - -``` -val to_seq : 'a list -> 'a Seq.t -``` -Iterate on the list. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a list -``` -Create a list from a sequence. - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md deleted file mode 100644 index d02ffc06f..000000000 --- a/docs/api/re/melange/Stdlib-Map-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Map-Make.md b/docs/api/re/melange/Stdlib-Map-Make.md deleted file mode 100644 index ce73f7b9a..000000000 --- a/docs/api/re/melange/Stdlib-Map-Make.md +++ /dev/null @@ -1,315 +0,0 @@ - -# Module `Map.Make` - -Functor building an implementation of the map structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Maps - -``` -type key = Ord.t -``` -The type of the map keys. - -``` -type !+'a t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key -> 'a -> 'a t -> 'a t -``` -`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key -> 'a -> 'a list t -> 'a list t -``` -`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key -> ('a option -> 'a option) -> 'a t -> 'a t -``` -`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - (key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : (key -> bool) -> 'a t -> key * 'a -``` -`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : (key -> bool) -> 'a t -> key * 'a -``` -`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : (key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : (key -> 'a -> bool) -> 'a t -> bool -``` -`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : (key -> 'a -> bool) -> 'a t -> bool -``` -`exists f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md deleted file mode 100644 index 269a6a025..000000000 --- a/docs/api/re/melange/Stdlib-Map-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Map.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-Map-Make.md). - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Map-module-type-S.md b/docs/api/re/melange/Stdlib-Map-module-type-S.md deleted file mode 100644 index 849b1ff51..000000000 --- a/docs/api/re/melange/Stdlib-Map-module-type-S.md +++ /dev/null @@ -1,306 +0,0 @@ - -# Module type `Map.S` - -Output signature of the functor [`Make`](./Stdlib-Map-Make.md). - - -## Maps - -``` -type key -``` -The type of the map keys. - -``` -type !+'a t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key -> 'a -> 'a t -> 'a t -``` -`add key data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key -> 'a -> 'a list t -> 'a list t -``` -`add_to_list key data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key -> ('a option -> 'a option) -> 'a t -> 'a t -``` -`update key f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - (key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : (key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-Map-Make.md). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : (key -> bool) -> 'a t -> key * 'a -``` -`find_first f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : (key -> bool) -> 'a t -> key * 'a -``` -`find_last f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : (key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : (key -> 'a -> unit) -> 'a t -> unit -``` -`iter f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : (key -> 'a -> 'acc -> 'acc) -> 'a t -> 'acc -> 'acc -``` -`fold f m init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : (key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : (key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : (key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : (key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : (key -> 'a -> bool) -> 'a t -> bool -``` -`for_all f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : (key -> 'a -> bool) -> 'a t -> bool -``` -`exists f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Map.md b/docs/api/re/melange/Stdlib-Map.md deleted file mode 100644 index e91aa6845..000000000 --- a/docs/api/re/melange/Stdlib-Map.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `Stdlib.Map` - -Association tables over ordered types. - -This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For instance: - -```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") -``` -This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-Map-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-Map-Make.md). - -``` -module Make (Ord : OrderedType) : S with type key = Ord.t -``` -Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-Marshal.md b/docs/api/re/melange/Stdlib-Marshal.md deleted file mode 100644 index b2619652a..000000000 --- a/docs/api/re/melange/Stdlib-Marshal.md +++ /dev/null @@ -1,106 +0,0 @@ - -# Module `Stdlib.Marshal` - -Marshaling of data structures. - -This module provides functions to encode arbitrary data structures as sequences of bytes, which can then be written on a file or sent over a pipe or network connection. The bytes can then be read back later, possibly in another process, and decoded back into a data structure. The format for the byte sequences is compatible across all machines for a given version of OCaml. - -Warning: marshaling is currently not type-safe. The type of marshaled data is not transmitted along the value of the data, making it impossible to check that the data read back possesses the type expected by the context. In particular, the result type of the `Marshal.from_*` functions is given as `'a`, but this is misleading: the returned OCaml value does not possess type `'a` for all `'a`; it has one, unique type which cannot be determined at compile-time. The programmer should explicitly give the expected type of the returned value, using the following syntax: - -- `(Marshal.from_channel chan : type)`. Anything can happen at run-time if the object in the file does not belong to the given type. -Values of extensible variant types, for example exceptions (of extensible type `exn`), returned by the unmarshaller should not be pattern-matched over through `match ... with` or `try ... with`, because unmarshalling does not preserve the information required for matching their constructors. Structural equalities with other extensible variant values does not work either. Most other uses such as Printexc.to\_string, will still work as expected. - -The representation of marshaled values is not human-readable, and uses bytes that are not printable characters. Therefore, input and output channels used in conjunction with `Marshal.to_channel` and `Marshal.from_channel` must be opened in binary mode, using e.g. `open_out_bin` or `open_in_bin`; channels opened in text mode will cause unmarshaling errors on platforms where text channels behave differently than binary channels, e.g. Windows. - -``` -type extern_flags = -``` -``` -| No_sharing -``` -Don't preserve sharing - -``` -| Closures -``` -Send function closures - -``` -| Compat_32 -``` -Ensure 32-bit compatibility - -``` - -``` -The flags to the `Marshal.to_*` functions below. - -``` -val to_channel : out_channel -> 'a -> extern_flags list -> unit -``` -`Marshal.to_channel chan v flags` writes the representation of `v` on channel `chan`. The `flags` argument is a possibly empty list of flags that governs the marshaling behavior with respect to sharing, functional values, and compatibility between 32- and 64-bit platforms. - -If `flags` does not contain `Marshal.No_sharing`, circularities and sharing inside the value `v` are detected and preserved in the sequence of bytes produced. In particular, this guarantees that marshaling always terminates. Sharing between values marshaled by successive calls to `Marshal.to_channel` is neither detected nor preserved, though. If `flags` contains `Marshal.No_sharing`, sharing is ignored. This results in faster marshaling if `v` contains no shared substructures, but may cause slower marshaling and larger byte representations if `v` actually contains sharing, or even non-termination if `v` contains cycles. - -If `flags` does not contain `Marshal.Closures`, marshaling fails when it encounters a functional value inside `v`: only 'pure' data structures, containing neither functions nor objects, can safely be transmitted between different programs. If `flags` contains `Marshal.Closures`, functional values will be marshaled as a the position in the code of the program together with the values corresponding to the free variables captured in the closure. In this case, the output of marshaling can only be read back in processes that run exactly the same program, with exactly the same compiled code. (This is checked at un-marshaling time, using an MD5 digest of the code transmitted along with the code position.) - -The exact definition of which free variables are captured in a closure is not specified and can vary between bytecode and native code (and according to optimization flags). In particular, a function value accessing a global reference may or may not include the reference in its closure. If it does, unmarshaling the corresponding closure will create a new reference, different from the global one. - -If `flags` contains `Marshal.Compat_32`, marshaling fails when it encounters an integer value outside the range `-2``30`, `2``30``-1` of integers that are representable on a 32-bit platform. This ensures that marshaled data generated on a 64-bit platform can be safely read back on a 32-bit platform. If `flags` does not contain `Marshal.Compat_32`, integer values outside the range `-2``30`, `2``30``-1` are marshaled, and can be read back on a 64-bit platform, but will cause an error at un-marshaling time when read back on a 32-bit platform. The `Mashal.Compat_32` flag only matters when marshaling is performed on a 64-bit platform; it has no effect if marshaling is performed on a 32-bit platform. - -raises [`Failure`](./Stdlib.md#exception-Failure) if chan is not in binary mode. -``` -val to_bytes : 'a -> extern_flags list -> bytes -``` -`Marshal.to_bytes v flags` returns a byte sequence containing the representation of `v`. The `flags` argument has the same meaning as for [`Marshal.to_channel`](./#val-to_channel). - -since 4.02 -``` -val to_string : 'a -> extern_flags list -> string -``` -Same as `to_bytes` but return the result as a string instead of a byte sequence. - -``` -val to_buffer : bytes -> int -> int -> 'a -> extern_flags list -> int -``` -`Marshal.to_buffer buff ofs len v flags` marshals the value `v`, storing its byte representation in the sequence `buff`, starting at index `ofs`, and writing at most `len` bytes. It returns the number of bytes actually written to the sequence. If the byte representation of `v` does not fit in `len` characters, the exception `Failure` is raised. - -``` -val from_channel : in_channel -> 'a -``` -`Marshal.from_channel chan` reads from channel `chan` the byte representation of a structured value, as produced by one of the `Marshal.to_*` functions, and reconstructs and returns the corresponding value. - -raises [`End_of_file`](./Stdlib.md#exception-End_of_file) if chan is already at the end of the file. -raises [`Failure`](./Stdlib.md#exception-Failure) if the end of the file is reached during unmarshalling itself or if chan is not in binary mode. -``` -val from_bytes : bytes -> int -> 'a -``` -`Marshal.from_bytes buff ofs` unmarshals a structured value like [`Marshal.from_channel`](./#val-from_channel) does, except that the byte representation is not read from a channel, but taken from the byte sequence `buff`, starting at position `ofs`. The byte sequence is not mutated. - -since 4.02 -``` -val from_string : string -> int -> 'a -``` -Same as `from_bytes` but take a string as argument instead of a byte sequence. - -``` -val header_size : int -``` -The bytes representing a marshaled value are composed of a fixed-size header and a variable-sized data part, whose size can be determined from the header. [`Marshal.header_size`](./#val-header_size) is the size, in bytes, of the header. [`Marshal.data_size`](./#val-data_size)` buff ofs` is the size, in bytes, of the data part, assuming a valid header is stored in `buff` starting at position `ofs`. Finally, [`Marshal.total_size`](./#val-total_size) `buff ofs` is the total size, in bytes, of the marshaled value. Both [`Marshal.data_size`](./#val-data_size) and [`Marshal.total_size`](./#val-total_size) raise `Failure` if `buff`, `ofs` does not contain a valid header. - -To read the byte representation of a marshaled value into a byte sequence, the program needs to read first [`Marshal.header_size`](./#val-header_size) bytes into the sequence, then determine the length of the remainder of the representation using [`Marshal.data_size`](./#val-data_size), make sure the sequence is large enough to hold the remaining data, then read it, and finally call [`Marshal.from_bytes`](./#val-from_bytes) to unmarshal the value. - -``` -val data_size : bytes -> int -> int -``` -See [`Marshal.header_size`](./#val-header_size). - -``` -val total_size : bytes -> int -> int -``` -See [`Marshal.header_size`](./#val-header_size). - - -## Marshal and domain safety - -Care must be taken when marshaling a mutable value that may be modified by a different domain. Mutating a value that is being marshaled (i.e., turned into a sequence of bytes) is a programming error and might result in surprising values (when unmarshaling) due to tearing, since marshaling involves byte-per-byte copy. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md deleted file mode 100644 index 80efdc53c..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make-argument-1-H.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Parameter `Make.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md deleted file mode 100644 index 3743681ec..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-Make.md +++ /dev/null @@ -1,96 +0,0 @@ - -# Module `Hashtbl.Make` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - - -## Parameters - -``` -module H : HashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type 'a t = 'a Hashtbl.Make(H).t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md deleted file mode 100644 index d47afa082..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded-argument-1-H.md +++ /dev/null @@ -1,17 +0,0 @@ - -# Parameter `MakeSeeded.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md deleted file mode 100644 index 3fe6e44f2..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-MakeSeeded.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Hashtbl.MakeSeeded` - -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./Stdlib-MoreLabels-Hashtbl.md#val-randomize)). - -since 4.00 - -## Parameters - -``` -module H : SeededHashedType -``` - -## Signature - -``` -type key = H.t -``` -``` -type 'a t = 'a Hashtbl.MakeSeeded(H).t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md deleted file mode 100644 index b8aa185ce..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-HashedType.md +++ /dev/null @@ -1,23 +0,0 @@ - -# Module type `Hashtbl.HashedType` - -The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md deleted file mode 100644 index 9843ac29b..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-S.md +++ /dev/null @@ -1,87 +0,0 @@ - -# Module type `Hashtbl.S` - -The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -type key -``` -``` -type !'a t -``` -``` -val create : int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -since 4.00 -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -since 4.00 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md deleted file mode 100644 index 09e30086f..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededHashedType.md +++ /dev/null @@ -1,20 +0,0 @@ - -# Module type `Hashtbl.SeededHashedType` - -The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val seeded_hash : int -> t -> int -``` -A seeded hashing function on keys. The first argument is the seed. It must be the case that if `equal x y` is true, then `seeded_hash seed x = seeded_hash seed y` for any value of `seed`. A suitable choice for `seeded_hash` is the function [`Hashtbl.seeded_hash`](./Stdlib-MoreLabels-Hashtbl.md#val-seeded_hash) below. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md deleted file mode 100644 index 909c707c6..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl-module-type-SeededS.md +++ /dev/null @@ -1,86 +0,0 @@ - -# Module type `Hashtbl.SeededS` - -The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -since 4.00 -``` -type key -``` -``` -type !'a t -``` -``` -val create : ?random:bool -> int -> 'a t -``` -``` -val clear : 'a t -> unit -``` -``` -val reset : 'a t -> unit -``` -``` -val copy : 'a t -> 'a t -``` -``` -val add : 'a t -> key:key -> data:'a -> unit -``` -``` -val remove : 'a t -> key -> unit -``` -``` -val find : 'a t -> key -> 'a -``` -``` -val find_opt : 'a t -> key -> 'a option -``` -since 4.05 -``` -val find_all : 'a t -> key -> 'a list -``` -``` -val replace : 'a t -> key:key -> data:'a -> unit -``` -``` -val mem : 'a t -> key -> bool -``` -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -``` -val filter_map_inplace : f:(key:key -> data:'a -> 'a option) -> 'a t -> unit -``` -since 4.03 -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -``` -val length : 'a t -> int -``` -``` -val stats : 'a t -> statistics -``` -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -since 4.07 -``` -val to_seq_keys : _ t -> key Seq.t -``` -since 4.07 -``` -val to_seq_values : 'a t -> 'a Seq.t -``` -since 4.07 -``` -val add_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val replace_seq : 'a t -> (key * 'a) Seq.t -> unit -``` -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md b/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md deleted file mode 100644 index 9a4b5177e..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Hashtbl.md +++ /dev/null @@ -1,399 +0,0 @@ - -# Module `MoreLabels.Hashtbl` - -Hash tables and hash functions. - -Hash tables are hashed association tables, with in-place modification. Because most operations on a hash table modify their input, they're more commonly used in imperative code. The lookup of the value associated with a key (see [`find`](./#val-find), [`find_opt`](./#val-find_opt)) is normally very fast, often faster than the equivalent lookup in [`Map`](./Stdlib-MoreLabels-Map.md). - -The functors [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md) and [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md) can be used when performance or flexibility are key. The user provides custom equality and hash functions for the key type, and obtains a custom hash table type for this particular type of key. - -**Warning** a hash table is only as good as the hash function. A bad hash function will turn the table into a degenerate association list, with linear time lookup instead of constant time lookup. - -The polymorphic [`t`](./#type-t) hash table is useful in simpler cases or in interactive environments. It uses the polymorphic [`hash`](./#val-hash) function defined in the OCaml runtime (at the time of writing, it's SipHash), as well as the polymorphic equality `(=)`. - -See [the examples section](./#examples). - -**Unsynchronized accesses** - -Unsynchronized accesses to a hash table may lead to an invalid hash table state. Thus, concurrent accesses to a hash tables must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -## Generic interface - -``` -type (!'a, !'b) t = ('a, 'b) Hashtbl.t -``` -The type of hash tables from type `'a` to type `'b`. - -``` -val create : ?random:bool -> int -> ('a, 'b) t -``` -`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`](./#val-hash)) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. In Web-facing applications or other security-sensitive applications, the deterministic collision patterns can be exploited by a malicious user to create a denial-of-service attack: the attacker sends input crafted to create many collisions in the table, slowing the application down. - -A hash table that is created with `~random` set to `true` uses the seeded hash function [`seeded_hash`](./#val-seeded_hash) with a seed that is randomly chosen at hash table creation time. In effect, the hash function used is randomly selected among `2^{30}` different hash functions. All these hash functions have different collision patterns, rendering ineffective the denial-of-service attack described above. However, because of randomization, enumerating all elements of the hash table using [`fold`](./#val-fold) or [`iter`](./#val-iter) is no longer deterministic: elements are enumerated in different orders at different runs of the program. - -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`](./#val-randomize) or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. - -before 4.00 the ~random parameter was not present and all hash tables were created in non-randomized mode. -``` -val clear : ('a, 'b) t -> unit -``` -Empty a hash table. Use `reset` instead of `clear` to shrink the size of the bucket table to its initial size. - -``` -val reset : ('a, 'b) t -> unit -``` -Empty a hash table and shrink the size of the bucket table to its initial size. - -since 4.00 -``` -val copy : ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. - -``` -val add : ('a, 'b) t -> key:'a -> data:'b -> unit -``` -`Hashtbl.add tbl ~key ~data` adds a binding of `key` to `data` in table `tbl`. - -**Warning**: Previous bindings for `key` are not removed, but simply hidden. That is, after performing [`remove`](./#val-remove)` tbl key`, the previous binding for `key`, if any, is restored. (Same behavior as with association lists.) - -If you desire the classic behavior of replacing elements, see [`replace`](./#val-replace). - -``` -val find : ('a, 'b) t -> 'a -> 'b -``` -`Hashtbl.find tbl x` returns the current binding of `x` in `tbl`, or raises `Not_found` if no such binding exists. - -``` -val find_opt : ('a, 'b) t -> 'a -> 'b option -``` -`Hashtbl.find_opt tbl x` returns the current binding of `x` in `tbl`, or `None` if no such binding exists. - -since 4.05 -``` -val find_all : ('a, 'b) t -> 'a -> 'b list -``` -`Hashtbl.find_all tbl x` returns the list of all data associated with `x` in `tbl`. The current binding is returned first, then the previous bindings, in reverse order of introduction in the table. - -``` -val mem : ('a, 'b) t -> 'a -> bool -``` -`Hashtbl.mem tbl x` checks if `x` is bound in `tbl`. - -``` -val remove : ('a, 'b) t -> 'a -> unit -``` -`Hashtbl.remove tbl x` removes the current binding of `x` in `tbl`, restoring the previous binding if it exists. It does nothing if `x` is not bound in `tbl`. - -``` -val replace : ('a, 'b) t -> key:'a -> data:'b -> unit -``` -`Hashtbl.replace tbl ~key ~data` replaces the current binding of `key` in `tbl` by a binding of `key` to `data`. If `key` is unbound in `tbl`, a binding of `key` to `data` is added to `tbl`. This is functionally equivalent to [`remove`](./#val-remove)` tbl key` followed by [`add`](./#val-add)` tbl key data`. - -``` -val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit -``` -`Hashtbl.iter ~f tbl` applies `f` to all bindings in table `tbl`. `f` receives the key as first argument, and the associated value as second argument. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val filter_map_inplace : - f:(key:'a -> data:'b -> 'b option) -> - ('a, 'b) t -> - unit -``` -`Hashtbl.filter_map_inplace ~f tbl` applies `f` to all bindings in table `tbl` and update each binding depending on the result of `f`. If `f` returns `None`, the binding is discarded. If it returns `Some new_val`, the binding is update to associate the key to `new_val`. - -Other comments for [`iter`](./#val-iter) apply as well. - -since 4.03 -``` -val fold : - f:(key:'a -> data:'b -> 'acc -> 'acc) -> - ('a, 'b) t -> - init:'acc -> - 'acc -``` -`Hashtbl.fold ~f tbl ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `tbl`, and `d1 ... dN` are the associated values. Each binding is presented exactly once to `f`. - -The order in which the bindings are passed to `f` is unspecified. However, if the table contains several bindings for the same key, they are passed to `f` in reverse order of introduction, that is, the most recent binding is passed first. - -If the hash table was created in non-randomized mode, the order in which the bindings are enumerated is reproducible between successive runs of the program, and even between minor versions of OCaml. For randomized hash tables, the order of enumeration is entirely random. - -The behavior is not specified if the hash table is modified by `f` during the iteration. - -``` -val length : ('a, 'b) t -> int -``` -`Hashtbl.length tbl` returns the number of bindings in `tbl`. It takes constant time. Multiple bindings are counted once each, so `Hashtbl.length` gives the number of times `Hashtbl.iter` calls its first argument. - -``` -val randomize : unit -> unit -``` -After a call to `Hashtbl.randomize()`, hash tables are created in randomized mode by default: [`create`](./#val-create) returns randomized hash tables, unless the `~random:false` optional parameter is given. The same effect can be achieved by setting the `R` parameter in the `OCAMLRUNPARAM` environment variable. - -It is recommended that applications or Web frameworks that need to protect themselves against the denial-of-service attack described in [`create`](./#val-create) call `Hashtbl.randomize()` at initialization time before any domains are created. - -Note that once `Hashtbl.randomize()` was called, there is no way to revert to the non-randomized default behavior of [`create`](./#val-create). This is intentional. Non-randomized hash tables can still be created using `Hashtbl.create ~random:false`. - -since 4.00 -``` -val is_randomized : unit -> bool -``` -Return `true` if the tables are currently created in randomized mode by default, `false` otherwise. - -since 4.03 -``` -val rebuild : ?random:bool -> ('a, 'b) t -> ('a, 'b) t -``` -Return a copy of the given hashtable. Unlike [`copy`](./#val-copy), [`rebuild`](./#val-rebuild)` h` re-hashes all the (key, value) entries of the original table `h`. The returned hash table is randomized if `h` was randomized, or the optional `random` parameter is true, or if the default is to create randomized hash tables; see [`create`](./#val-create) for more information. - -[`rebuild`](./#val-rebuild) can safely be used to import a hash table built by an old version of the [`Hashtbl`](#) module, then marshaled to persistent storage. After unmarshaling, apply [`rebuild`](./#val-rebuild) to produce a hash table for the current version of the [`Hashtbl`](#) module. - -since 4.12 -``` -type statistics = Hashtbl.statistics = { -``` -`num_bindings : int;` -Number of bindings present in the table. Same value as returned by [`length`](./#val-length). - -`num_buckets : int;` -Number of buckets in the table. - -`max_bucket_length : int;` -Maximal number of bindings per bucket. - -`bucket_histogram : int array;` -Histogram of bucket sizes. This array `histo` has length `max_bucket_length + 1`. The value of `histo.(i)` is the number of buckets whose size is `i`. - -``` -} -``` -since 4.00 -``` -val stats : ('a, 'b) t -> statistics -``` -`Hashtbl.stats tbl` returns statistics about the table `tbl`: number of buckets, size of the biggest bucket, distribution of buckets by size. - -since 4.00 - -## Hash tables and Sequences - -``` -val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t -``` -Iterate on the whole table. The order in which the bindings appear in the sequence is unspecified. However, if the table contains several bindings for the same key, they appear in reversed order of introduction, that is, the most recent binding appears first. - -The behavior is not specified if the hash table is modified during the iteration. - -since 4.07 -``` -val to_seq_keys : ('a, _) t -> 'a Seq.t -``` -Same as `Seq.map fst (to_seq m)` - -since 4.07 -``` -val to_seq_values : (_, 'b) t -> 'b Seq.t -``` -Same as `Seq.map snd (to_seq m)` - -since 4.07 -``` -val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`add`](./#val-add) - -since 4.07 -``` -val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit -``` -Add the given bindings to the table, using [`replace`](./#val-replace) - -since 4.07 -``` -val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t -``` -Build a table from the given bindings. The bindings are added in the same order they appear in the sequence, using [`replace_seq`](./#val-replace_seq), which means that if two pairs have the same key, only the latest one will appear in the table. - -since 4.07 - -## Functorial interface - -The functorial interface allows the use of specific comparison and hash functions, either for performance/security concerns, or because keys are not hashable/comparable with the polymorphic builtins. - -For instance, one might want to specialize a table for integer keys: - -```ocaml - module IntHash = - struct - type t = int - let equal i j = i=j - let hash i = i land max_int - end - - module IntHashtbl = Hashtbl.Make(IntHash) - - let h = IntHashtbl.create 17 in - IntHashtbl.add h 12 "hello" -``` -This creates a new module `IntHashtbl`, with a new type `'a IntHashtbl.t` of tables from `int` to `'a`. In this example, `h` contains `string` values so its type is `string IntHashtbl.t`. - -Note that the new type `'a IntHashtbl.t` is not compatible with the type `('a,'b) Hashtbl.t` of the generic interface. For example, `Hashtbl.length h` would not type-check, you must use `IntHashtbl.length`. - -``` -module type HashedType = sig ... end -``` -The input signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -module type S = sig ... end -``` -The output signature of the functor [`Make`](./Stdlib-MoreLabels-Hashtbl-Make.md). - -``` -module Make - (H : HashedType) : - S with type key = H.t and type 'a t = 'a Hashtbl.Make(H).t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.Make` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. Since the hash function is not seeded, the `create` operation of the result structure always returns non-randomized hash tables. - -``` -module type SeededHashedType = sig ... end -``` -The input signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -``` -module type SeededS = sig ... end -``` -The output signature of the functor [`MakeSeeded`](./Stdlib-MoreLabels-Hashtbl-MakeSeeded.md). - -``` -module MakeSeeded - (H : SeededHashedType) : - SeededS with type key = H.t and type 'a t = 'a Hashtbl.MakeSeeded(H).t -``` -Functor building an implementation of the hashtable structure. The functor `Hashtbl.MakeSeeded` returns a structure containing a type `key` of keys and a type `'a t` of hash tables associating data of type `'a` to keys of type `key`. The operations perform similarly to those of the generic interface, but use the seeded hashing and equality functions specified in the functor argument `H` instead of generic equality and hashing. The `create` operation of the result structure supports the `~random` optional parameter and returns randomized hash tables if `~random:true` is passed or if randomization is globally on (see [`Hashtbl.randomize`](./#val-randomize)). - - -## The polymorphic hash functions - -``` -val hash : 'a -> int -``` -`Hashtbl.hash x` associates a nonnegative integer to any value of any type. It is guaranteed that if `x = y` or `Stdlib.compare x y = 0`, then `hash x = hash y`. Moreover, `hash` always terminates, even on cyclic structures. - -``` -val seeded_hash : int -> 'a -> int -``` -A variant of [`hash`](./#val-hash) that is further parameterized by an integer seed. - -since 4.00 -``` -val hash_param : int -> int -> 'a -> int -``` -`Hashtbl.hash_param meaningful total x` computes a hash value for `x`, with the same properties as for `hash`. The two extra integer parameters `meaningful` and `total` give more precise control over hashing. Hashing performs a breadth-first, left-to-right traversal of the structure `x`, stopping after `meaningful` meaningful nodes were encountered, or `total` nodes (meaningful or not) were encountered. If `total` as specified by the user exceeds a certain value, currently 256, then it is capped to that value. Meaningful nodes are: integers; floating-point numbers; strings; characters; booleans; and constant constructors. Larger values of `meaningful` and `total` means that more nodes are taken into account to compute the final hash value, and therefore collisions are less likely to happen. However, hashing takes longer. The parameters `meaningful` and `total` govern the tradeoff between accuracy and speed. As default choices, [`hash`](./#val-hash) and [`seeded_hash`](./#val-seeded_hash) take `meaningful = 10` and `total = 100`. - -``` -val seeded_hash_param : int -> int -> int -> 'a -> int -``` -A variant of [`hash_param`](./#val-hash_param) that is further parameterized by an integer seed. Usage: `Hashtbl.seeded_hash_param meaningful total seed x`. - -since 4.00 - -## 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 - 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 -``` - -### Counting Elements - -Given a sequence of elements (here, a [`Seq.t`](./Stdlib-Seq.md#type-t)), we want to count how many times each distinct element occurs in the sequence. A simple way to do this, assuming the elements are comparable and hashable, is to use a hash table that maps elements to their number of occurrences. - -Here we illustrate that principle using a sequence of (ascii) characters (type `char`). We use a custom `Char_tbl` specialized for `char`. - -```ocaml - # module Char_tbl = Hashtbl.Make(struct - type t = char - let equal = Char.equal - let hash = Hashtbl.hash - end) - - (* count distinct occurrences of chars in [seq] *) - # let count_chars (seq : char Seq.t) : _ list = - let counts = Char_tbl.create 16 in - Seq.iter - (fun c -> - let count_c = - Char_tbl.find_opt counts c - |> Option.value ~default:0 - in - Char_tbl.replace counts c (count_c + 1)) - seq; - (* turn into a list *) - Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] - |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) - val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = - - (* basic seq from a string *) - # let seq = String.to_seq "hello world, and all the camels in it!" - val seq : char Seq.t = - - # count_chars seq - - : (Char.t * int) list = - [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); - ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); - ('s', 1); ('t', 2); ('w', 1)] - - (* "abcabcabc..." *) - # let seq2 = - Seq.cycle (String.to_seq "abc") |> Seq.take 31 - val seq2 : char Seq.t = - - # String.of_seq seq2 - - : String.t = "abcabcabcabcabcabcabcabcabcabca" - - # count_chars seq2 - - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] - -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md deleted file mode 100644 index d02ffc06f..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Map-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md deleted file mode 100644 index b876ef70d..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Map-Make.md +++ /dev/null @@ -1,315 +0,0 @@ - -# Module `Map.Make` - -Functor building an implementation of the map structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Maps - -``` -type key = Ord.t -``` -The type of the map keys. - -``` -type 'a t = 'a Map.Make(Ord).t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key:key -> data:'a -> 'a t -> 'a t -``` -`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t -``` -`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t -``` -`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - f:(key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](#). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : f:('a -> 'b) -> 'a t -> 'b t -``` -`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md deleted file mode 100644 index 6858e0bdf..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Map.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - -``` -type t -``` -The type of the map keys. - -``` -val compare : t -> t -> int -``` -A total ordering function over the keys. This is a two-argument function `f` such that `f e1 e2` is zero if the keys `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md b/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md deleted file mode 100644 index 83ac73341..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Map-module-type-S.md +++ /dev/null @@ -1,306 +0,0 @@ - -# Module type `Map.S` - -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - - -## Maps - -``` -type key -``` -The type of the map keys. - -``` -type !+'a t -``` -The type of maps from type `key` to type `'a`. - -``` -val empty : 'a t -``` -The empty map. - -``` -val add : key:key -> data:'a -> 'a t -> 'a t -``` -`add ~key ~data m` returns a map containing the same bindings as `m`, plus a binding of `key` to `data`. If `key` was already bound in `m` to a value that is physically equal to `data`, `m` is returned unchanged (the result of the function is then physically equal to `m`). Otherwise, the previous binding of `key` in `m` disappears. - -before 4.03 Physical equality was not ensured. -``` -val add_to_list : key:key -> data:'a -> 'a list t -> 'a list t -``` -`add_to_list ~key ~data m` is `m` with `key` mapped to `l` such that `l` is `data :: Map.find key m` if `key` was bound in `m` and `[v]` otherwise. - -since 5.1 -``` -val update : key:key -> f:('a option -> 'a option) -> 'a t -> 'a t -``` -`update ~key ~f m` returns a map containing the same bindings as `m`, except for the binding of `key`. Depending on the value of `y` where `y` is `f (find_opt key m)`, the binding of `key` is added, removed or updated. If `y` is `None`, the binding is removed if it exists; otherwise, if `y` is `Some z` then `key` is associated to `z` in the resulting map. If `key` was already bound in `m` to a value that is physically equal to `z`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -since 4.06 -``` -val singleton : key -> 'a -> 'a t -``` -`singleton x y` returns the one-element map that contains a binding `y` for `x`. - -since 3.12 -``` -val remove : key -> 'a t -> 'a t -``` -`remove x m` returns a map containing the same bindings as `m`, except for `x` which is unbound in the returned map. If `x` was not in `m`, `m` is returned unchanged (the result of the function is then physically equal to `m`). - -before 4.03 Physical equality was not ensured. -``` -val merge : - f:(key -> 'a option -> 'b option -> 'c option) -> - 'a t -> - 'b t -> - 'c t -``` -`merge ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. The presence of each such binding, and the corresponding value, is determined with the function `f`. In terms of the `find_opt` operation, we have `find_opt x (merge f m1 m2) = f x (find_opt x m1) (find_opt x m2)` for any key `x`, provided that `f x None None = None`. - -since 3.12 -``` -val union : f:(key -> 'a -> 'a -> 'a option) -> 'a t -> 'a t -> 'a t -``` -`union ~f m1 m2` computes a map whose keys are a subset of the keys of `m1` and of `m2`. When the same binding is defined in both arguments, the function `f` is used to combine them. This is a special case of `merge`: `union f m1 m2` is equivalent to `merge f' m1 m2`, where - -- `f' _key None None = None` -- `f' _key (Some v) None = Some v` -- `f' _key None (Some v) = Some v` -- `f' key (Some v1) (Some v2) = f key v1 v2` -since 4.03 -``` -val cardinal : 'a t -> int -``` -Return the number of bindings of a map. - -since 3.12 - -## Bindings - -``` -val bindings : 'a t -> (key * 'a) list -``` -Return the list of all bindings of the given map. The returned list is sorted in increasing order of keys with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Map.Make`](./Stdlib-MoreLabels-Map-Make.md). - -since 3.12 -``` -val min_binding : 'a t -> key * 'a -``` -Return the binding with the smallest key in a given map (with respect to the `Ord.compare` ordering), or raise `Not_found` if the map is empty. - -since 3.12 -``` -val min_binding_opt : 'a t -> (key * 'a) option -``` -Return the binding with the smallest key in the given map (with respect to the `Ord.compare` ordering), or `None` if the map is empty. - -since 4.05 -``` -val max_binding : 'a t -> key * 'a -``` -Same as [`min_binding`](./#val-min_binding), but returns the binding with the largest key in the given map. - -since 3.12 -``` -val max_binding_opt : 'a t -> (key * 'a) option -``` -Same as [`min_binding_opt`](./#val-min_binding_opt), but returns the binding with the largest key in the given map. - -since 4.05 -``` -val choose : 'a t -> key * 'a -``` -Return one binding of the given map, or raise `Not_found` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 3.12 -``` -val choose_opt : 'a t -> (key * 'a) option -``` -Return one binding of the given map, or `None` if the map is empty. Which binding is chosen is unspecified, but equal bindings will be chosen for equal maps. - -since 4.05 - -## Searching - -``` -val find : key -> 'a t -> 'a -``` -`find x m` returns the current value of `x` in `m`, or raises `Not_found` if no binding for `x` exists. - -``` -val find_opt : key -> 'a t -> 'a option -``` -`find_opt x m` returns `Some v` if the current value of `x` in `m` is `v`, or `None` if no binding for `x` exists. - -since 4.05 -``` -val find_first : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_first ~f m`, where `f` is a monotonically increasing function, returns the binding of `m` with the lowest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -For example, `find_first (fun k -> Ord.compare k x >= 0) m` will return the first binding `k, v` of `m` where `Ord.compare k x >= 0` (intuitively: `k >= x`), or raise `Not_found` if `x` is greater than any element of `m`. - -since 4.05 -``` -val find_first_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_first_opt ~f m`, where `f` is a monotonically increasing function, returns an option containing the binding of `m` with the lowest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 -``` -val find_last : f:(key -> bool) -> 'a t -> key * 'a -``` -`find_last ~f m`, where `f` is a monotonically decreasing function, returns the binding of `m` with the highest key `k` such that `f k`, or raises `Not_found` if no such key exists. - -since 4.05 -``` -val find_last_opt : f:(key -> bool) -> 'a t -> (key * 'a) option -``` -`find_last_opt ~f m`, where `f` is a monotonically decreasing function, returns an option containing the binding of `m` with the highest key `k` such that `f k`, or `None` if no such key exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit -``` -`iter ~f m` applies `f` to all bindings in map `m`. `f` receives the key as first argument, and the associated value as second argument. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val fold : f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc -``` -`fold ~f m ~init` computes `(f kN dN ... (f k1 d1 init)...)`, where `k1 ... kN` are the keys of all bindings in `m` (in increasing order), and `d1 ... dN` are the associated data. - - -## Transforming - -``` -val map : f:('a -> 'b) -> 'a t -> 'b t -``` -`map ~f m` returns a map with same domain as `m`, where the associated value `a` of all bindings of `m` has been replaced by the result of the application of `f` to `a`. The bindings are passed to `f` in increasing order with respect to the ordering over the type of the keys. - -``` -val mapi : f:(key -> 'a -> 'b) -> 'a t -> 'b t -``` -Same as [`map`](./#val-map), but the function receives as arguments both the key and the associated value for each binding of the map. - -``` -val filter : f:(key -> 'a -> bool) -> 'a t -> 'a t -``` -`filter ~f m` returns the map with all the bindings in `m` that satisfy predicate `p`. If every binding in `m` satisfies `f`, `m` is returned unchanged (the result of the function is then physically equal to `m`) - -since 3.12 -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(key -> 'a -> 'b option) -> 'a t -> 'b t -``` -`filter_map ~f m` applies the function `f` to every binding of `m`, and builds a map from the results. For each binding `(k, v)` in the input map: - -- if `f k v` is `None` then `k` is not in the result, -- if `f k v` is `Some v'` then the binding `(k, v')` is in the output map. -For example, the following function on maps whose values are lists - -```ocaml -filter_map - (fun _k li -> match li with [] -> None | _::tl -> Some tl) - m -``` -drops all bindings of `m` whose value is an empty list, and pops the first element of each value that is non-empty. - -since 4.11 -``` -val partition : f:(key -> 'a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition ~f m` returns a pair of maps `(m1, m2)`, where `m1` contains all the bindings of `m` that satisfy the predicate `f`, and `m2` is the map with all the bindings of `m` that do not satisfy `f`. - -since 3.12 -``` -val split : key -> 'a t -> 'a t * 'a option * 'a t -``` -`split x m` returns a triple `(l, data, r)`, where `l` is the map with all the bindings of `m` whose key is strictly less than `x`; `r` is the map with all the bindings of `m` whose key is strictly greater than `x`; `data` is `None` if `m` contains no binding for `x`, or `Some v` if `m` binds `v` to `x`. - -since 3.12 - -## Predicates and comparisons - -``` -val is_empty : 'a t -> bool -``` -Test whether a map is empty or not. - -``` -val mem : key -> 'a t -> bool -``` -`mem x m` returns `true` if `m` contains a binding for `x`, and `false` otherwise. - -``` -val equal : cmp:('a -> 'a -> bool) -> 'a t -> 'a t -> bool -``` -`equal ~cmp m1 m2` tests whether the maps `m1` and `m2` are equal, that is, contain equal keys and associate them with equal data. `cmp` is the equality predicate used to compare the data associated with the keys. - -``` -val compare : cmp:('a -> 'a -> int) -> 'a t -> 'a t -> int -``` -Total ordering between maps. The first argument is a total ordering used to compare data associated with equal keys in the two maps. - -``` -val for_all : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`for_all ~f m` checks if all the bindings of the map satisfy the predicate `f`. - -since 3.12 -``` -val exists : f:(key -> 'a -> bool) -> 'a t -> bool -``` -`exists ~f m` checks if at least one binding of the map satisfies the predicate `f`. - -since 3.12 - -## Converting - -``` -val to_list : 'a t -> (key * 'a) list -``` -`to_list m` is [`bindings`](./#val-bindings)` m`. - -since 5.1 -``` -val of_list : (key * 'a) list -> 'a t -``` -`of_list bs` adds the bindings of `bs` to the empty map, in list order (if a key is bound twice in `bs` the last one takes over). - -since 5.1 -``` -val to_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in ascending order of keys - -since 4.07 -``` -val to_rev_seq : 'a t -> (key * 'a) Seq.t -``` -Iterate on the whole map, in descending order of keys - -since 4.12 -``` -val to_seq_from : key -> 'a t -> (key * 'a) Seq.t -``` -`to_seq_from k m` iterates on a subset of the bindings of `m`, in ascending order of keys, from key `k` or above. - -since 4.07 -``` -val add_seq : (key * 'a) Seq.t -> 'a t -> 'a t -``` -Add the given bindings to the map, in order. - -since 4.07 -``` -val of_seq : (key * 'a) Seq.t -> 'a t -``` -Build a map from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Map.md b/docs/api/re/melange/Stdlib-MoreLabels-Map.md deleted file mode 100644 index d7033ed13..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Map.md +++ /dev/null @@ -1,41 +0,0 @@ - -# Module `MoreLabels.Map` - -Association tables over ordered types. - -This module implements applicative association tables, also known as finite maps or dictionaries, given a total ordering function over the keys. All operations over maps are purely applicative (no side-effects). The implementation uses balanced binary trees, and therefore searching and insertion take time logarithmic in the size of the map. - -For instance: - -```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") -``` -This creates a new module `PairsMap`, with a new type `'a PairsMap.t` of maps from `int * int` to `'a`. In this example, `m` contains `string` values so its type is `string PairsMap.t`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Map-Make.md). - -``` -module Make - (Ord : OrderedType) : - S with type key = Ord.t and type 'a t = 'a Map.Make(Ord).t -``` -Functor building an implementation of the map structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md deleted file mode 100644 index 3abdead73..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Set-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md deleted file mode 100644 index df47ebd04..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Set-Make.md +++ /dev/null @@ -1,297 +0,0 @@ - -# Module `Set.Make` - -Functor building an implementation of the set structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Sets - -``` -type elt = Ord.t -``` -The type of the set elements. - -``` -type t = Set.Make(Ord).t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : f:(elt -> bool) -> t -> elt -``` -`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : f:(elt -> bool) -> t -> elt option -``` -`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : f:(elt -> bool) -> t -> elt -``` -`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : f:(elt -> bool) -> t -> elt option -``` -`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(elt -> unit) -> t -> unit -``` -`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc -``` -`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : f:(elt -> elt) -> t -> t -``` -`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : f:(elt -> bool) -> t -> t -``` -`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(elt -> elt option) -> t -> t -``` -`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : f:(elt -> bool) -> t -> t * t -``` -`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : f:(elt -> bool) -> t -> bool -``` -`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : f:(elt -> bool) -> t -> bool -``` -`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md deleted file mode 100644 index 4f07540de..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Set.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md b/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md deleted file mode 100644 index 853191d56..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Set-module-type-S.md +++ /dev/null @@ -1,288 +0,0 @@ - -# Module type `Set.S` - -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - - -## Sets - -``` -type elt -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : f:(elt -> bool) -> t -> elt -``` -`find_first ~f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : f:(elt -> bool) -> t -> elt option -``` -`find_first_opt ~f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : f:(elt -> bool) -> t -> elt -``` -`find_last ~f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : f:(elt -> bool) -> t -> elt option -``` -`find_last_opt ~f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : f:(elt -> unit) -> t -> unit -``` -`iter ~f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : f:(elt -> 'acc -> 'acc) -> t -> init:'acc -> 'acc -``` -`fold ~f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : f:(elt -> elt) -> t -> t -``` -`map ~f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : f:(elt -> bool) -> t -> t -``` -`filter ~f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : f:(elt -> elt option) -> t -> t -``` -`filter_map ~f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : f:(elt -> bool) -> t -> t * t -``` -`partition ~f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : f:(elt -> bool) -> t -> bool -``` -`for_all ~f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : f:(elt -> bool) -> t -> bool -``` -`exists ~f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-MoreLabels-Set.md b/docs/api/re/melange/Stdlib-MoreLabels-Set.md deleted file mode 100644 index 489cab218..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels-Set.md +++ /dev/null @@ -1,41 +0,0 @@ - -# Module `MoreLabels.Set` - -Sets over ordered types. - -This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. - -The [`Make`](./Stdlib-MoreLabels-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: - -```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 PairsSet = Set.Make(IntPairs) - - let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) -``` -This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-MoreLabels-Set-Make.md). - -``` -module Make - (Ord : OrderedType) : - S with type elt = Ord.t and type t = Set.Make(Ord).t -``` -Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-MoreLabels.md b/docs/api/re/melange/Stdlib-MoreLabels.md deleted file mode 100644 index 3dda53b24..000000000 --- a/docs/api/re/melange/Stdlib-MoreLabels.md +++ /dev/null @@ -1,30 +0,0 @@ - -# Module `Stdlib.MoreLabels` - -Extra labeled libraries. - -This meta-module provides labelized versions of the [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md) and [`Set`](./Stdlib-MoreLabels-Set.md) modules. - -This module is intended to be used through `open MoreLabels` which replaces [`Hashtbl`](./Stdlib-MoreLabels-Hashtbl.md), [`Map`](./Stdlib-MoreLabels-Map.md), and [`Set`](./Stdlib-MoreLabels-Set.md) with their labeled counterparts. - -For example: - -```ocaml - open MoreLabels - - Hashtbl.iter ~f:(fun ~key ~data -> g key data) table -``` -``` -module Hashtbl : sig ... end -``` -Hash tables and hash functions. - -``` -module Map : sig ... end -``` -Association tables over ordered types. - -``` -module Set : sig ... end -``` -Sets over ordered types. diff --git a/docs/api/re/melange/Stdlib-Mutex.md b/docs/api/re/melange/Stdlib-Mutex.md deleted file mode 100644 index 7e8180f6c..000000000 --- a/docs/api/re/melange/Stdlib-Mutex.md +++ /dev/null @@ -1,49 +0,0 @@ - -# Module `Stdlib.Mutex` - -Locks for mutual exclusion. - -Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses. The typical use is (if `m` is the mutex associated with the data structure `D`): - -```ocaml - Mutex.lock m; - (* Critical section that operates over D *); - Mutex.unlock m -``` -``` -type t -``` -The type of mutexes. - -``` -val create : unit -> t -``` -Return a new mutex. - -``` -val lock : t -> unit -``` -Lock the given mutex. Only one thread can have the mutex locked at any time. A thread that attempts to lock a mutex already locked by another thread will suspend until the other thread unlocks the mutex. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is already locked by the thread calling Mutex.lock. -before 4.12 Sys\_error was not raised for recursive locking (platform-dependent behaviour) -``` -val try_lock : t -> bool -``` -Same as [`Mutex.lock`](./#val-lock), but does not suspend the calling thread if the mutex is already locked: just return `false` immediately in that case. If the mutex is unlocked, lock it and return `true`. - -``` -val unlock : t -> unit -``` -Unlock the given mutex. Other threads suspended trying to lock the mutex will restart. The mutex must have been previously locked by the thread that calls [`Mutex.unlock`](./#val-unlock). - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if the mutex is unlocked or was locked by another thread. -before 4.12 Sys\_error was not raised when unlocking an unlocked mutex or when unlocking a mutex from a different thread. -``` -val protect : t -> (unit -> 'a) -> 'a -``` -`protect mutex f` runs `f()` in a critical section where `mutex` is locked (using [`lock`](./#val-lock)); it then takes care of releasing `mutex`, whether `f()` returned a value or raised an exception. - -The unlocking operation is guaranteed to always takes place, even in the event an asynchronous exception (e.g. [`Sys.Break`](./Stdlib-Sys.md#exception-Break)) is raised in some signal handler. - -since 5.1 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Obj-Ephemeron.md b/docs/api/re/melange/Stdlib-Obj-Ephemeron.md deleted file mode 100644 index 4020b901b..000000000 --- a/docs/api/re/melange/Stdlib-Obj-Ephemeron.md +++ /dev/null @@ -1,65 +0,0 @@ - -# Module `Obj.Ephemeron` - -Ephemeron with arbitrary arity and untyped - -``` -type obj_t = t -``` -alias for [`Obj.t`](./Stdlib-Obj.md#type-t) - -``` -type t -``` -an ephemeron cf [`Ephemeron`](#) - -``` -val create : int -> t -``` -`create n` returns an ephemeron with `n` keys. All the keys and the data are initially empty. The argument `n` must be between zero and [`max_ephe_length`](./#val-max_ephe_length) (limits included). - -``` -val length : t -> int -``` -return the number of keys - -``` -val get_key : t -> int -> obj_t option -``` -``` -val get_key_copy : t -> int -> obj_t option -``` -``` -val set_key : t -> int -> obj_t -> unit -``` -``` -val unset_key : t -> int -> unit -``` -``` -val check_key : t -> int -> bool -``` -``` -val blit_key : t -> int -> t -> int -> int -> unit -``` -``` -val get_data : t -> obj_t option -``` -``` -val get_data_copy : t -> obj_t option -``` -``` -val set_data : t -> obj_t -> unit -``` -``` -val unset_data : t -> unit -``` -``` -val check_data : t -> bool -``` -``` -val blit_data : t -> t -> unit -``` -``` -val max_ephe_length : int -``` -Maximum length of an ephemeron, ie the maximum number of keys an ephemeron could contain diff --git a/docs/api/re/melange/Stdlib-Obj-Extension_constructor.md b/docs/api/re/melange/Stdlib-Obj-Extension_constructor.md deleted file mode 100644 index c08771eb4..000000000 --- a/docs/api/re/melange/Stdlib-Obj-Extension_constructor.md +++ /dev/null @@ -1,15 +0,0 @@ - -# Module `Obj.Extension_constructor` - -``` -type t = extension_constructor -``` -``` -val of_val : 'a -> t -``` -``` -val name : t -> string -``` -``` -val id : t -> int -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Obj.md b/docs/api/re/melange/Stdlib-Obj.md deleted file mode 100644 index 2e619aff6..000000000 --- a/docs/api/re/melange/Stdlib-Obj.md +++ /dev/null @@ -1,139 +0,0 @@ - -# Module `Stdlib.Obj` - -Operations on internal representations of values. - -Not for the casual user. - -``` -type t -``` -``` -type raw_data = nativeint -``` -``` -val repr : 'a -> t -``` -``` -val obj : t -> 'a -``` -``` -val magic : 'a -> 'b -``` -``` -val is_block : t -> bool -``` -``` -val is_int : t -> bool -``` -``` -val tag : t -> int -``` -``` -val size : t -> int -``` -``` -val reachable_words : t -> int -``` -Computes the total size (in words, including the headers) of all heap blocks accessible from the argument. Statically allocated blocks are included. - -since 4.04 -``` -val field : t -> int -> t -``` -``` -val set_field : t -> int -> t -> unit -``` -When using flambda: - -`set_field` MUST NOT be called on immutable blocks. (Blocks allocated in C stubs, or with `new_block` below, are always considered mutable.) - -The same goes for `set_double_field`. - -For experts only: `set_field` et al can be made safe by first wrapping the block in [`Sys.opaque_identity`](./Stdlib-Sys.md#val-opaque_identity), so any information about its contents will not be propagated. - -``` -val double_field : t -> int -> float -``` -``` -val set_double_field : t -> int -> float -> unit -``` -``` -val raw_field : t -> int -> raw_data -``` -``` -val set_raw_field : t -> int -> raw_data -> unit -``` -``` -val new_block : int -> int -> t -``` -``` -val dup : t -> t -``` -``` -val add_offset : t -> Int32.t -> t -``` -``` -val with_tag : int -> t -> t -``` -``` -val first_non_constant_constructor_tag : int -``` -``` -val last_non_constant_constructor_tag : int -``` -``` -val forcing_tag : int -``` -``` -val cont_tag : int -``` -``` -val lazy_tag : int -``` -``` -val closure_tag : int -``` -``` -val object_tag : int -``` -``` -val infix_tag : int -``` -``` -val forward_tag : int -``` -``` -val no_scan_tag : int -``` -``` -val abstract_tag : int -``` -``` -val string_tag : int -``` -``` -val double_tag : int -``` -``` -val double_array_tag : int -``` -``` -val custom_tag : int -``` -``` -val int_tag : int -``` -``` -val out_of_heap_tag : int -``` -``` -val unaligned_tag : int -``` -``` -module Extension_constructor : sig ... end -``` -``` -module Ephemeron : sig ... end -``` -Ephemeron with arbitrary arity and untyped diff --git a/docs/api/re/melange/Stdlib-Oo.md b/docs/api/re/melange/Stdlib-Oo.md deleted file mode 100644 index f212cee13..000000000 --- a/docs/api/re/melange/Stdlib-Oo.md +++ /dev/null @@ -1,15 +0,0 @@ - -# Module `Stdlib.Oo` - -Operations on objects - -``` -val copy : < .. > as 'a -> 'a -``` -`Oo.copy o` returns a copy of object `o`, that is a fresh object with the same methods and instance variables as `o`. - -alert unsynchronized\_access Unsynchronized accesses to mutable objects are a programming error. -``` -val id : < .. > -> int -``` -Return an integer identifying this object, unique for the current execution of the program. The generic comparison and hashing functions are based on this integer. When an object is obtained by unmarshaling, the id is refreshed, and thus different from the original object. As a consequence, the internal invariants of data structures such as hash table or sets containing objects are broken after unmarshaling the data structures. diff --git a/docs/api/re/melange/Stdlib-Option.md b/docs/api/re/melange/Stdlib-Option.md deleted file mode 100644 index c84df4dca..000000000 --- a/docs/api/re/melange/Stdlib-Option.md +++ /dev/null @@ -1,111 +0,0 @@ - -# Module `Stdlib.Option` - -Option values. - -Option values explicitly indicate the presence or absence of a value. - -since 4.08 - -## Options - -``` -type 'a t = 'a option = -``` -``` -| None -``` -``` -| Some of 'a -``` -``` - -``` -The type for option values. Either `None` or a value `Some v`. - -``` -val none : 'a option -``` -`none` is `None`. - -``` -val some : 'a -> 'a option -``` -`some v` is `Some v`. - -``` -val value : 'a option -> default:'a -> 'a -``` -`value o ~default` is `v` if `o` is `Some v` and `default` otherwise. - -``` -val get : 'a option -> 'a -``` -`get o` is `v` if `o` is `Some v` and raise otherwise. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if o is None. -``` -val bind : 'a option -> ('a -> 'b option) -> 'b option -``` -`bind o f` is `f v` if `o` is `Some v` and `None` if `o` is `None`. - -``` -val join : 'a option option -> 'a option -``` -`join oo` is `Some v` if `oo` is `Some (Some v)` and `None` otherwise. - -``` -val map : ('a -> 'b) -> 'a option -> 'b option -``` -`map f o` is `None` if `o` is `None` and `Some (f v)` if `o` is `Some v`. - -``` -val fold : none:'a -> some:('b -> 'a) -> 'b option -> 'a -``` -`fold ~none ~some o` is `none` if `o` is `None` and `some v` if `o` is `Some v`. - -``` -val iter : ('a -> unit) -> 'a option -> unit -``` -`iter f o` is `f v` if `o` is `Some v` and `()` otherwise. - - -## Predicates and comparisons - -``` -val is_none : 'a option -> bool -``` -`is_none o` is `true` if and only if `o` is `None`. - -``` -val is_some : 'a option -> bool -``` -`is_some o` is `true` if and only if `o` is `Some o`. - -``` -val equal : ('a -> 'a -> bool) -> 'a option -> 'a option -> bool -``` -`equal eq o0 o1` is `true` if and only if `o0` and `o1` are both `None` or if they are `Some v0` and `Some v1` and `eq v0 v1` is `true`. - -``` -val compare : ('a -> 'a -> int) -> 'a option -> 'a option -> int -``` -`compare cmp o0 o1` is a total order on options using `cmp` to compare values wrapped by `Some _`. `None` is smaller than `Some _` values. - - -## Converting - -``` -val to_result : none:'e -> 'a option -> ('a, 'e) result -``` -`to_result ~none o` is `Ok v` if `o` is `Some v` and `Error none` otherwise. - -``` -val to_list : 'a option -> 'a list -``` -`to_list o` is `[]` if `o` is `None` and `[v]` if `o` is `Some v`. - -``` -val to_seq : 'a option -> 'a Seq.t -``` -`to_seq o` is `o` as a sequence. `None` is the empty sequence and `Some v` is the singleton sequence containing `v`. diff --git a/docs/api/re/melange/Stdlib-Out_channel.md b/docs/api/re/melange/Stdlib-Out_channel.md deleted file mode 100644 index 35eade38e..000000000 --- a/docs/api/re/melange/Stdlib-Out_channel.md +++ /dev/null @@ -1,239 +0,0 @@ - -# Module `Stdlib.Out_channel` - -Output channels. - -This module provides functions for working with output channels. - -See [the example section](./#examples) below. - -since 4.14 - -## Channels - -``` -type t = out_channel -``` -The type of output channel. - -``` -type open_flag = open_flag = -``` -``` -| Open_rdonly -``` -open for reading. - -``` -| Open_wronly -``` -open for writing. - -``` -| Open_append -``` -open for appending: always write at end of file. - -``` -| Open_creat -``` -create the file if it does not exist. - -``` -| Open_trunc -``` -empty the file if it already exists. - -``` -| Open_excl -``` -fail if Open\_creat and the file already exists. - -``` -| Open_binary -``` -open in binary mode (no conversion). - -``` -| Open_text -``` -open in text mode (may perform conversions). - -``` -| Open_nonblock -``` -open in non-blocking mode. - -``` - -``` -Opening modes for [`open_gen`](./#val-open_gen). - -``` -val stdout : t -``` -The standard output for the process. - -``` -val stderr : t -``` -The standard error output for the process. - -``` -val open_bin : string -> t -``` -Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. - -``` -val open_text : string -> t -``` -Same as [`open_bin`](./#val-open_bin), but the file is opened in text mode, so that newline translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`open_bin`](./#val-open_bin). - -``` -val open_gen : open_flag list -> int -> string -> t -``` -`open_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`open_text`](./#val-open_text) and [`open_bin`](./#val-open_bin) are special cases of this function. - -``` -val with_open_bin : string -> (t -> 'a) -> 'a -``` -`with_open_bin fn f` opens a channel `oc` on file `fn` and returns `f oc`. After `f` returns, either with a value or by raising an exception, `oc` is guaranteed to be closed. - -``` -val with_open_text : string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but the channel is opened in text mode (see [`open_text`](./#val-open_text)). - -``` -val with_open_gen : open_flag list -> int -> string -> (t -> 'a) -> 'a -``` -Like [`with_open_bin`](./#val-with_open_bin), but can specify the opening mode and file permission, in case the file must be created (see [`open_gen`](./#val-open_gen)). - -``` -val close : t -> unit -``` -Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except [`close`](./#val-close) and [`flush`](./#val-flush), which do nothing when applied to an already closed channel. Note that [`close`](./#val-close) may raise `Sys_error` if the operating system signals an error when flushing or closing. - -``` -val close_noerr : t -> unit -``` -Same as [`close`](./#val-close), but ignore all errors. - - -## Output - -``` -val output_char : t -> char -> unit -``` -Write the character on the given output channel. - -``` -val output_byte : t -> int -> unit -``` -Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. - -``` -val output_string : t -> string -> unit -``` -Write the string on the given output channel. - -``` -val output_bytes : t -> bytes -> unit -``` -Write the byte sequence on the given output channel. - - -## Advanced output - -``` -val output : t -> bytes -> int -> int -> unit -``` -`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val output_substring : t -> string -> int -> int -> unit -``` -Same as [`output`](./#val-output) but take a string as argument instead of a byte sequence. - - -## Flushing - -``` -val flush : t -> unit -``` -Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. - -``` -val flush_all : unit -> unit -``` -Flush all open output channels; ignore errors. - - -## Seeking - -``` -val seek : t -> int64 -> unit -``` -`seek chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. - -``` -val pos : t -> int64 -``` -Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). - -For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with [`pos`](./#val-pos), then going back to this position using [`seek`](./#val-seek) will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - - -## Attributes - -``` -val length : t -> int64 -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. - -``` -val set_binary_mode : t -> bool -> unit -``` -`set_binary_mode oc true` sets the channel `oc` to binary mode: no translations take place during output. - -`set_binary_mode oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. - -This function has no effect under operating systems that do not distinguish between text mode and binary mode. - -``` -val is_binary_mode : t -> bool -``` -`is_binary_mode oc` returns whether the channel `oc` is in binary mode (see [`set_binary_mode`](./#val-set_binary_mode)). - -since 5.2 -``` -val set_buffered : t -> bool -> unit -``` -`set_buffered oc true` sets the channel `oc` to *buffered* mode. In this mode, data output on `oc` will be buffered until either the internal buffer is full or the function [`flush`](./#val-flush) or [`flush_all`](./#val-flush_all) is called, at which point it will be sent to the output device. - -`set_buffered oc false` sets the channel `oc` to *unbuffered* mode. In this mode, data output on `oc` will be sent to the output device immediately. - -All channels are open in *buffered* mode by default. - -``` -val is_buffered : t -> bool -``` -`is_buffered oc` returns whether the channel `oc` is buffered (see [`set_buffered`](./#val-set_buffered)). - -``` -val isatty : t -> bool -``` -`isatty oc` is `true` if `oc` refers to a terminal or console window, `false` otherwise. - -since 5.1 - -## Examples - -Writing the contents of a file: - -```ocaml - let write_file file s = - Out_channel.with_open_bin file - (fun oc -> Out_channel.output_string oc s)) -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Parsing.md b/docs/api/re/melange/Stdlib-Parsing.md deleted file mode 100644 index b95445513..000000000 --- a/docs/api/re/melange/Stdlib-Parsing.md +++ /dev/null @@ -1,61 +0,0 @@ - -# Module `Stdlib.Parsing` - -The run-time library for parsers generated by `ocamlyacc`. - -``` -val symbol_start : unit -> int -``` -`symbol_start` and [`Parsing.symbol_end`](./#val-symbol_end) are to be called in the action part of a grammar rule only. They return the offset of the string that matches the left-hand side of the rule: `symbol_start()` returns the offset of the first character; `symbol_end()` returns the offset after the last character. The first character in a file is at offset 0. - -``` -val symbol_end : unit -> int -``` -See [`Parsing.symbol_start`](./#val-symbol_start). - -``` -val rhs_start : int -> int -``` -Same as [`Parsing.symbol_start`](./#val-symbol_start) and [`Parsing.symbol_end`](./#val-symbol_end), but return the offset of the string matching the `n`th item on the right-hand side of the rule, where `n` is the integer parameter to `rhs_start` and `rhs_end`. `n` is 1 for the leftmost item. - -``` -val rhs_end : int -> int -``` -See [`Parsing.rhs_start`](./#val-rhs_start). - -``` -val symbol_start_pos : unit -> Lexing.position -``` -Same as `symbol_start`, but return a `position` instead of an offset. - -``` -val symbol_end_pos : unit -> Lexing.position -``` -Same as `symbol_end`, but return a `position` instead of an offset. - -``` -val rhs_start_pos : int -> Lexing.position -``` -Same as `rhs_start`, but return a `position` instead of an offset. - -``` -val rhs_end_pos : int -> Lexing.position -``` -Same as `rhs_end`, but return a `position` instead of an offset. - -``` -val clear_parser : unit -> unit -``` -Empty the parser stack. Call it just after a parsing function has returned, to remove all pointers from the parser stack to structures that were built by semantic actions during parsing. This is optional, but lowers the memory requirements of the programs. - -``` -exception Parse_error -``` -Raised when a parser encounters a syntax error. Can also be raised from the action part of a grammar rule, to initiate error recovery. - -``` -val set_trace : bool -> bool -``` -Control debugging support for `ocamlyacc`\-generated parsers. After `Parsing.set_trace true`, the pushdown automaton that executes the parsers prints a trace of its actions (reading a token, shifting a state, reducing by a rule) on standard output. `Parsing.set_trace false` turns this debugging trace off. The boolean returned is the previous state of the trace flag. - -since 3.11 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Printexc-Slot.md b/docs/api/re/melange/Stdlib-Printexc-Slot.md deleted file mode 100644 index 452eda49a..000000000 --- a/docs/api/re/melange/Stdlib-Printexc-Slot.md +++ /dev/null @@ -1,45 +0,0 @@ - -# Module `Printexc.Slot` - -since 4.02 -``` -type t = backtrace_slot -``` -``` -val is_raise : t -> bool -``` -`is_raise slot` is `true` when `slot` refers to a raising point in the code, and `false` when it comes from a simple function call. - -since 4.02 -``` -val is_inline : t -> bool -``` -`is_inline slot` is `true` when `slot` refers to a call that got inlined by the compiler, and `false` when it comes from any other context. - -since 4.04 -``` -val location : t -> location option -``` -`location slot` returns the location information of the slot, if available, and `None` otherwise. - -Some possible reasons for failing to return a location are as follow: - -- the slot corresponds to a compiler-inserted raise -- the slot corresponds to a part of the program that has not been compiled with debug information (`-g`) -since 4.02 -``` -val name : t -> string option -``` -`name slot` returns the name of the function or definition enclosing the location referred to by the slot. - -`name slot` returns None if the name is unavailable, which may happen for the same reasons as `location` returning None. - -since 4.11 -``` -val format : int -> t -> string option -``` -`format pos slot` returns the string representation of `slot` as `raw_backtrace_to_string` would format it, assuming it is the `pos`\-th element of the backtrace: the `0`\-th element is pretty-printed differently than the others. - -Whole-backtrace printing functions also skip some uninformative slots; in that case, `format pos slot` returns `None`. - -since 4.02 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Printexc.md b/docs/api/re/melange/Stdlib-Printexc.md deleted file mode 100644 index 47bfc94fe..000000000 --- a/docs/api/re/melange/Stdlib-Printexc.md +++ /dev/null @@ -1,280 +0,0 @@ - -# Module `Stdlib.Printexc` - -Facilities for printing exceptions and inspecting current call stack. - -``` -type t = exn = .. -``` -The type of exception values. - -``` -val to_string : exn -> string -``` -`Printexc.to_string e` returns a string representation of the exception `e`. - -``` -val to_string_default : exn -> string -``` -`Printexc.to_string_default e` returns a string representation of the exception `e`, ignoring all registered exception printers. - -since 4.09 -``` -val print : ('a -> 'b) -> 'a -> 'b -``` -`Printexc.print fn x` applies `fn` to `x` and returns the result. If the evaluation of `fn x` raises any exception, the name of the exception is printed on standard error output, and the exception is raised again. The typical use is to catch and report exceptions that escape a function application. - -``` -val catch : ('a -> 'b) -> 'a -> 'b -``` -`Printexc.catch fn x` is similar to [`Printexc.print`](./#val-print), but aborts the program with exit code 2 after printing the uncaught exception. This function is deprecated: the runtime system is now able to print uncaught exceptions as precisely as `Printexc.catch` does. Moreover, calling `Printexc.catch` makes it harder to track the location of the exception using the debugger or the stack backtrace facility. So, do not use `Printexc.catch` in new code. - -deprecated This function is no longer needed. -``` -val print_backtrace : out_channel -> unit -``` -`Printexc.print_backtrace oc` prints an exception backtrace on the output channel `oc`. The backtrace lists the program locations where the most-recently raised exception was raised and where it was propagated through function calls. - -If the call is not inside an exception handler, the returned backtrace is unspecified. If the call is after some exception-catching code (before in the handler, or in a when-guard during the matching of the exception handler), the backtrace may correspond to a later exception than the handled one. - -since 3.11 -``` -val get_backtrace : unit -> string -``` -`Printexc.get_backtrace ()` returns a string containing the same exception backtrace that `Printexc.print_backtrace` would print. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). - -since 3.11 -``` -val record_backtrace : bool -> unit -``` -`Printexc.record_backtrace b` turns recording of exception backtraces on (if `b = true`) or off (if `b = false`). Initially, backtraces are not recorded, unless the `b` flag is given to the program through the `OCAMLRUNPARAM` variable. - -since 3.11 -``` -val backtrace_status : unit -> bool -``` -`Printexc.backtrace_status()` returns `true` if exception backtraces are currently recorded, `false` if not. - -since 3.11 -``` -val register_printer : (exn -> string option) -> unit -``` -`Printexc.register_printer fn` registers `fn` as an exception printer. The printer should return `None` or raise an exception if it does not know how to convert the passed exception, and `Some s` with `s` the resulting string if it can convert the passed exception. Exceptions raised by the printer are ignored. - -When converting an exception into a string, the printers will be invoked in the reverse order of their registrations, until a printer returns a `Some s` value (if no such printer exists, the runtime will use a generic printer). - -When using this mechanism, one should be aware that an exception backtrace is attached to the thread that saw it raised, rather than to the exception itself. Practically, it means that the code related to `fn` should not use the backtrace if it has itself raised an exception before. - -since 3.11.2 -``` -val use_printers : exn -> string option -``` -`Printexc.use_printers e` returns `None` if there are no registered printers and `Some s` with `s` the resulting string otherwise. - -since 4.09 - -## Raw backtraces - -``` -type raw_backtrace -``` -The type `raw_backtrace` stores a backtrace in a low-level format, which can be converted to usable form using `raw_backtrace_entries` and `backtrace_slots_of_raw_entry` below. - -Converting backtraces to `backtrace_slot`s is slower than capturing the backtraces. If an application processes many backtraces, it can be useful to use `raw_backtrace` to avoid or delay conversion. - -Raw backtraces cannot be marshalled. If you need marshalling, you should use the array returned by the `backtrace_slots` function of the next section. - -since 4.01 -``` -type raw_backtrace_entry = private int -``` -A `raw_backtrace_entry` is an element of a `raw_backtrace`. - -Each `raw_backtrace_entry` is an opaque integer, whose value is not stable between different programs, or even between different runs of the same binary. - -A `raw_backtrace_entry` can be converted to a usable form using `backtrace_slots_of_raw_entry` below. Note that, due to inlining, a single `raw_backtrace_entry` may convert to several `backtrace_slot`s. Since the values of a `raw_backtrace_entry` are not stable, they cannot be marshalled. If they are to be converted, the conversion must be done by the process that generated them. - -Again due to inlining, there may be multiple distinct raw\_backtrace\_entry values that convert to equal `backtrace_slot`s. However, if two `raw_backtrace_entry`s are equal as integers, then they represent the same `backtrace_slot`s. - -since 4.12 -``` -val raw_backtrace_entries : raw_backtrace -> raw_backtrace_entry array -``` -since 4.12 -``` -val get_raw_backtrace : unit -> raw_backtrace -``` -`Printexc.get_raw_backtrace ()` returns the same exception backtrace that `Printexc.print_backtrace` would print, but in a raw format. Same restriction usage than [`print_backtrace`](./#val-print_backtrace). - -since 4.01 -``` -val print_raw_backtrace : out_channel -> raw_backtrace -> unit -``` -Print a raw backtrace in the same format `Printexc.print_backtrace` uses. - -since 4.01 -``` -val raw_backtrace_to_string : raw_backtrace -> string -``` -Return a string from a raw backtrace, in the same format `Printexc.get_backtrace` uses. - -since 4.01 -``` -val raise_with_backtrace : exn -> raw_backtrace -> 'a -``` -Reraise the exception using the given raw\_backtrace for the origin of the exception - -since 4.05 - -## Current call stack - -``` -val get_callstack : int -> raw_backtrace -``` -`Printexc.get_callstack n` returns a description of the top of the call stack on the current program point (for the current thread), with at most `n` entries. (Note: this function is not related to exceptions at all, despite being part of the `Printexc` module.) - -since 4.01 - -## Uncaught exceptions - -``` -val default_uncaught_exception_handler : exn -> raw_backtrace -> unit -``` -`Printexc.default_uncaught_exception_handler` prints the exception and backtrace on standard error output. - -since 4.11 -``` -val set_uncaught_exception_handler : (exn -> raw_backtrace -> unit) -> unit -``` -`Printexc.set_uncaught_exception_handler fn` registers `fn` as the handler for uncaught exceptions. The default handler is [`Printexc.default_uncaught_exception_handler`](./#val-default_uncaught_exception_handler). - -Note that when `fn` is called all the functions registered with [`Stdlib.at_exit`](./Stdlib.md#val-at_exit) have already been called. Because of this you must make sure any output channel `fn` writes on is flushed. - -Also note that exceptions raised by user code in the interactive toplevel are not passed to this function as they are caught by the toplevel itself. - -If `fn` raises an exception, both the exceptions passed to `fn` and raised by `fn` will be printed with their respective backtrace. - -since 4.02 - -## Manipulation of backtrace information - -These functions are used to traverse the slots of a raw backtrace and extract information from them in a programmer-friendly format. - -``` -type backtrace_slot -``` -The abstract type `backtrace_slot` represents a single slot of a backtrace. - -since 4.02 -``` -val backtrace_slots : raw_backtrace -> backtrace_slot array option -``` -Returns the slots of a raw backtrace, or `None` if none of them contain useful information. - -In the return array, the slot at index `0` corresponds to the most recent function call, raise, or primitive `get_backtrace` call in the trace. - -Some possible reasons for returning `None` are as follow: - -- none of the slots in the trace come from modules compiled with debug information (`-g`) -- the program is a bytecode program that has not been linked with debug information enabled (`ocamlc -g`) -since 4.02 -``` -val backtrace_slots_of_raw_entry : - raw_backtrace_entry -> - backtrace_slot array option -``` -Returns the slots of a single raw backtrace entry, or `None` if this entry lacks debug information. - -Slots are returned in the same order as `backtrace_slots`: the slot at index `0` is the most recent call, raise, or primitive, and subsequent slots represent callers. - -since 4.12 -``` -type location = { -``` -`filename : string;` -`line_number : int;` -`start_char : int;` -`end_char : int;` -`end_line : int;` -since 5.2 -`end_col : int;` -since 5.2 -``` -} -``` -The type of location information found in backtraces. `start_char` and `end_char` are positions relative to the beginning of `line_number`. `end_col` is relative to the beginning of `end_line`. - -since 4.02 -``` -module Slot : sig ... end -``` - -## Raw backtrace slots - -``` -type raw_backtrace_slot -``` -This type is used to iterate over the slots of a `raw_backtrace`. For most purposes, `backtrace_slots_of_raw_entry` is easier to use. - -Like `raw_backtrace_entry`, values of this type are process-specific and must absolutely not be marshalled, and are unsafe to use for this reason (marshalling them may not fail, but un-marshalling and using the result will result in undefined behavior). - -Elements of this type can still be compared and hashed: when two elements are equal, then they represent the same source location (the converse is not necessarily true in presence of inlining, for example). - -since 4.02 -``` -val raw_backtrace_length : raw_backtrace -> int -``` -`raw_backtrace_length bckt` returns the number of slots in the backtrace `bckt`. - -since 4.02 -``` -val get_raw_backtrace_slot : raw_backtrace -> int -> raw_backtrace_slot -``` -`get_raw_backtrace_slot bckt pos` returns the slot in position `pos` in the backtrace `bckt`. - -since 4.02 -``` -val convert_raw_backtrace_slot : raw_backtrace_slot -> backtrace_slot -``` -Extracts the user-friendly `backtrace_slot` from a low-level `raw_backtrace_slot`. - -since 4.02 -``` -val get_raw_backtrace_next_slot : - raw_backtrace_slot -> - raw_backtrace_slot option -``` -`get_raw_backtrace_next_slot slot` returns the next slot inlined, if any. - -Sample code to iterate over all frames (inlined and non-inlined): - -```ocaml - (* Iterate over inlined frames *) - let rec iter_raw_backtrace_slot f slot = - f slot; - match get_raw_backtrace_next_slot slot with - | None -> () - | Some slot' -> iter_raw_backtrace_slot f slot' - - (* Iterate over stack frames *) - let iter_raw_backtrace f bt = - for i = 0 to raw_backtrace_length bt - 1 do - iter_raw_backtrace_slot f (get_raw_backtrace_slot bt i) - done -``` -since 4.04 - -## Exception slots - -``` -val exn_slot_id : exn -> int -``` -`Printexc.exn_slot_id` returns an integer which uniquely identifies the constructor used to create the exception value `exn` (in the current runtime). - -since 4.02 -``` -val exn_slot_name : exn -> string -``` -`Printexc.exn_slot_name exn` returns the internal name of the constructor used to create the exception value `exn`. - -since 4.02 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Printf.md b/docs/api/re/melange/Stdlib-Printf.md deleted file mode 100644 index 4c1d41539..000000000 --- a/docs/api/re/melange/Stdlib-Printf.md +++ /dev/null @@ -1,144 +0,0 @@ - -# Module `Stdlib.Printf` - -Formatted output functions. - -``` -val fprintf : out_channel -> ('a, out_channel, unit) format -> 'a -``` -`fprintf outchan format arg1 ... argN` formats the arguments `arg1` to `argN` according to the format string `format`, and outputs the resulting string on the channel `outchan`. - -The format string is a character string which contains two types of objects: plain characters, which are simply copied to the output channel, and conversion specifications, each of which causes conversion and printing of arguments. - -Conversion specifications have the following form: - -`% [flags] [width] [.precision] type` - -In short, a conversion specification consists in the `%` character, followed by optional modifiers and a type which is made of one or two characters. - -The types and their meanings are: - -- `d`, `i`: convert an integer argument to signed decimal. The flag `#` adds underscores to large values for readability. -- `u`, `n`, `l`, `L`, or `N`: convert an integer argument to unsigned decimal. Warning: `n`, `l`, `L`, and `N` are used for `scanf`, and should not be used for `printf`. The flag `#` adds underscores to large values for readability. -- `x`: convert an integer argument to unsigned hexadecimal, using lowercase letters. The flag `#` adds a `0x` prefix to non zero values. -- `X`: convert an integer argument to unsigned hexadecimal, using uppercase letters. The flag `#` adds a `0X` prefix to non zero values. -- `o`: convert an integer argument to unsigned octal. The flag `#` adds a `0` prefix to non zero values. -- `s`: insert a string argument. -- `S`: convert a string argument to OCaml syntax (double quotes, escapes). -- `c`: insert a character argument. -- `C`: convert a character argument to OCaml syntax (single quotes, escapes). -- `f`: convert a floating-point argument to decimal notation, in the style `dddd.ddd`. -- `F`: convert a floating-point argument to OCaml syntax (`dddd.` or `dddd.ddd` or `d.ddd e+-dd`). Converts to hexadecimal with the `#` flag (see `h`). -- `e` or `E`: convert a floating-point argument to decimal notation, in the style `d.ddd e+-dd` (mantissa and exponent). -- `g` or `G`: convert a floating-point argument to decimal notation, in style `f` or `e`, `E` (whichever is more compact). Moreover, any trailing zeros are removed from the fractional part of the result and the decimal-point character is removed if there is no fractional part remaining. -- `h` or `H`: convert a floating-point argument to hexadecimal notation, in the style `0xh.hhhh p+-dd` (hexadecimal mantissa, exponent in decimal and denotes a power of 2). -- `B`: convert a boolean argument to the string `true` or `false` -- `b`: convert a boolean argument (deprecated; do not use in new programs). -- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: convert an `int32` argument to the format specified by the second letter (decimal, hexadecimal, etc). -- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: convert a `nativeint` argument to the format specified by the second letter. -- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: convert an `int64` argument to the format specified by the second letter. -- `a`: user-defined printer. Take two arguments and apply the first one to `outchan` (the current output channel) and to the second argument. The first argument must therefore have type `out_channel -> 'b -> unit` and the second `'b`. The output produced by the function is inserted in the output of `fprintf` at the current point. -- `t`: same as `%a`, but take only one argument (with type `out_channel -> unit`) and apply it to `outchan`. -- `\{ fmt %\}`: convert a format string argument to its type digest. The argument must have the same type as the internal format string `fmt`. -- `( fmt %)`: format string substitution. Take a format string argument and substitute it to the internal format string `fmt` to print following arguments. The argument must have the same type as the internal format string `fmt`. -- `!`: take no argument and flush the output. -- `%`: take no argument and output one `%` character. -- `\@`: take no argument and output one `\@` character. -- `,`: take no argument and output nothing: a no-op delimiter for conversion specifications. -The optional `flags` are: - -- `-`: left-justify the output (default is right justification). -- `0`: for numerical conversions, pad with zeroes instead of spaces. -- `+`: for signed numerical conversions, prefix number with a `+` sign if positive. -- space: for signed numerical conversions, prefix number with a space if positive. -- `#`: request an alternate formatting style for the integer types and the floating-point type `F`. -The optional `width` is an integer indicating the minimal width of the result. For instance, `%6d` prints an integer, prefixing it with spaces to fill at least 6 characters. - -The optional `precision` is a dot `.` followed by an integer indicating how many digits follow the decimal point in the `%f`, `%e`, `%E`, `%h`, and `%H` conversions or the maximum number of significant digits to appear for the `%F`, `%g` and `%G` conversions. For instance, `%.4f` prints a `float` with 4 fractional digits. - -The integer in a `width` or `precision` can also be specified as `*`, in which case an extra integer argument is taken to specify the corresponding `width` or `precision`. This integer argument precedes immediately the argument to print. For instance, `%.*f` prints a `float` with as many fractional digits as the value of the argument given before the float. - -``` -val printf : ('a, out_channel, unit) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but output on `stdout`. - -``` -val eprintf : ('a, out_channel, unit) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but output on `stderr`. - -``` -val sprintf : ('a, unit, string) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, return a string containing the result of formatting the arguments. - -``` -val bprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but instead of printing on an output channel, append the formatted arguments to the given extensible buffer (see module [`Buffer`](./Stdlib-Buffer.md)). - -``` -val ifprintf : 'b -> ('a, 'b, 'c, unit) format4 -> 'a -``` -Same as [`Printf.fprintf`](./#val-fprintf), but does not print anything. Useful to ignore some material when conditionally printing. - -since 3.10 -``` -val ibprintf : Buffer.t -> ('a, Buffer.t, unit) format -> 'a -``` -Same as [`Printf.bprintf`](./#val-bprintf), but does not print anything. Useful to ignore some material when conditionally printing. - -since 4.11 -Formatted output functions with continuations. - -``` -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 -``` -val ikfprintf : ('b -> 'd) -> 'b -> ('a, 'b, 'c, 'd) format4 -> 'a -``` -Same as `kfprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 4.01 -``` -val ksprintf : (string -> 'd) -> ('a, unit, string, 'd) format4 -> 'a -``` -Same as `sprintf` above, but instead of returning the string, passes it to the first argument. - -since 3.09 -``` -val kbprintf : - (Buffer.t -> 'd) -> - Buffer.t -> - ('a, Buffer.t, unit, 'd) format4 -> - 'a -``` -Same as `bprintf`, but instead of returning immediately, passes the buffer to its first argument at the end of printing. - -since 3.10 -``` -val ikbprintf : - (Buffer.t -> 'd) -> - Buffer.t -> - ('a, Buffer.t, unit, 'd) format4 -> - 'a -``` -Same as `kbprintf` above, but does not print anything. Useful to ignore some material when conditionally printing. - -since 4.11 -Deprecated - -``` -val kprintf : (string -> 'b) -> ('a, unit, string, 'b) format4 -> 'a -``` -A deprecated synonym for `ksprintf`. - -deprecated Use Printf.ksprintf instead. \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Queue.md b/docs/api/re/melange/Stdlib-Queue.md deleted file mode 100644 index 820e40343..000000000 --- a/docs/api/re/melange/Stdlib-Queue.md +++ /dev/null @@ -1,225 +0,0 @@ - -# Module `Stdlib.Queue` - -First-in first-out queues. - -This module implements queues (FIFOs), with in-place modification. See [the example section](./#examples) below. - -**Unsynchronized accesses** - -Unsynchronized accesses to a queue may lead to an invalid queue state. Thus, concurrent accesses to queues must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -type !'a t -``` -The type of queues containing elements of type `'a`. - -``` -exception Empty -``` -Raised when [`Queue.take`](./#val-take) or [`Queue.peek`](./#val-peek) is applied to an empty queue. - -``` -val create : unit -> 'a t -``` -Return a new queue, initially empty. - -``` -val add : 'a -> 'a t -> unit -``` -`add x q` adds the element `x` at the end of the queue `q`. - -``` -val push : 'a -> 'a t -> unit -``` -`push` is a synonym for `add`. - -``` -val take : 'a t -> 'a -``` -`take q` removes and returns the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. - -``` -val take_opt : 'a t -> 'a option -``` -`take_opt q` removes and returns the first element in queue `q`, or returns `None` if the queue is empty. - -since 4.08 -``` -val pop : 'a t -> 'a -``` -`pop` is a synonym for `take`. - -``` -val peek : 'a t -> 'a -``` -`peek q` returns the first element in queue `q`, without removing it from the queue, or raises [`Empty`](./#exception-Empty) if the queue is empty. - -``` -val peek_opt : 'a t -> 'a option -``` -`peek_opt q` returns the first element in queue `q`, without removing it from the queue, or returns `None` if the queue is empty. - -since 4.08 -``` -val top : 'a t -> 'a -``` -`top` is a synonym for `peek`. - -``` -val drop : 'a t -> unit -``` -`drop q` removes the first element in queue `q`, or raises [`Empty`](./#exception-Empty) if the queue is empty. - -since 5.3 -``` -val clear : 'a t -> unit -``` -Discard all elements from a queue. - -``` -val copy : 'a t -> 'a t -``` -Return a copy of the given queue. - -``` -val is_empty : 'a t -> bool -``` -Return `true` if the given queue is empty, `false` otherwise. - -``` -val length : 'a t -> int -``` -Return the number of elements in a queue. - -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f q` applies `f` in turn to all elements of `q`, from the least recently entered to the most recently entered. The queue itself is unchanged. - -``` -val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold f accu q` is equivalent to `List.fold_left f accu l`, where `l` is the list of `q`'s elements. The queue remains unchanged. - -``` -val transfer : 'a t -> 'a t -> unit -``` -`transfer q1 q2` adds all of `q1`'s elements at the end of the queue `q2`, then clears `q1`. It is equivalent to the sequence `iter (fun x -> add x q2) q1; clear q1`, but runs in constant time. - - -## Iterators - -``` -val to_seq : 'a t -> 'a Seq.t -``` -Iterate on the queue, in front-to-back order. The behavior is not specified if the queue is modified during the iteration. - -since 4.07 -``` -val add_seq : 'a t -> 'a Seq.t -> unit -``` -Add the elements from a sequence to the end of the queue. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a t -``` -Create a queue from a sequence. - -since 4.07 - -## Examples - - -### Basic Example - -A basic example: - -```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. -``` - -### Search Through a Graph - -For a more elaborate example, a classic algorithmic use of queues is to implement a BFS (breadth-first search) through a graph. - -```ocaml - type graph = { - edges: (int, int list) Hashtbl.t - } - - (* Search in graph [g] using BFS, starting from node [start]. - It returns the first node that satisfies [p], or [None] if - no node reachable from [start] satisfies [p]. - *) - let search_for ~(g:graph) ~(start:int) (p:int -> bool) : int option = - let to_explore = Queue.create() in - let explored = Hashtbl.create 16 in - - Queue.push start to_explore; - let rec loop () = - if Queue.is_empty to_explore then None - else - (* node to explore *) - let node = Queue.pop to_explore in - explore_node node - - and explore_node node = - if not (Hashtbl.mem explored node) then ( - if p node then Some node (* found *) - else ( - Hashtbl.add explored node (); - let children = - Hashtbl.find_opt g.edges node - |> Option.value ~default:[] - in - List.iter (fun child -> Queue.push child to_explore) children; - loop() - ) - ) else loop() - in - loop() - - (* a sample graph *) - let my_graph: graph = - let edges = - List.to_seq [ - 1, [2;3]; - 2, [10; 11]; - 3, [4;5]; - 5, [100]; - 11, [0; 20]; - ] - |> Hashtbl.of_seq - in {edges} - - # search_for ~g:my_graph ~start:1 (fun x -> x = 30) - - : int option = None - - # search_for ~g:my_graph ~start:1 (fun x -> x >= 15) - - : int option = Some 20 - - # search_for ~g:my_graph ~start:1 (fun x -> x >= 50) - - : int option = Some 100 -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Random-State.md b/docs/api/re/melange/Stdlib-Random-State.md deleted file mode 100644 index cf10b7a30..000000000 --- a/docs/api/re/melange/Stdlib-Random-State.md +++ /dev/null @@ -1,50 +0,0 @@ - -# Module `Random.State` - -``` -type t -``` -The type of PRNG states. - -``` -val make : int array -> t -``` -Create a new state and initialize it with the given seed. - -``` -val make_self_init : unit -> t -``` -Create a new state and initialize it with a random seed chosen in a system-dependent way. The seed is obtained as described in [`Random.self_init`](./Stdlib-Random.md#val-self_init). - -``` -val copy : t -> t -``` -Return a copy of the given state. - -``` -val bits : t -> int -``` -``` -val int : t -> int -> int -``` -``` -val full_int : t -> int -> int -``` -``` -val int32 : t -> Int32.t -> Int32.t -``` -``` -val int64 : t -> Int64.t -> Int64.t -``` -``` -val float : t -> float -> float -``` -``` -val bool : t -> bool -``` -``` -val bits32 : t -> Int32.t -``` -``` -val bits64 : t -> Int64.t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Random.md b/docs/api/re/melange/Stdlib-Random.md deleted file mode 100644 index 98f498047..000000000 --- a/docs/api/re/melange/Stdlib-Random.md +++ /dev/null @@ -1,103 +0,0 @@ - -# Module `Stdlib.Random` - -Pseudo-random number generators (PRNG). - -With multiple domains, each domain has its own generator that evolves independently of the generators of other domains. When a domain is created, its generator is initialized by splitting the state of the generator associated with the parent domain. - -In contrast, all threads within a domain share the same domain-local generator. Independent generators can be created with the `Random.split` function and used with the functions from the [`Random.State`](./Stdlib-Random-State.md) module. - -before 5.0 Random value generation used a different algorithm. This affects all the functions in this module which return random values. - -## Basic functions - -``` -val init : int -> unit -``` -Initialize the domain-local generator, using the argument as a seed. The same seed will always yield the same sequence of numbers. - -``` -val full_init : int array -> unit -``` -Same as [`Random.init`](./#val-init) but takes more data as seed. - -``` -val self_init : unit -> unit -``` -Initialize the domain-local generator with a random seed chosen in a system-dependent way. If `/dev/urandom` is available on the host machine, it is used to provide a highly random initial seed. Otherwise, a less random seed is computed from system parameters (current time, process IDs, domain-local state). - -``` -val bits : unit -> int -``` -Return 30 random bits in a nonnegative integer. - -``` -val int : int -> int -``` -`Random.int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0 and less than 230. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0 or bound \>= 230. -``` -val full_int : int -> int -``` -`Random.full_int bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` may be any positive integer. - -If `bound` is less than 231, then `Random.full_int bound` yields identical output across systems with varying `int` sizes. - -If `bound` is less than 230, then `Random.full_int bound` is equal to [`Random.int`](./#val-int)` bound`. - -If `bound` is at least 230 (on 64-bit systems, or non-standard environments such as JavaScript), then `Random.full_int` returns a value whereas [`Random.int`](./#val-int) raises [`Stdlib.Invalid_argument`](./Stdlib.md#exception-Invalid_argument). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. -since 4.13 -``` -val int32 : Int32.t -> Int32.t -``` -`Random.int32 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. -``` -val int64 : Int64.t -> Int64.t -``` -`Random.int64 bound` returns a random integer between 0 (inclusive) and `bound` (exclusive). `bound` must be greater than 0. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if bound \<= 0. -``` -val float : float -> float -``` -`Random.float bound` returns a random floating-point number between 0 and `bound` (inclusive). If `bound` is negative, the result is negative or zero. If `bound` is 0, the result is 0. - -``` -val bool : unit -> bool -``` -`Random.bool ()` returns `true` or `false` with probability 0.5 each. - -``` -val bits32 : unit -> Int32.t -``` -`Random.bits32 ()` returns 32 random bits as an integer between [`Int32.min_int`](./Stdlib-Int32.md#val-min_int) and [`Int32.max_int`](./Stdlib-Int32.md#val-max_int). - -since 4.14 -``` -val bits64 : unit -> Int64.t -``` -`Random.bits64 ()` returns 64 random bits as an integer between [`Int64.min_int`](./Stdlib-Int64.md#val-min_int) and [`Int64.max_int`](./Stdlib-Int64.md#val-max_int). - -since 4.14 - -## Advanced functions - -The functions from module [`State`](./Stdlib-Random-State.md) manipulate the current state of the random generator explicitly. This allows using one or several deterministic PRNGs, even in a multi-threaded program, without interference from other parts of the program. - -``` -module State : sig ... end -``` -``` -val get_state : unit -> State.t -``` -`get_state()` returns a fresh copy of the current state of the domain-local generator (which is used by the basic functions). - -``` -val set_state : State.t -> unit -``` -`set_state s` updates the current state of the domain-local generator (which is used by the basic functions) by copying the state `s` into it. diff --git a/docs/api/re/melange/Stdlib-Result.md b/docs/api/re/melange/Stdlib-Result.md deleted file mode 100644 index 5e42a7a68..000000000 --- a/docs/api/re/melange/Stdlib-Result.md +++ /dev/null @@ -1,137 +0,0 @@ - -# Module `Stdlib.Result` - -Result values. - -Result values handle computation results and errors in an explicit and declarative manner without resorting to exceptions. - -since 4.08 - -## Results - -``` -type ('a, 'e) t = ('a, 'e) result = -``` -``` -| Ok of 'a -``` -``` -| Error of 'e -``` -``` - -``` -The type for result values. Either a value `Ok v` or an error `Error e`. - -``` -val ok : 'a -> ('a, 'e) result -``` -`ok v` is `Ok v`. - -``` -val error : 'e -> ('a, 'e) result -``` -`error e` is `Error e`. - -``` -val value : ('a, 'e) result -> default:'a -> 'a -``` -`value r ~default` is `v` if `r` is `Ok v` and `default` otherwise. - -``` -val get_ok : ('a, 'e) result -> 'a -``` -`get_ok r` is `v` if `r` is `Ok v` and raise otherwise. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Error \_. -``` -val get_error : ('a, 'e) result -> 'e -``` -`get_error r` is `e` if `r` is `Error e` and raise otherwise. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if r is Ok \_. -``` -val bind : ('a, 'e) result -> ('a -> ('b, 'e) result) -> ('b, 'e) result -``` -`bind r f` is `f v` if `r` is `Ok v` and `r` if `r` is `Error _`. - -``` -val join : (('a, 'e) result, 'e) result -> ('a, 'e) result -``` -`join rr` is `r` if `rr` is `Ok r` and `rr` if `rr` is `Error _`. - -``` -val map : ('a -> 'b) -> ('a, 'e) result -> ('b, 'e) result -``` -`map f r` is `Ok (f v)` if `r` is `Ok v` and `r` if `r` is `Error _`. - -``` -val map_error : ('e -> 'f) -> ('a, 'e) result -> ('a, 'f) result -``` -`map_error f r` is `Error (f e)` if `r` is `Error e` and `r` if `r` is `Ok _`. - -``` -val fold : ok:('a -> 'c) -> error:('e -> 'c) -> ('a, 'e) result -> 'c -``` -`fold ~ok ~error r` is `ok v` if `r` is `Ok v` and `error e` if `r` is `Error e`. - -``` -val iter : ('a -> unit) -> ('a, 'e) result -> unit -``` -`iter f r` is `f v` if `r` is `Ok v` and `()` otherwise. - -``` -val iter_error : ('e -> unit) -> ('a, 'e) result -> unit -``` -`iter_error f r` is `f e` if `r` is `Error e` and `()` otherwise. - - -## Predicates and comparisons - -``` -val is_ok : ('a, 'e) result -> bool -``` -`is_ok r` is `true` if and only if `r` is `Ok _`. - -``` -val is_error : ('a, 'e) result -> bool -``` -`is_error r` is `true` if and only if `r` is `Error _`. - -``` -val equal : - ok:('a -> 'a -> bool) -> - error:('e -> 'e -> bool) -> - ('a, 'e) result -> - ('a, 'e) result -> - bool -``` -`equal ~ok ~error r0 r1` tests equality of `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _` and `Error _`. - -``` -val compare : - ok:('a -> 'a -> int) -> - error:('e -> 'e -> int) -> - ('a, 'e) result -> - ('a, 'e) result -> - int -``` -`compare ~ok ~error r0 r1` totally orders `r0` and `r1` using `ok` and `error` to respectively compare values wrapped by `Ok _ ` and `Error _`. `Ok _` values are smaller than `Error _` values. - - -## Converting - -``` -val to_option : ('a, 'e) result -> 'a option -``` -`to_option r` is `r` as an option, mapping `Ok v` to `Some v` and `Error _` to `None`. - -``` -val to_list : ('a, 'e) result -> 'a list -``` -`to_list r` is `[v]` if `r` is `Ok v` and `[]` otherwise. - -``` -val to_seq : ('a, 'e) result -> 'a Seq.t -``` -`to_seq r` is `r` as a sequence. `Ok v` is the singleton sequence containing `v` and `Error _` is the empty sequence. diff --git a/docs/api/re/melange/Stdlib-Scanf-Scanning.md b/docs/api/re/melange/Stdlib-Scanf-Scanning.md deleted file mode 100644 index 1bfe20e18..000000000 --- a/docs/api/re/melange/Stdlib-Scanf-Scanning.md +++ /dev/null @@ -1,95 +0,0 @@ - -# Module `Scanf.Scanning` - -``` -type in_channel -``` -The notion of input channel for the [`Scanf`](./Stdlib-Scanf.md) module: those channels provide all the machinery necessary to read from any source of characters, including a [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) value. A Scanf.Scanning.in\_channel value is also called a *formatted input channel* or equivalently a *scanning buffer*. The type [`Scanning.scanbuf`](./#type-scanbuf) below is an alias for `Scanning.in_channel`. Note that a `Scanning.in_channel` is not concurrency-safe: concurrent use may produce arbitrary values or exceptions. - -since 3.12 -``` -type scanbuf = in_channel -``` -The type of scanning buffers. A scanning buffer is the source from which a formatted input function gets characters. The scanning buffer holds the current state of the scan, plus a function to get the next char from the input, and a token buffer to store the string matched so far. - -Note: a scanning action may often require to examine one character in advance; when this 'lookahead' character does not belong to the token read, it is stored back in the scanning buffer and becomes the next character yet to be read. - -``` -val stdin : in_channel -``` -The standard input notion for the [`Scanf`](./Stdlib-Scanf.md) module. `Scanning.stdin` is the [`Scanning.in_channel`](./#type-in_channel) formatted input channel attached to [`Stdlib.stdin`](./Stdlib.md#val-stdin). - -Note: in the interactive system, when input is read from [`Stdlib.stdin`](./Stdlib.md#val-stdin), the newline character that triggers evaluation is part of the input; thus, the scanning specifications must properly skip this additional newline character (for instance, simply add a `'\n'` as the last character of the format string). - -since 3.12 -``` -type file_name = string -``` -A convenient alias to designate a file name. - -since 4.00 -``` -val open_in : file_name -> in_channel -``` -`Scanning.open_in fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in text mode from file `fname`. - -Note: `open_in` returns a formatted input channel that efficiently reads characters in large chunks; in contrast, `from_channel` below returns formatted input channels that must read one character at a time, leading to a much slower scanning rate. - -since 3.12 -``` -val open_in_bin : file_name -> in_channel -``` -`Scanning.open_in_bin fname` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel for bufferized reading in binary mode from file `fname`. - -since 3.12 -``` -val close_in : in_channel -> unit -``` -Closes the [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) associated with the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -since 3.12 -``` -val from_file : file_name -> in_channel -``` -An alias for [`Scanning.open_in`](./#val-open_in) above. - -``` -val from_file_bin : string -> in_channel -``` -An alias for [`Scanning.open_in_bin`](./#val-open_in_bin) above. - -``` -val from_string : string -> in_channel -``` -`Scanning.from_string s` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the given string. Reading starts from the first character in the string. The end-of-input condition is set when the end of the string is reached. - -``` -val from_function : (unit -> char) -> in_channel -``` -`Scanning.from_function f` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel with the given function as its reading method. - -When scanning needs one more character, the given function is called. - -When the function has no more character to provide, it *must* signal an end-of-input condition by raising the exception `End_of_file`. - -``` -val from_channel : in_channel -> in_channel -``` -`Scanning.from_channel ic` returns a [`Scanning.in_channel`](./#type-in_channel) formatted input channel which reads from the regular [`Stdlib.in_channel`](./Stdlib.md#type-in_channel) input channel `ic` argument. Reading starts at current reading position of `ic`. - -``` -val end_of_input : in_channel -> bool -``` -`Scanning.end_of_input ic` tests the end-of-input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -``` -val beginning_of_input : in_channel -> bool -``` -`Scanning.beginning_of_input ic` tests the beginning of input condition of the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -``` -val name_of_input : in_channel -> string -``` -`Scanning.name_of_input ic` returns the name of the character source for the given [`Scanning.in_channel`](./#type-in_channel) formatted input channel. - -since 3.09 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Scanf.md b/docs/api/re/melange/Stdlib-Scanf.md deleted file mode 100644 index 717b966f9..000000000 --- a/docs/api/re/melange/Stdlib-Scanf.md +++ /dev/null @@ -1,265 +0,0 @@ - -# Module `Stdlib.Scanf` - -Formatted input functions. - - -## Introduction - - -### Functional input with format strings - -The module [`Scanf`](#) provides formatted input functions or *scanners*. - -The formatted input functions can read from any kind of input, including strings, files, or anything that can return characters. The more general source of characters is named a *formatted input channel* (or *scanning buffer*) and has type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). The more general formatted input function reads from any scanning buffer and is named `bscanf`. - -Generally speaking, the formatted input functions have 3 arguments: - -- the first argument is a source of characters for the input, -- the second argument is a format string that specifies the values to read, -- the third argument is a *receiver function* that is applied to the values read. -Hence, a typical call to the formatted input function [`Scanf.bscanf`](./#val-bscanf) is `bscanf ic fmt f`, where: - -- `ic` is a source of characters (typically a *formatted input channel* with type [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)), -- `fmt` is a format string (the same format strings as those used to print material with module [`Printf`](./Stdlib-Printf.md) or [`Format`](./Stdlib-Format.md)), -- `f` is a function that has as many arguments as the number of values to read in the input according to `fmt`. - -### A simple example - -As suggested above, the expression `bscanf ic "%d" f` reads a decimal integer `n` from the source of characters `ic` and returns `f n`. - -For instance, - -- if we use `stdin` as the source of characters ([`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) is the predefined formatted input channel that reads from standard input), -- if we define the receiver `f` as `let f x = x + 1`, -then `bscanf Scanning.stdin "%d" f` reads an integer `n` from the standard input and returns `f n` (that is `n + 1`). Thus, if we evaluate `bscanf stdin "%d" f`, and then enter `41` at the keyboard, the result we get is `42`. - - -### Formatted input as a functional feature - -The OCaml scanning facility is reminiscent of the corresponding C feature. However, it is also largely different, simpler, and yet more powerful: the formatted input functions are higher-order functionals and the parameter passing mechanism is just the regular function application not the variable assignment based mechanism which is typical for formatted input in imperative languages; the OCaml format strings also feature useful additions to easily define complex tokens; as expected within a functional programming language, the formatted input functions also support polymorphism, in particular arbitrary interaction with polymorphic user-defined scanners. Furthermore, the OCaml formatted input facility is fully type-checked at compile time. - -**Unsynchronized accesses** - -Unsynchronized accesses to a [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) may lead to an invalid [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) state. Thus, concurrent accesses to [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel)s must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - - -## Formatted input channel - -``` -module Scanning : sig ... end -``` - -## Type of formatted input functions - -``` -type ('a, 'b, 'c, 'd) scanner = - ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd, 'd) format6 -> - 'c -``` -The type of formatted input scanners: `('a, 'b, 'c, 'd) scanner` is the type of a formatted input function that reads from some formatted input channel according to some format string; more precisely, if `scan` is some formatted input function, then `scan ic fmt f` applies `f` to all the arguments specified by format string `fmt`, when `scan` has read those arguments from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic`. - -For instance, the [`Scanf.scanf`](./#val-scanf) function below has type `('a, 'b, 'c, 'd) scanner`, since it is a formatted input function that reads from [`Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin): `scanf fmt f` applies `f` to the arguments specified by `fmt`, reading those arguments from [`Stdlib.stdin`](./Stdlib.md#val-stdin) as expected. - -If the format `fmt` has some `%r` indications, the corresponding formatted input functions must be provided *before* receiver function `f`. For instance, if `read_elem` is an input function for values of type `t`, then `bscanf ic "%r;" read_elem f` reads a value `v` of type `t` followed by a `';'` character, and returns `f v`. - -since 3.10 -``` -type ('a, 'b, 'c, 'd) scanner_opt = - ('a, Scanning.in_channel, 'b, 'c, 'a -> 'd option, 'd) format6 -> - 'c -``` -``` -exception Scan_failure of string -``` -When the input can not be read according to the format string specification, formatted input functions typically raise exception `Scan_failure`. - - -## The general formatted input function - -``` -val bscanf : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner -``` -`bscanf ic fmt r1 ... rN f` reads characters from the [`Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel) formatted input channel `ic` and converts them to values according to format string `fmt`. As a final step, receiver function `f` is applied to the values read and gives the result of the `bscanf` call. - -For instance, if `f` is the function `fun s i -> i + 1`, then `Scanf.sscanf "x = 1" "%s = %i" f` returns `2`. - -Arguments `r1` to `rN` are user-defined input functions that read the argument corresponding to the `%r` conversions specified in the format string. - -``` -val bscanf_opt : Scanning.in_channel -> ('a, 'b, 'c, 'd) scanner_opt -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but returns `None` in case of scanning failure. - -since 5.0 - -## Format string description - -The format string is a character string which contains three types of objects: - -- plain characters, which are simply matched with the characters of the input (with a special case for space and line feed, see [The space character in format strings](./#space)), -- conversion specifications, each of which causes reading and conversion of one argument for the function `f` (see [Conversion specifications in format strings](./#conversion)), -- scanning indications to specify boundaries of tokens (see scanning [Scanning indications in format strings](./#indication)). - -### The space character in format strings - -As mentioned above, a plain character in the format string is just matched with the next character of the input; however, two characters are special exceptions to this rule: the space character (`' '` or ASCII code 32) and the line feed character (`'\n'` or ASCII code 10). A space does not match a single space character, but any amount of 'whitespace' in the input. More precisely, a space inside the format string matches *any number* of tab, space, line feed and carriage return characters. Similarly, a line feed character in the format string matches either a single line feed or a carriage return followed by a line feed. - -Matching *any* amount of whitespace, a space in the format string also matches no amount of whitespace at all; hence, the call `bscanf ib "Price = %d $" (fun p -> p)` succeeds and returns `1` when reading an input with various whitespace in it, such as `Price = 1 $`, `Price = 1 $`, or even `Price=1$`. - - -### Conversion specifications in format strings - -Conversion specifications consist in the `%` character, followed by an optional flag, an optional field width, and followed by one or two conversion characters. - -The conversion characters and their meanings are: - -- `d`: reads an optionally signed decimal integer (`0-9`\+). -- `i`: reads an optionally signed integer (usual input conventions for decimal (`0-9`\+), hexadecimal (`0x[0-9a-f]+` and `0X[0-9A-F]+`), octal (`0o[0-7]+`), and binary (`0b[0-1]+`) notations are understood). -- `u`: reads an unsigned decimal integer. -- `x` or `X`: reads an unsigned hexadecimal integer (`[0-9a-fA-F]+`). -- `o`: reads an unsigned octal integer (`[0-7]+`). -- `s`: reads a string argument that spreads as much as possible, until the following bounding condition holds: - - - a whitespace has been found (see [The space character in format strings](./#space)), - - a scanning indication (see scanning [Scanning indications in format strings](./#indication)) has been encountered, - - the end-of-input has been reached. - Hence, this conversion always succeeds: it returns an empty string if the bounding condition holds when the scan begins. - -- `S`: reads a delimited string argument (delimiters and special escaped characters follow the lexical conventions of OCaml). -- `c`: reads a single character. To test the current input character without reading it, specify a null field width, i.e. use specification `%0c`. Raise `Invalid_argument`, if the field width specification is greater than 1\. -- `C`: reads a single delimited character (delimiters and special escaped characters follow the lexical conventions of OCaml). -- `f`, `e`, `E`, `g`, `G`: reads an optionally signed floating-point number in decimal notation, in the style `dddd.ddd e/E+-dd`. -- `h`, `H`: reads an optionally signed floating-point number in hexadecimal notation. -- `F`: reads a floating point number according to the lexical conventions of OCaml (hence the decimal point is mandatory if the exponent part is not mentioned). -- `B`: reads a boolean argument (`true` or `false`). -- `b`: reads a boolean argument (for backward compatibility; do not use in new programs). -- `ld`, `li`, `lu`, `lx`, `lX`, `lo`: reads an `int32` argument to the format specified by the second letter for regular integers. -- `nd`, `ni`, `nu`, `nx`, `nX`, `no`: reads a `nativeint` argument to the format specified by the second letter for regular integers. -- `Ld`, `Li`, `Lu`, `Lx`, `LX`, `Lo`: reads an `int64` argument to the format specified by the second letter for regular integers. -- `[ range ]`: reads characters that matches one of the characters mentioned in the range of characters `range` (or not mentioned in it, if the range starts with `^`). Reads a `string` that can be empty, if the next input character does not match the range. The set of characters from `c1` to `c2` (inclusively) is denoted by `c1-c2`. Hence, `%[0-9]` returns a string representing a decimal number or an empty string if no decimal digit is found; similarly, `%[0-9a-f]` returns a string of hexadecimal digits. If a closing bracket appears in a range, it must occur as the first character of the range (or just after the `^` in case of range negation); hence `[]]` matches a `]` character and `[^]]` matches any character that is not `]`. Use `%%` and `%@` to include a `%` or a `@` in a range. -- `r`: user-defined reader. Takes the next `ri` formatted input function and applies it to the scanning buffer `ib` to read the next argument. The input function `ri` must therefore have type `Scanning.in_channel -> 'a` and the argument read has type `'a`. -- `{ fmt %}`: reads a format string argument. The format string read must have the same type as the format string specification `fmt`. For instance, `"%{ %i %}"` reads any format string that can read a value of type `int`; hence, if `s` is the string `"fmt:\"number is %u\""`, then `Scanf.sscanf s "fmt: %{%i%}"` succeeds and returns the format string `"number is %u"`. -- `( fmt %)`: scanning sub-format substitution. Reads a format string `rf` in the input, then goes on scanning with `rf` instead of scanning with `fmt`. The format string `rf` must have the same type as the format string specification `fmt` that it replaces. For instance, `"%( %i %)"` reads any format string that can read a value of type `int`. The conversion returns the format string read `rf`, and then a value read using `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%(%i%)" (fun fmt i -> fmt, i)` evaluates to `("%4d", 1234)`. This behaviour is not mere format substitution, since the conversion returns the format string read as additional argument. If you need pure format substitution, use special flag `_` to discard the extraneous argument: conversion `%_( fmt %)` reads a format string `rf` and then behaves the same as format string `rf`. Hence, if `s` is the string `"\"%4d\"1234.00"`, then `Scanf.sscanf s "%_(%i%)"` is simply equivalent to `Scanf.sscanf "1234.00" "%4d"`. -- `l`: returns the number of lines read so far. -- `n`: returns the number of characters read so far. -- `N` or `L`: returns the number of tokens read so far. -- `!`: matches the end of input condition. -- `%`: matches one `%` character in the input. -- `@`: matches one `@` character in the input. -- `,`: does nothing. -Following the `%` character that introduces a conversion, there may be the special flag `_`: the conversion that follows occurs as usual, but the resulting value is discarded. For instance, if `f` is the function `fun i -> i + 1`, and `s` is the string `"x = 1"`, then `Scanf.sscanf s "%_s = %i" f` returns `2`. - -The field width is composed of an optional integer literal indicating the maximal width of the token to read. For instance, `%6d` reads an integer, having at most 6 decimal digits; `%4f` reads a float with at most 4 characters; and `%8[\000-\255]` returns the next 8 characters (or all the characters still available, if fewer than 8 characters are available in the input). - -Notes: - -- as mentioned above, a `%s` conversion always succeeds, even if there is nothing to read in the input: in this case, it simply returns `""`. -- in addition to the relevant digits, `'_'` characters may appear inside numbers (this is reminiscent to the usual OCaml lexical conventions). If stricter scanning is desired, use the range conversion facility instead of the number conversions. -- the `scanf` facility is not intended for heavy duty lexical analysis and parsing. If it appears not expressive enough for your needs, several alternative exists: regular expressions (module `Str`), stream parsers, `ocamllex`\-generated lexers, `ocamlyacc`\-generated parsers. - -### Scanning indications in format strings - -Scanning indications appear just after the string conversions `%s` and `%[ range ]` to delimit the end of the token. A scanning indication is introduced by a `@` character, followed by some plain character `c`. It means that the string token should end just before the next matching `c` (which is skipped). If no `c` character is encountered, the string token spreads as much as possible. For instance, `"%s@\t"` reads a string up to the next tab character or to the end of input. If a `@` character appears anywhere else in the format string, it is treated as a plain character. - -Note: - -- As usual in format strings, `%` and `@` characters must be escaped using `%%` and `%@`; this rule still holds within range specifications and scanning indications. For instance, format `"%s@%%"` reads a string up to the next `%` character, and format `"%s@%@"` reads a string up to the next `@`. -- The scanning indications introduce slight differences in the syntax of [`Scanf`](#) format strings, compared to those used for the [`Printf`](./Stdlib-Printf.md) module. However, the scanning indications are similar to those used in the [`Format`](./Stdlib-Format.md) module; hence, when producing formatted text to be scanned by [`Scanf.bscanf`](./#val-bscanf), it is wise to use printing functions from the [`Format`](./Stdlib-Format.md) module (or, if you need to use functions from [`Printf`](./Stdlib-Printf.md), banish or carefully double check the format strings that contain `'@'` characters). - -### Exceptions during scanning - -Scanners may raise the following exceptions when the input cannot be read according to the format string: - -- Raise [`Scanf.Scan_failure`](./#exception-Scan_failure) if the input does not match the format. -- Raise `Failure` if a conversion to a number is not possible. -- Raise `End_of_file` if the end of input is encountered while some more characters are needed to read the current conversion specification. -- Raise `Invalid_argument` if the format string is invalid. -Note: - -- as a consequence, scanning a `%s` conversion never raises exception `End_of_file`: if the end of input is reached the conversion succeeds and simply returns the characters read so far, or `""` if none were ever read. - -## Specialised formatted input functions - -``` -val sscanf : string -> ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the given string. - -``` -val sscanf_opt : string -> ('a, 'b, 'c, 'd) scanner_opt -``` -Same as [`Scanf.sscanf`](./#val-sscanf), but returns `None` in case of scanning failure. - -since 5.0 -``` -val scanf : ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but reads from the predefined formatted input channel [`Scanf.Scanning.stdin`](./Stdlib-Scanf-Scanning.md#val-stdin) that is connected to [`Stdlib.stdin`](./Stdlib.md#val-stdin). - -``` -val scanf_opt : ('a, 'b, 'c, 'd) scanner_opt -``` -Same as [`Scanf.scanf`](./#val-scanf), but returns `None` in case of scanning failure. - -since 5.0 -``` -val kscanf : - Scanning.in_channel -> - (Scanning.in_channel -> exn -> 'd) -> - ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.bscanf`](./#val-bscanf), but takes an additional function argument `ef` that is called in case of error: if the scanning process or some conversion fails, the scanning function aborts and calls the error handling function `ef` with the formatted input channel and the exception that aborted the scanning process as arguments. - -``` -val ksscanf : - string -> - (Scanning.in_channel -> exn -> 'd) -> - ('a, 'b, 'c, 'd) scanner -``` -Same as [`Scanf.kscanf`](./#val-kscanf) but reads from the given string. - -since 4.02 - -## Reading format strings from input - -``` -val bscanf_format : - Scanning.in_channel -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> - 'g -``` -`bscanf_format ic fmt f` reads a format string token from the formatted input channel `ic`, according to the given format string `fmt`, and applies `f` to the resulting format string value. - -raises [`Scan_failure`](./#exception-Scan_failure) if the format string value read does not have the same type as fmt. -since 3.09 -``` -val sscanf_format : - string -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - (('a, 'b, 'c, 'd, 'e, 'f) format6 -> 'g) -> - 'g -``` -Same as [`Scanf.bscanf_format`](./#val-bscanf_format), but reads from the given string. - -since 3.09 -``` -val format_from_string : - string -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -``` -`format_from_string s fmt` converts a string argument to a format string, according to the given format string `fmt`. - -raises [`Scan_failure`](./#exception-Scan_failure) if s, considered as a format string, does not have the same type as fmt. -since 3.10 -``` -val unescaped : string -> string -``` -`unescaped s` return a copy of `s` with escape sequences (according to the lexical conventions of OCaml) replaced by their corresponding special characters. More precisely, `Scanf.unescaped` has the following property: for all string `s`, `Scanf.unescaped (String.escaped s) = s`. - -Always return a copy of the argument, even if there is no escape sequence in the argument. - -raises [`Scan_failure`](./#exception-Scan_failure) if s is not properly escaped (i.e. s has invalid escape sequences or special characters that are not properly escaped). For instance, Scanf.unescaped "\\"" will fail. -since 4.00 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Seq.md b/docs/api/re/melange/Stdlib-Seq.md deleted file mode 100644 index fae489474..000000000 --- a/docs/api/re/melange/Stdlib-Seq.md +++ /dev/null @@ -1,624 +0,0 @@ - -# Module `Stdlib.Seq` - -Sequences. - -A sequence of type `'a Seq.t` can be thought of as a **delayed list**, that is, a list whose elements are computed only when they are demanded by a consumer. This allows sequences to be produced and transformed lazily (one element at a time) rather than eagerly (all elements at once). This also allows constructing conceptually infinite sequences. - -The type `'a Seq.t` is defined as a synonym for `unit -> 'a Seq.node`. This is a function type: therefore, it is opaque. The consumer can **query** a sequence in order to request the next element (if there is one), but cannot otherwise inspect the sequence in any way. - -Because it is opaque, the type `'a Seq.t` does *not* reveal whether a sequence is: - -- **persistent**, which means that the sequence can be used as many times as desired, producing the same elements every time, just like an immutable list; or -- **ephemeral**, which means that the sequence is not persistent. Querying an ephemeral sequence might have an observable side effect, such as incrementing a mutable counter. As a common special case, an ephemeral sequence can be **affine**, which means that it must be queried at most once. -It also does *not* reveal whether the elements of the sequence are: - -- **pre-computed and stored** in memory, which means that querying the sequence is cheap; -- **computed when first demanded and then stored** in memory, which means that querying the sequence once can be expensive, but querying the same sequence again is cheap; or -- **re-computed every time they are demanded**, which may or may not be cheap. -It is up to the programmer to keep these distinctions in mind so as to understand the time and space requirements of sequences. - -For the sake of simplicity, most of the documentation that follows is written under the implicit assumption that the sequences at hand are persistent. We normally do not point out *when* or *how many times* each function is invoked, because that would be too verbose. For instance, in the description of `map`, we write: "if `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`". If we wished to be more explicit, we could point out that the transformation takes place on demand: that is, the elements of `map f xs` are computed only when they are demanded. In other words, the definition `let ys = map f xs` terminates immediately and does not invoke `f`. The function call `f x0` takes place only when the first element of `ys` is demanded, via the function call `ys()`. Furthermore, calling `ys()` twice causes `f x0` to be called twice as well. If one wishes for `f` to be applied at most once to each element of `xs`, even in scenarios where `ys` is queried more than once, then one should use `let ys = memoize (map f xs)`. - -As a general rule, the functions that build sequences, such as `map`, `filter`, `scan`, `take`, etc., produce sequences whose elements are computed only on demand. The functions that eagerly consume sequences, such as `is_empty`, `find`, `length`, `iter`, `fold_left`, etc., are the functions that force computation to take place. - -When possible, we recommend using sequences rather than dispensers (functions of type `unit -> 'a option` that produce elements upon demand). Whereas sequences can be persistent or ephemeral, dispensers are always ephemeral, and are typically more difficult to work with than sequences. Two conversion functions, [`to_dispenser`](./#val-to_dispenser) and [`of_dispenser`](./#val-of_dispenser), are provided. - -since 4.07 -``` -type 'a t = unit -> 'a node -``` -A sequence `xs` of type `'a t` is a delayed list of elements of type `'a`. Such a sequence is queried by performing a function application `xs()`. This function application returns a node, allowing the caller to determine whether the sequence is empty or nonempty, and in the latter case, to obtain its head and tail. - -``` -and +'a node = -``` -``` -| Nil -``` -``` -| Cons of 'a * 'a t -``` -``` - -``` -A node is either `Nil`, which means that the sequence is empty, or `Cons (x, xs)`, which means that `x` is the first element of the sequence and that `xs` is the remainder of the sequence. - - -## Consuming sequences - -The functions in this section consume their argument, a sequence, either partially or completely: - -- `is_empty` and `uncons` consume the sequence down to depth 1\. That is, they demand the first argument of the sequence, if there is one. -- `iter`, `fold_left`, `length`, etc., consume the sequence all the way to its end. They terminate only if the sequence is finite. -- `for_all`, `exists`, `find`, etc. consume the sequence down to a certain depth, which is a priori unpredictable. -Similarly, among the functions that consume two sequences, one can distinguish two groups: - -- `iter2` and `fold_left2` consume both sequences all the way to the end, provided the sequences have the same length. -- `for_all2`, `exists2`, `equal`, `compare` consume the sequences down to a certain depth, which is a priori unpredictable. -The functions that consume two sequences can be applied to two sequences of distinct lengths: in that case, the excess elements in the longer sequence are ignored. (It may be the case that one excess element is demanded, even though this element is not used.) - -None of the functions in this section is lazy. These functions are consumers: they force some computation to take place. - -``` -val is_empty : 'a t -> bool -``` -`is_empty xs` determines whether the sequence `xs` is empty. - -It is recommended that the sequence `xs` be persistent. Indeed, `is_empty xs` demands the head of the sequence `xs`, so, if `xs` is ephemeral, it may be the case that `xs` cannot be used any more after this call has taken place. - -since 4.14 -``` -val uncons : 'a t -> ('a * 'a t) option -``` -If `xs` is empty, then `uncons xs` is `None`. - -If `xs` is nonempty, then `uncons xs` is `Some (x, ys)` where `x` is the head of the sequence and `ys` its tail. - -since 4.14 -``` -val length : 'a t -> int -``` -`length xs` is the length of the sequence `xs`. - -The sequence `xs` must be finite. - -since 4.14 -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f xs` invokes `f x` successively for every element `x` of the sequence `xs`, from left to right. - -It terminates only if the sequence `xs` is finite. - -``` -val fold_left : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold_left f _ xs` invokes `f _ x` successively for every element `x` of the sequence `xs`, from left to right. - -An accumulator of type `'a` is threaded through the calls to `f`. - -It terminates only if the sequence `xs` is finite. - -``` -val iteri : (int -> 'a -> unit) -> 'a t -> unit -``` -`iteri f xs` invokes `f i x` successively for every element `x` located at index `i` in the sequence `xs`. - -It terminates only if the sequence `xs` is finite. - -`iteri f xs` is equivalent to `iter (fun (i, x) -> f i x) (zip (ints 0) xs)`. - -since 4.14 -``` -val fold_lefti : ('acc -> int -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold_lefti f _ xs` invokes `f _ i x` successively for every element `x` located at index `i` of the sequence `xs`. - -An accumulator of type `'b` is threaded through the calls to `f`. - -It terminates only if the sequence `xs` is finite. - -`fold_lefti f accu xs` is equivalent to `fold_left (fun accu (i, x) -> f accu i x) accu (zip (ints 0) xs)`. - -since 4.14 -``` -val for_all : ('a -> bool) -> 'a t -> bool -``` -`for_all p xs` determines whether all elements `x` of the sequence `xs` satisfy `p x`. - -The sequence `xs` must be finite. - -since 4.14 -``` -val exists : ('a -> bool) -> 'a t -> bool -``` -`exists xs p` determines whether at least one element `x` of the sequence `xs` satisfies `p x`. - -The sequence `xs` must be finite. - -since 4.14 -``` -val find : ('a -> bool) -> 'a t -> 'a option -``` -`find p xs` returns `Some x`, where `x` is the first element of the sequence `xs` that satisfies `p x`, if there is such an element. - -It returns `None` if there is no such element. - -The sequence `xs` must be finite. - -since 4.14 -``` -val find_index : ('a -> bool) -> 'a t -> int option -``` -`find_index p xs` returns `Some i`, where `i` is the index of the first element of the sequence `xs` that satisfies `p x`, if there is such an element. - -It returns `None` if there is no such element. - -The sequence `xs` must be finite. - -since 5.1 -``` -val find_map : ('a -> 'b option) -> 'a t -> 'b option -``` -`find_map f xs` returns `Some y`, where `x` is the first element of the sequence `xs` such that `f x = Some _`, if there is such an element, and where `y` is defined by `f x = Some y`. - -It returns `None` if there is no such element. - -The sequence `xs` must be finite. - -since 4.14 -``` -val find_mapi : (int -> 'a -> 'b option) -> 'a t -> 'b option -``` -Same as `find_map`, but the predicate is applied to the index of the element as first argument (counting from 0), and the element itself as second argument. - -The sequence `xs` must be finite. - -since 5.1 -``` -val iter2 : ('a -> 'b -> unit) -> 'a t -> 'b t -> unit -``` -`iter2 f xs ys` invokes `f x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. - -If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. - -`iter2 f xs ys` is equivalent to `iter (fun (x, y) -> f x y) (zip xs ys)`. - -since 4.14 -``` -val fold_left2 : ('acc -> 'a -> 'b -> 'acc) -> 'acc -> 'a t -> 'b t -> 'acc -``` -`fold_left2 f _ xs ys` invokes `f _ x y` successively for every pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys`. - -An accumulator of type `'a` is threaded through the calls to `f`. - -If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -Iteration terminates only if at least one of the sequences `xs` and `ys` is finite. - -`fold_left2 f accu xs ys` is equivalent to `fold_left (fun accu (x, y) -> f accu x y) (zip xs ys)`. - -since 4.14 -``` -val for_all2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool -``` -`for_all2 p xs ys` determines whether all pairs `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfy `p x y`. - -If the sequences `xs` and `ys` have different lengths, then iteration stops as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. In particular, if `xs` or `ys` is empty, then `for_all2 p xs ys` is true. This is where `for_all2` and `equal` differ: `equal eq xs ys` can be true only if `xs` and `ys` have the same length. - -At least one of the sequences `xs` and `ys` must be finite. - -`for_all2 p xs ys` is equivalent to `for_all (fun b -> b) (map2 p xs ys)`. - -since 4.14 -``` -val exists2 : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool -``` -`exists2 p xs ys` determines whether some pair `(x, y)` of elements drawn synchronously from the sequences `xs` and `ys` satisfies `p x y`. - -If the sequences `xs` and `ys` have different lengths, then iteration must stop as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -At least one of the sequences `xs` and `ys` must be finite. - -`exists2 p xs ys` is equivalent to `exists (fun b -> b) (map2 p xs ys)`. - -since 4.14 -``` -val equal : ('a -> 'b -> bool) -> 'a t -> 'b t -> bool -``` -Provided the function `eq` defines an equality on elements, `equal eq xs ys` determines whether the sequences `xs` and `ys` are pointwise equal. - -At least one of the sequences `xs` and `ys` must be finite. - -since 4.14 -``` -val compare : ('a -> 'b -> int) -> 'a t -> 'b t -> int -``` -Provided the function `cmp` defines a preorder on elements, `compare cmp xs ys` compares the sequences `xs` and `ys` according to the lexicographic preorder. - -For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). - -At least one of the sequences `xs` and `ys` must be finite. - -since 4.14 - -## Constructing sequences - -The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. - -``` -val empty : 'a t -``` -`empty` is the empty sequence. It has no elements. Its length is 0. - -``` -val return : 'a -> 'a t -``` -`return x` is the sequence whose sole element is `x`. Its length is 1\. - -``` -val cons : 'a -> 'a t -> 'a t -``` -`cons x xs` is the sequence that begins with the element `x`, followed with the sequence `xs`. - -Writing `cons (f()) xs` causes the function call `f()` to take place immediately. For this call to be delayed until the sequence is queried, one must instead write `(fun () -> Cons(f(), xs))`. - -since 4.11 -``` -val init : int -> (int -> 'a) -> 'a t -``` -`init n f` is the sequence `f 0; f 1; ...; f (n-1)`. - -`n` must be nonnegative. - -If desired, the infinite sequence `f 0; f 1; ...` can be defined as `map f (ints 0)`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.14 -``` -val unfold : ('b -> ('a * 'b) option) -> 'b -> 'a t -``` -`unfold` constructs a sequence out of a step function and an initial state. - -If `f u` is `None` then `unfold f u` is the empty sequence. If `f u` is `Some (x, u')` then `unfold f u` is the nonempty sequence `cons x (unfold f u')`. - -For example, `unfold (function [] -> None | h :: t -> Some (h, t)) l` is equivalent to `List.to_seq l`. - -since 4.11 -``` -val repeat : 'a -> 'a t -``` -`repeat x` is the infinite sequence where the element `x` is repeated indefinitely. - -`repeat x` is equivalent to `cycle (return x)`. - -since 4.14 -``` -val forever : (unit -> 'a) -> 'a t -``` -`forever f` is an infinite sequence where every element is produced (on demand) by the function call `f()`. - -For instance, `forever Random.bool` is an infinite sequence of random bits. - -`forever f` is equivalent to `map f (repeat ())`. - -since 4.14 -``` -val cycle : 'a t -> 'a t -``` -`cycle xs` is the infinite sequence that consists of an infinite number of repetitions of the sequence `xs`. - -If `xs` is an empty sequence, then `cycle xs` is empty as well. - -Consuming (a prefix of) the sequence `cycle xs` once can cause the sequence `xs` to be consumed more than once. Therefore, `xs` must be persistent. - -since 4.14 -``` -val iterate : ('a -> 'a) -> 'a -> 'a t -``` -`iterate f x` is the infinite sequence whose elements are `x`, `f x`, `f (f x)`, and so on. - -In other words, it is the orbit of the function `f`, starting at `x`. - -since 4.14 - -## Transforming sequences - -The functions in this section are lazy: that is, they return sequences whose elements are computed only when demanded. - -``` -val map : ('a -> 'b) -> 'a t -> 'b t -``` -`map f xs` is the image of the sequence `xs` through the transformation `f`. - -If `xs` is the sequence `x0; x1; ...` then `map f xs` is the sequence `f x0; f x1; ...`. - -``` -val mapi : (int -> 'a -> 'b) -> 'a t -> 'b t -``` -`mapi` is analogous to `map`, but applies the function `f` to an index and an element. - -`mapi f xs` is equivalent to `map2 f (ints 0) xs`. - -since 4.14 -``` -val filter : ('a -> bool) -> 'a t -> 'a t -``` -`filter p xs` is the sequence of the elements `x` of `xs` that satisfy `p x`. - -In other words, `filter p xs` is the sequence `xs`, deprived of the elements `x` such that `p x` is false. - -``` -val filter_map : ('a -> 'b option) -> 'a t -> 'b t -``` -`filter_map f xs` is the sequence of the elements `y` such that `f x = Some y`, where `x` ranges over `xs`. - -`filter_map f xs` is equivalent to `map Option.get (filter Option.is_some (map f xs))`. - -``` -val scan : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b t -``` -If `xs` is a sequence `[x0; x1; x2; ...]`, then `scan f a0 xs` is a sequence of accumulators `[a0; a1; a2; ...]` where `a1` is `f a0 x0`, `a2` is `f a1 x1`, and so on. - -Thus, `scan f a0 xs` is conceptually related to `fold_left f a0 xs`. However, instead of performing an eager iteration and immediately returning the final accumulator, it returns a sequence of accumulators. - -For instance, `scan (+) 0` transforms a sequence of integers into the sequence of its partial sums. - -If `xs` has length `n` then `scan f a0 xs` has length `n+1`. - -since 4.14 -``` -val take : int -> 'a t -> 'a t -``` -`take n xs` is the sequence of the first `n` elements of `xs`. - -If `xs` has fewer than `n` elements, then `take n xs` is equivalent to `xs`. - -`n` must be nonnegative. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.14 -``` -val drop : int -> 'a t -> 'a t -``` -`drop n xs` is the sequence `xs`, deprived of its first `n` elements. - -If `xs` has fewer than `n` elements, then `drop n xs` is empty. - -`n` must be nonnegative. - -`drop` is lazy: the first `n+1` elements of the sequence `xs` are demanded only when the first element of `drop n xs` is demanded. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is negative. -since 4.14 -``` -val take_while : ('a -> bool) -> 'a t -> 'a t -``` -`take_while p xs` is the longest prefix of the sequence `xs` where every element `x` satisfies `p x`. - -since 4.14 -``` -val drop_while : ('a -> bool) -> 'a t -> 'a t -``` -`drop_while p xs` is the sequence `xs`, deprived of the prefix `take_while p xs`. - -since 4.14 -``` -val group : ('a -> 'a -> bool) -> 'a t -> 'a t t -``` -Provided the function `eq` defines an equality on elements, `group eq xs` is the sequence of the maximal runs of adjacent duplicate elements of the sequence `xs`. - -Every element of `group eq xs` is a nonempty sequence of equal elements. - -The concatenation `concat (group eq xs)` is equal to `xs`. - -Consuming `group eq xs`, and consuming the sequences that it contains, can cause `xs` to be consumed more than once. Therefore, `xs` must be persistent. - -since 4.14 -``` -val memoize : 'a t -> 'a t -``` -The sequence `memoize xs` has the same elements as the sequence `xs`. - -Regardless of whether `xs` is ephemeral or persistent, `memoize xs` is persistent: even if it is queried several times, `xs` is queried at most once. - -The construction of the sequence `memoize xs` internally relies on suspensions provided by the module [`Lazy`](./Stdlib-Lazy.md). These suspensions are *not* thread-safe. Therefore, the sequence `memoize xs` must *not* be queried by multiple threads concurrently. - -since 4.14 -``` -exception Forced_twice -``` -This exception is raised when a sequence returned by [`once`](./#val-once) (or a suffix of it) is queried more than once. - -since 4.14 -``` -val once : 'a t -> 'a t -``` -The sequence `once xs` has the same elements as the sequence `xs`. - -Regardless of whether `xs` is ephemeral or persistent, `once xs` is an ephemeral sequence: it can be queried at most once. If it (or a suffix of it) is queried more than once, then the exception `Forced_twice` is raised. This can be useful, while debugging or testing, to ensure that a sequence is consumed at most once. - -raises [`Forced_twice`](./#exception-Forced_twice) if once xs, or a suffix of it, is queried more than once. -since 4.14 -``` -val transpose : 'a t t -> 'a t t -``` -If `xss` is a matrix (a sequence of rows), then `transpose xss` is the sequence of the columns of the matrix `xss`. - -The rows of the matrix `xss` are not required to have the same length. - -The matrix `xss` is not required to be finite (in either direction). - -The matrix `xss` must be persistent. - -since 4.14 - -## Combining sequences - -``` -val append : 'a t -> 'a t -> 'a t -``` -`append xs ys` is the concatenation of the sequences `xs` and `ys`. - -Its elements are the elements of `xs`, followed by the elements of `ys`. - -since 4.11 -``` -val concat : 'a t t -> 'a t -``` -If `xss` is a sequence of sequences, then `concat xss` is its concatenation. - -If `xss` is the sequence `xs0; xs1; ...` then `concat xss` is the sequence `xs0 @ xs1 @ ...`. - -since 4.13 -``` -val flat_map : ('a -> 'b t) -> 'a t -> 'b t -``` -`flat_map f xs` is equivalent to `concat (map f xs)`. - -``` -val concat_map : ('a -> 'b t) -> 'a t -> 'b t -``` -`concat_map f xs` is equivalent to `concat (map f xs)`. - -`concat_map` is an alias for `flat_map`. - -since 4.13 -``` -val zip : 'a t -> 'b t -> ('a * 'b) t -``` -`zip xs ys` is the sequence of pairs `(x, y)` drawn synchronously from the sequences `xs` and `ys`. - -If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -`zip xs ys` is equivalent to `map2 (fun a b -> (a, b)) xs ys`. - -since 4.14 -``` -val map2 : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t -``` -`map2 f xs ys` is the sequence of the elements `f x y`, where the pairs `(x, y)` are drawn synchronously from the sequences `xs` and `ys`. - -If the sequences `xs` and `ys` have different lengths, then the sequence ends as soon as one sequence is exhausted; the excess elements in the other sequence are ignored. - -`map2 f xs ys` is equivalent to `map (fun (x, y) -> f x y) (zip xs ys)`. - -since 4.14 -``` -val interleave : 'a t -> 'a t -> 'a t -``` -`interleave xs ys` is the sequence that begins with the first element of `xs`, continues with the first element of `ys`, and so on. - -When one of the sequences `xs` and `ys` is exhausted, `interleave xs ys` continues with the rest of the other sequence. - -since 4.14 -``` -val sorted_merge : ('a -> 'a -> int) -> 'a t -> 'a t -> 'a t -``` -If the sequences `xs` and `ys` are sorted according to the total preorder `cmp`, then `sorted_merge cmp xs ys` is the sorted sequence obtained by merging the sequences `xs` and `ys`. - -For more details on comparison functions, see [`Array.sort`](./Stdlib-Array.md#val-sort). - -since 4.14 -``` -val product : 'a t -> 'b t -> ('a * 'b) t -``` -`product xs ys` is the Cartesian product of the sequences `xs` and `ys`. - -For every element `x` of `xs` and for every element `y` of `ys`, the pair `(x, y)` appears once as an element of `product xs ys`. - -The order in which the pairs appear is unspecified. - -The sequences `xs` and `ys` are not required to be finite. - -The sequences `xs` and `ys` must be persistent. - -since 4.14 -``` -val map_product : ('a -> 'b -> 'c) -> 'a t -> 'b t -> 'c t -``` -The sequence `map_product f xs ys` is the image through `f` of the Cartesian product of the sequences `xs` and `ys`. - -For every element `x` of `xs` and for every element `y` of `ys`, the element `f x y` appears once as an element of `map_product f xs ys`. - -The order in which these elements appear is unspecified. - -The sequences `xs` and `ys` are not required to be finite. - -The sequences `xs` and `ys` must be persistent. - -`map_product f xs ys` is equivalent to `map (fun (x, y) -> f x y) (product xs ys)`. - -since 4.14 - -## Splitting a sequence into two sequences - -``` -val unzip : ('a * 'b) t -> 'a t * 'b t -``` -`unzip` transforms a sequence of pairs into a pair of sequences. - -`unzip xs` is equivalent to `(map fst xs, map snd xs)`. - -Querying either of the sequences returned by `unzip xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `unzip (memoize xs)`. - -since 4.14 -``` -val split : ('a * 'b) t -> 'a t * 'b t -``` -`split` is an alias for `unzip`. - -since 4.14 -``` -val partition_map : ('a -> ('b, 'c) Either.t) -> 'a t -> 'b t * 'c t -``` -`partition_map f xs` returns a pair of sequences `(ys, zs)`, where: - -- `ys` is the sequence of the elements `y` such that `f x = Left y`, where `x` ranges over `xs`; -- `zs` is the sequence of the elements `z` such that `f x = Right z`, where `x` ranges over `xs`. -`partition_map f xs` is equivalent to a pair of `filter_map Either.find_left (map f xs)` and `filter_map Either.find_right (map f xs)`. - -Querying either of the sequences returned by `partition_map f xs` causes `xs` to be queried. Therefore, querying both of them causes `xs` to be queried twice. Thus, `xs` must be persistent and cheap. If that is not the case, use `partition_map f (memoize xs)`. - -since 4.14 -``` -val partition : ('a -> bool) -> 'a t -> 'a t * 'a t -``` -`partition p xs` returns a pair of the subsequence of the elements of `xs` that satisfy `p` and the subsequence of the elements of `xs` that do not satisfy `p`. - -`partition p xs` is equivalent to `filter p xs, filter (fun x -> not (p x)) xs`. - -Consuming both of the sequences returned by `partition p xs` causes `xs` to be consumed twice and causes the function `f` to be applied twice to each element of the list. Therefore, `f` should be pure and cheap. Furthermore, `xs` should be persistent and cheap. If that is not the case, use `partition p (memoize xs)`. - -since 4.14 - -## Converting between sequences and dispensers - -A dispenser is a representation of a sequence as a function of type `unit -> 'a option`. Every time this function is invoked, it returns the next element of the sequence. When there are no more elements, it returns `None`. A dispenser has mutable internal state, therefore is ephemeral: the sequence that it represents can be consumed at most once. - -``` -val of_dispenser : (unit -> 'a option) -> 'a t -``` -`of_dispenser it` is the sequence of the elements produced by the dispenser `it`. It is an ephemeral sequence: it can be consumed at most once. If a persistent sequence is needed, use `memoize (of_dispenser it)`. - -since 4.14 -``` -val to_dispenser : 'a t -> unit -> 'a option -``` -`to_dispenser xs` is a fresh dispenser on the sequence `xs`. - -This dispenser has mutable internal state, which is not protected by a lock; so, it must not be used by several threads concurrently. - -since 4.14 - -## Sequences of integers - -``` -val ints : int -> int t -``` -`ints i` is the infinite sequence of the integers beginning at `i` and counting up. - -since 4.14 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md b/docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md deleted file mode 100644 index 3abdead73..000000000 --- a/docs/api/re/melange/Stdlib-Set-Make-argument-1-Ord.md +++ /dev/null @@ -1,12 +0,0 @@ - -# Parameter `Make.Ord` - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Set-Make.md b/docs/api/re/melange/Stdlib-Set-Make.md deleted file mode 100644 index 93d2962e8..000000000 --- a/docs/api/re/melange/Stdlib-Set-Make.md +++ /dev/null @@ -1,297 +0,0 @@ - -# Module `Set.Make` - -Functor building an implementation of the set structure given a totally ordered type. - - -## Parameters - -``` -module Ord : OrderedType -``` - -## Signature - - -## Sets - -``` -type elt = Ord.t -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](#). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : (elt -> bool) -> t -> elt -``` -`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : (elt -> bool) -> t -> elt option -``` -`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : (elt -> bool) -> t -> elt -``` -`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : (elt -> bool) -> t -> elt option -``` -`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : (elt -> unit) -> t -> unit -``` -`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : (elt -> elt) -> t -> t -``` -`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : (elt -> bool) -> t -> t -``` -`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : (elt -> elt option) -> t -> t -``` -`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : (elt -> bool) -> t -> t * t -``` -`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : (elt -> bool) -> t -> bool -``` -`for_all f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : (elt -> bool) -> t -> bool -``` -`exists f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md b/docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md deleted file mode 100644 index 11f9d9c0d..000000000 --- a/docs/api/re/melange/Stdlib-Set-module-type-OrderedType.md +++ /dev/null @@ -1,14 +0,0 @@ - -# Module type `Set.OrderedType` - -Input signature of the functor [`Make`](./Stdlib-Set-Make.md). - -``` -type t -``` -The type of the set elements. - -``` -val compare : t -> t -> int -``` -A total ordering function over the set elements. This is a two-argument function `f` such that `f e1 e2` is zero if the elements `e1` and `e2` are equal, `f e1 e2` is strictly negative if `e1` is smaller than `e2`, and `f e1 e2` is strictly positive if `e1` is greater than `e2`. Example: a suitable ordering function is the generic structural comparison function [`Stdlib.compare`](./Stdlib.md#val-compare). diff --git a/docs/api/re/melange/Stdlib-Set-module-type-S.md b/docs/api/re/melange/Stdlib-Set-module-type-S.md deleted file mode 100644 index 72db61d6a..000000000 --- a/docs/api/re/melange/Stdlib-Set-module-type-S.md +++ /dev/null @@ -1,288 +0,0 @@ - -# Module type `Set.S` - -Output signature of the functor [`Make`](./Stdlib-Set-Make.md). - - -## Sets - -``` -type elt -``` -The type of the set elements. - -``` -type t -``` -The type of sets. - -``` -val empty : t -``` -The empty set. - -``` -val add : elt -> t -> t -``` -`add x s` returns a set containing all elements of `s`, plus `x`. If `x` was already in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val singleton : elt -> t -``` -`singleton x` returns the one-element set containing only `x`. - -``` -val remove : elt -> t -> t -``` -`remove x s` returns a set containing all elements of `s`, except `x`. If `x` was not in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val union : t -> t -> t -``` -Set union. - -``` -val inter : t -> t -> t -``` -Set intersection. - -``` -val disjoint : t -> t -> bool -``` -Test if two sets are disjoint. - -since 4.08 -``` -val diff : t -> t -> t -``` -Set difference: `diff s1 s2` contains the elements of `s1` that are not in `s2`. - -``` -val cardinal : t -> int -``` -Return the number of elements of a set. - - -## Elements - -``` -val elements : t -> elt list -``` -Return the list of all elements of the given set. The returned list is sorted in increasing order with respect to the ordering `Ord.compare`, where `Ord` is the argument given to [`Set.Make`](./Stdlib-Set-Make.md). - -``` -val min_elt : t -> elt -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or raise `Not_found` if the set is empty. - -``` -val min_elt_opt : t -> elt option -``` -Return the smallest element of the given set (with respect to the `Ord.compare` ordering), or `None` if the set is empty. - -since 4.05 -``` -val max_elt : t -> elt -``` -Same as [`min_elt`](./#val-min_elt), but returns the largest element of the given set. - -``` -val max_elt_opt : t -> elt option -``` -Same as [`min_elt_opt`](./#val-min_elt_opt), but returns the largest element of the given set. - -since 4.05 -``` -val choose : t -> elt -``` -Return one element of the given set, or raise `Not_found` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -``` -val choose_opt : t -> elt option -``` -Return one element of the given set, or `None` if the set is empty. Which element is chosen is unspecified, but equal elements will be chosen for equal sets. - -since 4.05 - -## Searching - -``` -val find : elt -> t -> elt -``` -`find x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or raise `Not_found` if no such element exists. - -since 4.01 -``` -val find_opt : elt -> t -> elt option -``` -`find_opt x s` returns the element of `s` equal to `x` (according to `Ord.compare`), or `None` if no such element exists. - -since 4.05 -``` -val find_first : (elt -> bool) -> t -> elt -``` -`find_first f s`, where `f` is a monotonically increasing function, returns the lowest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -For example, `find_first (fun e -> Ord.compare e x >= 0) s` will return the first element `e` of `s` where `Ord.compare e x >= 0` (intuitively: `e >= x`), or raise `Not_found` if `x` is greater than any element of `s`. - -since 4.05 -``` -val find_first_opt : (elt -> bool) -> t -> elt option -``` -`find_first_opt f s`, where `f` is a monotonically increasing function, returns an option containing the lowest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 -``` -val find_last : (elt -> bool) -> t -> elt -``` -`find_last f s`, where `f` is a monotonically decreasing function, returns the highest element `e` of `s` such that `f e`, or raises `Not_found` if no such element exists. - -since 4.05 -``` -val find_last_opt : (elt -> bool) -> t -> elt option -``` -`find_last_opt f s`, where `f` is a monotonically decreasing function, returns an option containing the highest element `e` of `s` such that `f e`, or `None` if no such element exists. - -since 4.05 - -## Traversing - -``` -val iter : (elt -> unit) -> t -> unit -``` -`iter f s` applies `f` in turn to all elements of `s`. The elements of `s` are presented to `f` in increasing order with respect to the ordering over the type of the elements. - -``` -val fold : (elt -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f s init` computes `(f xN ... (f x2 (f x1 init))...)`, where `x1 ... xN` are the elements of `s`, in increasing order. - - -## Transforming - -``` -val map : (elt -> elt) -> t -> t -``` -`map f s` is the set whose elements are `f a0`,`f a1`... `f aN`, where `a0`,`a1`...`aN` are the elements of `s`. - -The elements are passed to `f` in increasing order with respect to the ordering over the type of the elements. - -If no element of `s` is changed by `f`, `s` is returned unchanged. (If each output of `f` is physically equal to its input, the returned set is physically equal to `s`.) - -since 4.04 -``` -val filter : (elt -> bool) -> t -> t -``` -`filter f s` returns the set of all elements in `s` that satisfy predicate `f`. If `f` satisfies every element in `s`, `s` is returned unchanged (the result of the function is then physically equal to `s`). - -before 4.03 Physical equality was not ensured. -``` -val filter_map : (elt -> elt option) -> t -> t -``` -`filter_map f s` returns the set of all `v` such that `f x = Some v` for some element `x` of `s`. - -For example, - -```ocaml -filter_map (fun n -> if n mod 2 = 0 then Some (n / 2) else None) s -``` -is the set of halves of the even elements of `s`. - -If no element of `s` is changed or dropped by `f` (if `f x = Some x` for each element `x`), then `s` is returned unchanged: the result of the function is then physically equal to `s`. - -since 4.11 -``` -val partition : (elt -> bool) -> t -> t * t -``` -`partition f s` returns a pair of sets `(s1, s2)`, where `s1` is the set of all the elements of `s` that satisfy the predicate `f`, and `s2` is the set of all the elements of `s` that do not satisfy `f`. - -``` -val split : elt -> t -> t * bool * t -``` -`split x s` returns a triple `(l, present, r)`, where `l` is the set of elements of `s` that are strictly less than `x`; `r` is the set of elements of `s` that are strictly greater than `x`; `present` is `false` if `s` contains no element equal to `x`, or `true` if `s` contains an element equal to `x`. - - -## Predicates and comparisons - -``` -val is_empty : t -> bool -``` -Test whether a set is empty or not. - -``` -val mem : elt -> t -> bool -``` -`mem x s` tests whether `x` belongs to the set `s`. - -``` -val equal : t -> t -> bool -``` -`equal s1 s2` tests whether the sets `s1` and `s2` are equal, that is, contain equal elements. - -``` -val compare : t -> t -> int -``` -Total ordering between sets. Can be used as the ordering function for doing sets of sets. - -``` -val subset : t -> t -> bool -``` -`subset s1 s2` tests whether the set `s1` is a subset of the set `s2`. - -``` -val for_all : (elt -> bool) -> t -> bool -``` -`for_all f s` checks if all elements of the set satisfy the predicate `f`. - -``` -val exists : (elt -> bool) -> t -> bool -``` -`exists f s` checks if at least one element of the set satisfies the predicate `f`. - - -## Converting - -``` -val to_list : t -> elt list -``` -`to_list s` is [`elements`](./#val-elements)` s`. - -since 5.1 -``` -val of_list : elt list -> t -``` -`of_list l` creates a set from a list of elements. This is usually more efficient than folding `add` over the list, except perhaps for lists with many duplicated elements. - -since 4.02 -``` -val to_seq_from : elt -> t -> elt Seq.t -``` -`to_seq_from x s` iterates on a subset of the elements of `s` in ascending order, from `x` or above. - -since 4.07 -``` -val to_seq : t -> elt Seq.t -``` -Iterate on the whole set, in ascending order - -since 4.07 -``` -val to_rev_seq : t -> elt Seq.t -``` -Iterate on the whole set, in descending order - -since 4.12 -``` -val add_seq : elt Seq.t -> t -> t -``` -Add the given elements to the set, in order. - -since 4.07 -``` -val of_seq : elt Seq.t -> t -``` -Build a set from the given bindings - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Set.md b/docs/api/re/melange/Stdlib-Set.md deleted file mode 100644 index f961f9b00..000000000 --- a/docs/api/re/melange/Stdlib-Set.md +++ /dev/null @@ -1,39 +0,0 @@ - -# Module `Stdlib.Set` - -Sets over ordered types. - -This module implements the set data structure, given a total ordering function over the set elements. All operations over sets are purely applicative (no side-effects). The implementation uses balanced binary trees, and is therefore reasonably efficient: insertion and membership take time logarithmic in the size of the set, for instance. - -The [`Make`](./Stdlib-Set-Make.md) functor constructs implementations for any type, given a `compare` function. For instance: - -```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 PairsSet = Set.Make(IntPairs) - - let m = PairsSet.(empty |> add (2,3) |> add (5,7) |> add (11,13)) -``` -This creates a new module `PairsSet`, with a new type `PairsSet.t` of sets of `int * int`. - -``` -module type OrderedType = sig ... end -``` -Input signature of the functor [`Make`](./Stdlib-Set-Make.md). - -``` -module type S = sig ... end -``` -Output signature of the functor [`Make`](./Stdlib-Set-Make.md). - -``` -module Make (Ord : OrderedType) : S with type elt = Ord.t -``` -Functor building an implementation of the set structure given a totally ordered type. diff --git a/docs/api/re/melange/Stdlib-Stack.md b/docs/api/re/melange/Stdlib-Stack.md deleted file mode 100644 index e02894994..000000000 --- a/docs/api/re/melange/Stdlib-Stack.md +++ /dev/null @@ -1,111 +0,0 @@ - -# Module `Stdlib.Stack` - -Last-in first-out stacks. - -This module implements stacks (LIFOs), with in-place modification. - -**Unsynchronized accesses** - -Unsynchronized accesses to a stack may lead to an invalid queue state. Thus, concurrent accesses to stacks must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -type !'a t -``` -The type of stacks containing elements of type `'a`. - -``` -exception Empty -``` -Raised when [`Stack.pop`](./#val-pop) or [`Stack.top`](./#val-top) is applied to an empty stack. - -``` -val create : unit -> 'a t -``` -Return a new stack, initially empty. - -``` -val push : 'a -> 'a t -> unit -``` -`push x s` adds the element `x` at the top of stack `s`. - -``` -val pop : 'a t -> 'a -``` -`pop s` removes and returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. - -``` -val pop_opt : 'a t -> 'a option -``` -`pop_opt s` removes and returns the topmost element in stack `s`, or returns `None` if the stack is empty. - -since 4.08 -``` -val drop : 'a t -> unit -``` -`drop s` removes the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. - -since 5.1 -``` -val top : 'a t -> 'a -``` -`top s` returns the topmost element in stack `s`, or raises [`Empty`](./#exception-Empty) if the stack is empty. - -``` -val top_opt : 'a t -> 'a option -``` -`top_opt s` returns the topmost element in stack `s`, or `None` if the stack is empty. - -since 4.08 -``` -val clear : 'a t -> unit -``` -Discard all elements from a stack. - -``` -val copy : 'a t -> 'a t -``` -Return a copy of the given stack. - -``` -val is_empty : 'a t -> bool -``` -Return `true` if the given stack is empty, `false` otherwise. - -``` -val length : 'a t -> int -``` -Return the number of elements in a stack. Time complexity O(1) - -``` -val iter : ('a -> unit) -> 'a t -> unit -``` -`iter f s` applies `f` in turn to all elements of `s`, from the element at the top of the stack to the element at the bottom of the stack. The stack itself is unchanged. - -``` -val fold : ('acc -> 'a -> 'acc) -> 'acc -> 'a t -> 'acc -``` -`fold f accu s` is `(f (... (f (f accu x1) x2) ...) xn)` where `x1` is the top of the stack, `x2` the second element, and `xn` the bottom element. The stack is unchanged. - -since 4.03 - -## Stacks and Sequences - -``` -val to_seq : 'a t -> 'a Seq.t -``` -Iterate on the stack, top to bottom. It is safe to modify the stack during iteration. - -since 4.07 -``` -val add_seq : 'a t -> 'a Seq.t -> unit -``` -Add the elements from the sequence on the top of the stack. - -since 4.07 -``` -val of_seq : 'a Seq.t -> 'a t -``` -Create a stack from the sequence. - -since 4.07 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-StdLabels.md b/docs/api/re/melange/Stdlib-StdLabels.md deleted file mode 100644 index e90ae87f6..000000000 --- a/docs/api/re/melange/Stdlib-StdLabels.md +++ /dev/null @@ -1,26 +0,0 @@ - -# Module `Stdlib.StdLabels` - -Standard labeled libraries. - -This meta-module provides versions of the [`Array`](./Stdlib-ArrayLabels.md), [`Bytes`](./Stdlib-BytesLabels.md), [`List`](./Stdlib-ListLabels.md) and [`String`](./Stdlib-StringLabels.md) modules where function arguments are systematically labeled. It is intended to be opened at the top of source files, as shown below. - -```ocaml - open StdLabels - - let to_upper = String.map ~f:Char.uppercase_ascii - let seq len = List.init ~f:(fun i -> i) ~len - let everything = Array.create_matrix ~dimx:42 ~dimy:42 42 -``` -``` -module Array = ArrayLabels -``` -``` -module Bytes = BytesLabels -``` -``` -module List = ListLabels -``` -``` -module String = StringLabels -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-String.md b/docs/api/re/melange/Stdlib-String.md deleted file mode 100644 index 063536325..000000000 --- a/docs/api/re/melange/Stdlib-String.md +++ /dev/null @@ -1,480 +0,0 @@ - -# Module `Stdlib.String` - -Strings. - -A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. - -The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. - -``` -positions 0 1 2 3 4 n-1 n - +---+---+---+---+ +-----+ - indices | 0 | 1 | 2 | 3 | ... | n-1 | - +---+---+---+---+ +-----+ -``` -- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. -- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. -Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. - -**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. - -**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - - -## Strings - -``` -type t = string -``` -The type for strings. - -``` -val make : int -> char -> string -``` -`make n c` is a string of length `n` with each index holding the character `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> (int -> char) -> string -``` -`init n f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -since 4.02 -``` -val empty : string -``` -The empty string. - -since 4.13 -``` -val length : string -> int -``` -`length s` is the length (number of bytes/characters) of `s`. - -``` -val get : string -> int -> char -``` -`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. -``` -val of_bytes : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -since 4.13 -``` -val to_bytes : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -since 4.13 -``` -val blit : string -> int -> bytes -> int -> int -> unit -``` -Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. - - -## Concatenating - -**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. - -``` -val concat : string -> string list -> string -``` -`concat sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : string -> string -> string -``` -`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.13 - -## Predicates and comparisons - -``` -val equal : t -> t -> bool -``` -`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. - -since 4.03 (4.05 in StringLabels) -``` -val compare : t -> t -> int -``` -`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. - -``` -val starts_with : prefix:string -> string -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:string -> string -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 -``` -val contains_from : string -> int -> char -> bool -``` -`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : string -> int -> char -> bool -``` -`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val contains : string -> char -> bool -``` -`contains s c` is [`String.contains_from`](./#val-contains_from)` s 0 c`. - - -## Extracting substrings - -``` -val sub : string -> int -> int -> string -``` -`sub s pos len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. -``` -val split_on_char : char -> string -> string list -``` -`split_on_char sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. - -The function's result is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). -- No string in the result contains the `sep` character. -since 4.04 (4.05 in StringLabels) - -## Transforming - -``` -val map : (char -> char) -> string -> string -``` -`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. - -since 4.00 -``` -val mapi : (int -> char -> char) -> string -> string -``` -`mapi f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. - -since 4.02 -``` -val fold_left : ('acc -> char -> 'acc) -> 'acc -> string -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. - -since 4.13 -``` -val fold_right : (char -> 'acc -> 'acc) -> string -> 'acc -> 'acc -``` -`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. - -since 4.13 -``` -val for_all : (char -> bool) -> string -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : (char -> bool) -> string -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : string -> string -``` -`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. - -since 4.00 -``` -val escaped : string -> string -``` -`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. - -All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). - -The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val uppercase_ascii : string -> string -``` -`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val lowercase_ascii : string -> string -``` -`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val capitalize_ascii : string -> string -``` -`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val uncapitalize_ascii : string -> string -``` -`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) - -## Traversing - -``` -val iter : (char -> unit) -> string -> unit -``` -`iter f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. - -``` -val iteri : (int -> char -> unit) -> string -> unit -``` -`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. - -since 4.00 - -## Searching - -``` -val index_from : string -> int -> char -> int -``` -`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -``` -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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : string -> int -> char -> int -``` -`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -``` -val rindex_from_opt : string -> int -> char -> int option -``` -`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val index : string -> char -> int -``` -`index s c` is [`String.index_from`](./#val-index_from)` s 0 c`. - -``` -val index_opt : string -> char -> int option -``` -`index_opt s c` is [`String.index_from_opt`](./#val-index_from_opt)` s 0 c`. - -since 4.05 -``` -val rindex : string -> char -> int -``` -`rindex s c` is [`String.rindex_from`](./#val-rindex_from)` s (length s - 1) c`. - -``` -val rindex_opt : string -> char -> int option -``` -`rindex_opt s c` is [`String.rindex_from_opt`](./#val-rindex_from_opt)` s (length s - 1) c`. - -since 4.05 - -## Strings and Sequences - -``` -val to_seq : t -> char Seq.t -``` -`to_seq s` is a sequence made of the string's characters in increasing order. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -`of_seq s` is a string made of the sequence's characters. - -since 4.07 - -## UTF decoding and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary decoding of integers - -The functions in this section binary decode integers from strings. - -All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. - -``` -val get_uint8 : string -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int8 : string -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_ne : string -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_be : string -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_le : string -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_ne : string -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_be : string -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_le : string -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_ne : string -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val hash : t -> int -``` -An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.0 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.0 -``` -val get_int32_be : string -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_le : string -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_ne : string -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_be : string -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_le : string -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. - -since 4.13 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-StringLabels.md b/docs/api/re/melange/Stdlib-StringLabels.md deleted file mode 100644 index c969a00a3..000000000 --- a/docs/api/re/melange/Stdlib-StringLabels.md +++ /dev/null @@ -1,486 +0,0 @@ - -# Module `Stdlib.StringLabels` - -Strings. - -A string `s` of length `n` is an indexable and immutable sequence of `n` bytes. For historical reasons these bytes are referred to as characters. - -The semantics of string functions is defined in terms of indices and positions. These are depicted and described as follows. - -``` -positions 0 1 2 3 4 n-1 n - +---+---+---+---+ +-----+ - indices | 0 | 1 | 2 | 3 | ... | n-1 | - +---+---+---+---+ +-----+ -``` -- An *index* `i` of `s` is an integer in the range \[`0`;`n-1`\]. It represents the `i`th byte (character) of `s` which can be accessed using the constant time string indexing operator `s.[i]`. -- A *position* `i` of `s` is an integer in the range \[`0`;`n`\]. It represents either the point at the beginning of the string, or the point between two indices, or the point at the end of the string. The `i`th byte index is between position `i` and `i+1`. -Two integers `start` and `len` are said to define a *valid substring* of `s` if `len >= 0` and `start`, `start+len` are positions of `s`. - -**Unicode text.** Strings being arbitrary sequences of bytes, they can hold any kind of textual encoding. However the recommended encoding for storing Unicode text in OCaml strings is UTF-8. This is the encoding used by Unicode escapes in string literals. For example the string `"\u{1F42B}"` is the UTF-8 encoding of the Unicode character U+1F42B. - -**Past mutability.** Before OCaml 4.02, strings used to be modifiable in place like [`Bytes.t`](./Stdlib-Bytes.md#type-t) mutable sequences of bytes. OCaml 4 had various compiler flags and configuration options to support the transition period from mutable to immutable strings. Those options are no longer available, and strings are now always immutable. - -The labeled version of this module can be used as described in the [`StdLabels`](./Stdlib-StdLabels.md) module. - - -## Strings - -``` -type t = string -``` -The type for strings. - -``` -val make : int -> char -> string -``` -`make n c` is a string of length `n` with each index holding the character `c`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -``` -val init : int -> f:(int -> char) -> string -``` -`init n ~f` is a string of length `n` with index `i` holding the character `f i` (called in increasing index order). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n \< 0 or n \> Sys.max\_string\_length. -since 4.02 -``` -val empty : string -``` -The empty string. - -since 4.13 -``` -val length : string -> int -``` -`length s` is the length (number of bytes/characters) of `s`. - -``` -val get : string -> int -> char -``` -`get s i` is the character at index `i` in `s`. This is the same as writing `s.[i]`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i not an index of s. -``` -val of_bytes : bytes -> string -``` -Return a new string that contains the same bytes as the given byte sequence. - -since 4.13 -``` -val to_bytes : string -> bytes -``` -Return a new byte sequence that contains the same bytes as the given string. - -since 4.13 -``` -val blit : - src:string -> - src_pos:int -> - dst:bytes -> - dst_pos:int -> - len:int -> - unit -``` -Same as [`Bytes.blit_string`](./Stdlib-Bytes.md#val-blit_string) which should be preferred. - - -## Concatenating - -**Note.** The [`Stdlib.(^)`](./Stdlib.md#val-\(^\)) binary operator concatenates two strings. - -``` -val concat : sep:string -> string list -> string -``` -`concat ~sep ss` concatenates the list of strings `ss`, inserting the separator string `sep` between each. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val cat : string -> string -> string -``` -`cat s1 s2` concatenates s1 and s2 (`s1 ^ s2`). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -since 4.13 - -## Predicates and comparisons - -``` -val equal : t -> t -> bool -``` -`equal s0 s1` is `true` if and only if `s0` and `s1` are character-wise equal. - -since 4.03 (4.05 in StringLabels) -``` -val compare : t -> t -> int -``` -`compare s0 s1` sorts `s0` and `s1` in lexicographical order. `compare` behaves like [`Stdlib.compare`](./Stdlib.md#val-compare) on strings but may be more efficient. - -``` -val starts_with : prefix:string -> string -> bool -``` -`starts_with ``~prefix s` is `true` if and only if `s` starts with `prefix`. - -since 4.13 -``` -val ends_with : suffix:string -> string -> bool -``` -`ends_with ``~suffix s` is `true` if and only if `s` ends with `suffix`. - -since 4.13 -``` -val contains_from : string -> int -> char -> bool -``` -`contains_from s start c` is `true` if and only if `c` appears in `s` after position `start`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if start is not a valid position in s. -``` -val rcontains_from : string -> int -> char -> bool -``` -`rcontains_from s stop c` is `true` if and only if `c` appears in `s` before position `stop+1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if stop \< 0 or stop+1 is not a valid position in s. -``` -val contains : string -> char -> bool -``` -`contains s c` is [`String.contains_from`](./Stdlib-String.md#val-contains_from)` s 0 c`. - - -## Extracting substrings - -``` -val sub : string -> pos:int -> len:int -> string -``` -`sub s ~pos ~len` is a string of length `len`, containing the substring of `s` that starts at position `pos` and has length `len`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if pos and len do not designate a valid substring of s. -``` -val split_on_char : sep:char -> string -> string list -``` -`split_on_char ~sep s` is the list of all (possibly empty) substrings of `s` that are delimited by the character `sep`. If `s` is empty, the result is the singleton list `[""]`. - -The function's result is specified by the following invariants: - -- The list is not empty. -- Concatenating its elements using `sep` as a separator returns a string equal to the input (`concat (make 1 sep) (split_on_char sep s) = s`). -- No string in the result contains the `sep` character. -since 4.04 (4.05 in StringLabels) - -## Transforming - -``` -val map : f:(char -> char) -> string -> string -``` -`map f s` is the string resulting from applying `f` to all the characters of `s` in increasing order. - -since 4.00 -``` -val mapi : f:(int -> char -> char) -> string -> string -``` -`mapi ~f s` is like [`map`](./#val-map) but the index of the character is also passed to `f`. - -since 4.02 -``` -val fold_left : f:('acc -> char -> 'acc) -> init:'acc -> string -> 'acc -``` -`fold_left f x s` computes `f (... (f (f x s.[0]) s.[1]) ...) s.[n-1]`, where `n` is the length of the string `s`. - -since 4.13 -``` -val fold_right : f:(char -> 'acc -> 'acc) -> string -> init:'acc -> 'acc -``` -`fold_right f s x` computes `f s.[0] (f s.[1] ( ... (f s.[n-1] x) ...))`, where `n` is the length of the string `s`. - -since 4.13 -``` -val for_all : f:(char -> bool) -> string -> bool -``` -`for_all p s` checks if all characters in `s` satisfy the predicate `p`. - -since 4.13 -``` -val exists : f:(char -> bool) -> string -> bool -``` -`exists p s` checks if at least one character of `s` satisfies the predicate `p`. - -since 4.13 -``` -val trim : string -> string -``` -`trim s` is `s` without leading and trailing whitespace. Whitespace characters are: `' '`, `'\x0C'` (form feed), `'\n'`, `'\r'`, and `'\t'`. - -since 4.00 -``` -val escaped : string -> string -``` -`escaped s` is `s` with special characters represented by escape sequences, following the lexical conventions of OCaml. - -All characters outside the US-ASCII printable range \[0x20;0x7E\] are escaped, as well as backslash (0x2F) and double-quote (0x22). - -The function [`Scanf.unescaped`](./Stdlib-Scanf.md#val-unescaped) is a left inverse of `escaped`, i.e. `Scanf.unescaped (escaped s) = s` for any string `s` (unless `escaped s` fails). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if the result is longer than Sys.max\_string\_length bytes. -``` -val uppercase_ascii : string -> string -``` -`uppercase_ascii s` is `s` with all lowercase letters translated to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val lowercase_ascii : string -> string -``` -`lowercase_ascii s` is `s` with all uppercase letters translated to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val capitalize_ascii : string -> string -``` -`capitalize_ascii s` is `s` with the first character set to uppercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) -``` -val uncapitalize_ascii : string -> string -``` -`uncapitalize_ascii s` is `s` with the first character set to lowercase, using the US-ASCII character set. - -since 4.03 (4.05 in StringLabels) - -## Traversing - -``` -val iter : f:(char -> unit) -> string -> unit -``` -`iter ~f s` applies function `f` in turn to all the characters of `s`. It is equivalent to `f s.[0]; f s.[1]; ...; f s.[length s - 1]; ()`. - -``` -val iteri : f:(int -> char -> unit) -> string -> unit -``` -`iteri` is like [`iter`](./#val-iter), but the function is also given the corresponding character index. - -since 4.00 - -## Searching - -``` -val index_from : string -> int -> char -> int -``` -`index_from s i c` is the index of the first occurrence of `c` in `s` after position `i`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s after position i. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -``` -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`](./Stdlib.md#exception-Invalid_argument) if i is not a valid position in s. -since 4.05 -``` -val rindex_from : string -> int -> char -> int -``` -`rindex_from s i c` is the index of the last occurrence of `c` in `s` before position `i+1`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if c does not occur in s before position i+1. -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -``` -val rindex_from_opt : string -> int -> char -> int option -``` -`rindex_from_opt s i c` is the index of the last occurrence of `c` in `s` before position `i+1` (if any). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i+1 is not a valid position in s. -since 4.05 -``` -val index : string -> char -> int -``` -`index s c` is [`String.index_from`](./Stdlib-String.md#val-index_from)` s 0 c`. - -``` -val index_opt : string -> char -> int option -``` -`index_opt s c` is [`String.index_from_opt`](./Stdlib-String.md#val-index_from_opt)` s 0 c`. - -since 4.05 -``` -val rindex : string -> char -> int -``` -`rindex s c` is [`String.rindex_from`](./Stdlib-String.md#val-rindex_from)` s (length s - 1) c`. - -``` -val rindex_opt : string -> char -> int option -``` -`rindex_opt s c` is [`String.rindex_from_opt`](./Stdlib-String.md#val-rindex_from_opt)` s (length s - 1) c`. - -since 4.05 - -## Strings and Sequences - -``` -val to_seq : t -> char Seq.t -``` -`to_seq s` is a sequence made of the string's characters in increasing order. - -since 4.07 -``` -val to_seqi : t -> (int * char) Seq.t -``` -`to_seqi s` is like [`to_seq`](./#val-to_seq) but also tuples the corresponding index. - -since 4.07 -``` -val of_seq : char Seq.t -> t -``` -`of_seq s` is a string made of the sequence's characters. - -since 4.07 - -## UTF decoding and validations - -since 4.14 - -### UTF-8 - -``` -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`. - -``` -val is_valid_utf_8 : t -> bool -``` -`is_valid_utf_8 b` is `true` if and only if `b` contains valid UTF-8 data. - - -### UTF-16BE - -``` -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`. - -``` -val is_valid_utf_16be : t -> bool -``` -`is_valid_utf_16be b` is `true` if and only if `b` contains valid UTF-16BE data. - - -### UTF-16LE - -``` -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`. - -``` -val is_valid_utf_16le : t -> bool -``` -`is_valid_utf_16le b` is `true` if and only if `b` contains valid UTF-16LE data. - - -## Binary decoding of integers - -The functions in this section binary decode integers from strings. - -All following functions raise `Invalid_argument` if the characters needed at index `i` to decode the integer are not available. - -Little-endian (resp. big-endian) encoding means that least (resp. most) significant bytes are stored first. Big-endian is also known as network byte order. Native-endian encoding is either little-endian or big-endian depending on [`Sys.big_endian`](./Stdlib-Sys.md#val-big_endian). - -32-bit and 64-bit integers are represented by the `int32` and `int64` types, which can be interpreted either as signed or unsigned numbers. - -8-bit and 16-bit integers are represented by the `int` type, which has more bits than the binary encoding. These extra bits are sign-extended (or zero-extended) for functions which decode 8-bit or 16-bit integers and represented them with `int` values. - -``` -val get_uint8 : string -> int -> int -``` -`get_uint8 b i` is `b`'s unsigned 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int8 : string -> int -> int -``` -`get_int8 b i` is `b`'s signed 8-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_ne : string -> int -> int -``` -`get_uint16_ne b i` is `b`'s native-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_be : string -> int -> int -``` -`get_uint16_be b i` is `b`'s big-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_uint16_le : string -> int -> int -``` -`get_uint16_le b i` is `b`'s little-endian unsigned 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_ne : string -> int -> int -``` -`get_int16_ne b i` is `b`'s native-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_be : string -> int -> int -``` -`get_int16_be b i` is `b`'s big-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int16_le : string -> int -> int -``` -`get_int16_le b i` is `b`'s little-endian signed 16-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_ne : string -> int -> int32 -``` -`get_int32_ne b i` is `b`'s native-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val hash : t -> int -``` -An unseeded hash function for strings, with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.0 -``` -val seeded_hash : int -> t -> int -``` -A seeded hash function for strings, with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.0 -``` -val get_int32_be : string -> int -> int32 -``` -`get_int32_be b i` is `b`'s big-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int32_le : string -> int -> int32 -``` -`get_int32_le b i` is `b`'s little-endian 32-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_ne : string -> int -> int64 -``` -`get_int64_ne b i` is `b`'s native-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_be : string -> int -> int64 -``` -`get_int64_be b i` is `b`'s big-endian 64-bit integer starting at character index `i`. - -since 4.13 -``` -val get_int64_le : string -> int -> int64 -``` -`get_int64_le b i` is `b`'s little-endian 64-bit integer starting at character index `i`. - -since 4.13 \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md deleted file mode 100644 index 8c2c620d7..000000000 --- a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-1-Immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Parameter `Make.Immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md deleted file mode 100644 index 08e19ba97..000000000 --- a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make-argument-2-Non_immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Parameter `Make.Non_immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md deleted file mode 100644 index deef830ee..000000000 --- a/docs/api/re/melange/Stdlib-Sys-Immediate64-Make.md +++ /dev/null @@ -1,33 +0,0 @@ - -# Module `Immediate64.Make` - - -## Parameters - -``` -module Immediate : Immediate -``` -``` -module Non_immediate : Non_immediate -``` - -## Signature - -``` -type t -``` -``` -type 'a repr = -``` -``` -| Immediate : Immediate.t repr -``` -``` -| Non_immediate : Non_immediate.t repr -``` -``` - -``` -``` -val repr : t repr -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md deleted file mode 100644 index f63bbba0a..000000000 --- a/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Module type `Immediate64.Immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md b/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md deleted file mode 100644 index d4d3814fd..000000000 --- a/docs/api/re/melange/Stdlib-Sys-Immediate64-module-type-Non_immediate.md +++ /dev/null @@ -1,6 +0,0 @@ - -# Module type `Immediate64.Non_immediate` - -``` -type t -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys-Immediate64.md b/docs/api/re/melange/Stdlib-Sys-Immediate64.md deleted file mode 100644 index 79e8eb8ca..000000000 --- a/docs/api/re/melange/Stdlib-Sys-Immediate64.md +++ /dev/null @@ -1,18 +0,0 @@ - -# Module `Sys.Immediate64` - -This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. - -since 4.10 -``` -module type Non_immediate = sig ... end -``` -``` -module type Immediate = sig ... end -``` -``` -module Make - (Immediate : Immediate) - (Non_immediate : Non_immediate) : - sig ... end -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Sys.md b/docs/api/re/melange/Stdlib-Sys.md deleted file mode 100644 index af5584b69..000000000 --- a/docs/api/re/melange/Stdlib-Sys.md +++ /dev/null @@ -1,476 +0,0 @@ - -# Module `Stdlib.Sys` - -System interface. - -Every function in this module raises `Sys_error` with an informative message when the underlying system call signal an error. - -``` -val argv : string array -``` -The command line arguments given to the process. The first element is the command name used to invoke the program. The following elements are the command-line arguments given to the program. - -``` -val executable_name : string -``` -The name of the file containing the executable currently running. This name may be absolute or relative to the current directory, depending on the platform and whether the program was compiled to bytecode or a native executable. - -``` -val file_exists : string -> bool -``` -Test if a file with the given name exists. - -``` -val is_directory : string -> bool -``` -Returns `true` if the given name refers to a directory, `false` if it refers to another kind of file. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. -since 3.10 -``` -val is_regular_file : string -> bool -``` -Returns `true` if the given name refers to a regular file, `false` if it refers to another kind of file. - -raises [`Sys_error`](./Stdlib.md#exception-Sys_error) if no file exists with the given name. -since 5.1 -``` -val remove : string -> unit -``` -Remove the given file name from the file system. - -``` -val rename : string -> string -> unit -``` -Rename a file or directory. `rename oldpath newpath` renames the file or directory called `oldpath`, giving it `newpath` as its new name, moving it between (parent) directories if needed. If a file named `newpath` already exists, its contents will be replaced with those of `oldpath`. Depending on the operating system, the metadata (permissions, owner, etc) of `newpath` can either be preserved or be replaced by those of `oldpath`. - -since 4.06 concerning the "replace existing file" behavior -``` -val getenv : string -> string -``` -Return the value associated to a variable in the process environment. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if the variable is unbound. -``` -val getenv_opt : string -> string option -``` -Return the value associated to a variable in the process environment or `None` if the variable is unbound. - -since 4.05 -``` -val command : string -> int -``` -Execute the given shell command and return its exit code. - -The argument of [`Sys.command`](./#val-command) is generally the name of a command followed by zero, one or several arguments, separated by whitespace. The given argument is interpreted by a shell: either the Windows shell `cmd.exe` for the Win32 ports of OCaml, or the POSIX shell `sh` for other ports. It can contain shell builtin commands such as `echo`, and also special characters such as file redirections `>` and `<`, which will be honored by the shell. - -Conversely, whitespace or special shell characters occurring in command names or in their arguments must be quoted or escaped so that the shell does not interpret them. The quoting rules vary between the POSIX shell and the Windows shell. The [`Filename.quote_command`](./Stdlib-Filename.md#val-quote_command) performs the appropriate quoting given a command name, a list of arguments, and optional file redirections. - -``` -val time : unit -> float -``` -Return the processor time, in seconds, used by the program since the beginning of execution. - -``` -val chdir : string -> unit -``` -Change the current working directory of the process. - -``` -val mkdir : string -> int -> unit -``` -Create a directory with the given permissions. - -since 4.12 -``` -val rmdir : string -> unit -``` -Remove an empty directory. - -since 4.12 -``` -val getcwd : unit -> string -``` -Return the current working directory of the process. - -``` -val readdir : string -> string array -``` -Return the names of all files present in the given directory. Names denoting the current directory and the parent directory (`"."` and `".."` in Unix) are not returned. Each string in the result is a file name rather than a complete path. There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order. - -``` -val interactive : bool ref -``` -This reference is initially set to `false` in standalone programs and to `true` if the code is being executed under the interactive toplevel system `ocaml`. - -alert unsynchronized\_access The interactive status is a mutable global state. -``` -val os_type : string -``` -Operating system currently executing the OCaml program. One of - -- `"Unix"` (for all Unix versions, including Linux and Mac OS X), -- `"Win32"` (for MS-Windows, OCaml compiled with MSVC++ or MinGW-w64), -- `"Cygwin"` (for MS-Windows, OCaml compiled with Cygwin). -``` -type backend_type = -``` -``` -| Native -``` -``` -| Bytecode -``` -``` -| Other of string -``` -``` - -``` -Currently, the official distribution only supports `Native` and `Bytecode`, but it can be other backends with alternative compilers, for example, javascript. - -since 4.04 -``` -val backend_type : backend_type -``` -Backend type currently executing the OCaml program. - -since 4.04 -``` -val unix : bool -``` -True if `Sys.os_type = "Unix"`. - -since 4.01 -``` -val win32 : bool -``` -True if `Sys.os_type = "Win32"`. - -since 4.01 -``` -val cygwin : bool -``` -True if `Sys.os_type = "Cygwin"`. - -since 4.01 -``` -val word_size : int -``` -Size of one word on the machine currently executing the OCaml program, in bits: 32 or 64. - -``` -val int_size : int -``` -Size of `int`, in bits. It is 31 (resp. 63) when using OCaml on a 32-bit (resp. 64-bit) platform. It may differ for other implementations, e.g. it can be 32 bits when compiling to JavaScript. - -since 4.03 -``` -val big_endian : bool -``` -Whether the machine currently executing the Caml program is big-endian. - -since 4.00 -``` -val max_string_length : int -``` -Maximum length of strings and byte sequences. - -``` -val max_array_length : int -``` -Maximum length of a normal array (i.e. any array whose elements are not of type `float`). The maximum length of a `float array` is `max_floatarray_length` if OCaml was configured with `--enable-flat-float-array` and `max_array_length` if configured with `--disable-flat-float-array`. - -``` -val max_floatarray_length : int -``` -Maximum length of a floatarray. This is also the maximum length of a `float array` when OCaml is configured with `--enable-flat-float-array`. - -``` -val runtime_variant : unit -> string -``` -Return the name of the runtime variant the program is running on. This is normally the argument given to `-runtime-variant` at compile time, but for byte-code it can be changed after compilation. - -since 4.03 -``` -val runtime_parameters : unit -> string -``` -Return the value of the runtime parameters, in the same format as the contents of the `OCAMLRUNPARAM` environment variable. - -since 4.03 - -## Signal handling - -``` -type signal_behavior = -``` -``` -| Signal_default -``` -``` -| Signal_ignore -``` -``` -| Signal_handle of int -> unit -``` -``` - -``` -What to do when receiving a signal: - -- `Signal_default`: take the default behavior (usually: abort the program) -- `Signal_ignore`: ignore the signal -- `Signal_handle f`: call function `f`, giving it the signal number as argument. -``` -val signal : int -> signal_behavior -> signal_behavior -``` -Set the behavior of the system on receipt of a given signal. The first argument is the signal number. Return the behavior previously associated with the signal. If the signal number is invalid (or not available on your system), an `Invalid_argument` exception is raised. - -``` -val set_signal : int -> signal_behavior -> unit -``` -Same as [`Sys.signal`](./#val-signal) but return value is ignored. - - -### Signal numbers for the standard POSIX signals. - -``` -val sigabrt : int -``` -Abnormal termination - -``` -val sigalrm : int -``` -Timeout - -``` -val sigfpe : int -``` -Arithmetic exception - -``` -val sighup : int -``` -Hangup on controlling terminal - -``` -val sigill : int -``` -Invalid hardware instruction - -``` -val sigint : int -``` -Interactive interrupt (ctrl-C) - -``` -val sigkill : int -``` -Termination (cannot be ignored) - -``` -val sigpipe : int -``` -Broken pipe - -``` -val sigquit : int -``` -Interactive termination - -``` -val sigsegv : int -``` -Invalid memory reference - -``` -val sigterm : int -``` -Termination - -``` -val sigusr1 : int -``` -Application-defined signal 1 - -``` -val sigusr2 : int -``` -Application-defined signal 2 - -``` -val sigchld : int -``` -Child process terminated - -``` -val sigcont : int -``` -Continue - -``` -val sigstop : int -``` -Stop - -``` -val sigtstp : int -``` -Interactive stop - -``` -val sigttin : int -``` -Terminal read from background process - -``` -val sigttou : int -``` -Terminal write from background process - -``` -val sigvtalrm : int -``` -Timeout in virtual time - -``` -val sigprof : int -``` -Profiling interrupt - -``` -val sigbus : int -``` -Bus error - -since 4.03 -``` -val sigpoll : int -``` -Pollable event - -since 4.03 -``` -val sigsys : int -``` -Bad argument to routine - -since 4.03 -``` -val sigtrap : int -``` -Trace/breakpoint trap - -since 4.03 -``` -val sigurg : int -``` -Urgent condition on socket - -since 4.03 -``` -val sigxcpu : int -``` -Timeout in cpu time - -since 4.03 -``` -val sigxfsz : int -``` -File size limit exceeded - -since 4.03 -``` -exception Break -``` -Exception raised on interactive interrupt if [`Sys.catch_break`](./#val-catch_break) is enabled. - -``` -val catch_break : bool -> unit -``` -`catch_break` governs whether interactive interrupt (ctrl-C) terminates the program or raises the `Break` exception. Call `catch_break true` to enable raising `Break`, and `catch_break false` to let the system terminate the program on user interrupt. - -Inside multi-threaded programs, the `Break` exception will arise in any one of the active threads, and will keep arising on further interactive interrupt until all threads are terminated. Use signal masks from `Thread.sigmask` to direct the interrupt towards a specific thread. - -``` -val ocaml_version : string -``` -`ocaml_version` is the version of OCaml. It is a string of the form `"major.minor[.patchlevel][(+|~)additional-info]"`, where `major`, `minor`, and `patchlevel` are integers, and `additional-info` is an arbitrary string. The `[.patchlevel]` part was absent before version 3.08.0 and became mandatory from 3.08.0 onwards. The `[(+|~)additional-info]` part may be absent. - -``` -val development_version : bool -``` -`true` if this is a development version, `false` otherwise. - -since 4.14 -``` -type extra_prefix = -``` -``` -| Plus -``` -``` -| Tilde -``` -since 4.14 -``` - -``` -``` -type extra_info = extra_prefix * string -``` -since 4.14 -``` -type ocaml_release_info = { -``` -`major : int;` -`minor : int;` -`patchlevel : int;` -`extra : extra_info option;` -``` -} -``` -since 4.14 -``` -val ocaml_release : ocaml_release_info -``` -`ocaml_release` is the version of OCaml. - -since 4.14 -``` -val enable_runtime_warnings : bool -> unit -``` -Control whether the OCaml runtime system can emit warnings on stderr. Currently, the only supported warning is triggered when a channel created by `open_*` functions is finalized without being closed. Runtime warnings are disabled by default. - -since 4.03 -alert unsynchronized\_access The status of runtime warnings is a mutable global state. -``` -val runtime_warnings_enabled : unit -> bool -``` -Return whether runtime warnings are currently enabled. - -since 4.03 -alert unsynchronized\_access The status of runtime warnings is a mutable global state. - -## Optimization - -``` -val opaque_identity : 'a -> 'a -``` -For the purposes of optimization, `opaque_identity` behaves like an unknown (and thus possibly side-effecting) function. - -At runtime, `opaque_identity` disappears altogether. However, it does prevent the argument from being garbage collected until the location where the call would have occurred. - -A typical use of this function is to prevent pure computations from being optimized away in benchmarking loops. For example: - -```ocaml - for _round = 1 to 100_000 do - ignore (Sys.opaque_identity (my_pure_computation ())) - done -``` -since 4.03 -``` -module Immediate64 : sig ... end -``` -This module allows to define a type `t` with the `immediate64` attribute. This attribute means that the type is immediate on 64 bit architectures. On other architectures, it might or might not be immediate. diff --git a/docs/api/re/melange/Stdlib-Type-Id.md b/docs/api/re/melange/Stdlib-Type-Id.md deleted file mode 100644 index 39402a663..000000000 --- a/docs/api/re/melange/Stdlib-Type-Id.md +++ /dev/null @@ -1,80 +0,0 @@ - -# Module `Type.Id` - -Type identifiers. - -A type identifier is a value that denotes a type. Given two type identifiers, they can be tested for [equality](./#val-provably_equal) to prove they denote the same type. Note that: - -- Unequal identifiers do not imply unequal types: a given type can be denoted by more than one identifier. -- Type identifiers can be marshalled, but they get a new, distinct, identity on unmarshalling, so the equalities are lost. -See an [example](./#example) of use. - - -## Type identifiers - -``` -type !'a t -``` -The type for identifiers for type `'a`. - -``` -val make : unit -> 'a t -``` -`make ()` is a new type identifier. - -``` -val uid : 'a t -> int -``` -`uid id` is a runtime unique identifier for `id`. - -``` -val provably_equal : 'a t -> 'b t -> ('a, 'b) eq option -``` -`provably_equal i0 i1` is `Some Equal` if identifier `i0` is equal to `i1` and `None` otherwise. - - -## Example - -The following shows how type identifiers can be used to implement a simple heterogeneous key-value dictionary. In contrast to [`Stdlib.Map`](./Stdlib-Map.md) values whose keys map to a single, homogeneous type of values, this dictionary can associate a different type of value to each key. - -```ocaml -(** Heterogeneous dictionaries. *) -module Dict : sig - type t - (** The type for dictionaries. *) - - type 'a key - (** The type for keys binding values of type ['a]. *) - - val key : unit -> 'a key - (** [key ()] is a new dictionary key. *) - - val empty : t - (** [empty] is the empty dictionary. *) - - val add : 'a key -> 'a -> t -> t - (** [add k v d] is [d] with [k] bound to [v]. *) - - val remove : 'a key -> t -> t - (** [remove k d] is [d] with the last binding of [k] removed. *) - - val find : 'a key -> t -> 'a option - (** [find k d] is the binding of [k] in [d], if any. *) -end = struct - type 'a key = 'a Type.Id.t - type binding = B : 'a key * 'a -> binding - type t = (int * binding) list - - let key () = Type.Id.make () - let empty = [] - let add k v d = (Type.Id.uid k, B (k, v)) :: d - let remove k d = List.remove_assoc (Type.Id.uid k) d - let find : type a. a key -> t -> a option = fun k d -> - match List.assoc_opt (Type.Id.uid k) d with - | None -> None - | Some (B (k', v)) -> - match Type.Id.provably_equal k k' with - | Some Type.Equal -> Some v - | None -> assert false -end -``` \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Type.md b/docs/api/re/melange/Stdlib-Type.md deleted file mode 100644 index 0a071fda8..000000000 --- a/docs/api/re/melange/Stdlib-Type.md +++ /dev/null @@ -1,36 +0,0 @@ - -# Module `Stdlib.Type` - -Type introspection. - -since 5.1 - -## Type equality witness - -``` -type (_, _) eq = -``` -``` -| Equal : ('a, 'a) eq -``` -``` - -``` -The purpose of `eq` is to represent type equalities that may not otherwise be known by the type checker (e.g. because they may depend on dynamic data). - -A value of type `(a, b) eq` represents the fact that types `a` and `b` are equal. - -If one has a value `eq : (a, b) eq` that proves types `a` and `b` are equal, one can use it to convert a value of type `a` to a value of type `b` by pattern matching on `Equal`: - -```ocaml - let cast (type a) (type b) (Equal : (a, b) Type.eq) (a : a) : b = a -``` -At runtime, this function simply returns its second argument unchanged. - - -## Type identifiers - -``` -module Id : sig ... end -``` -Type identifiers. diff --git a/docs/api/re/melange/Stdlib-Uchar.md b/docs/api/re/melange/Stdlib-Uchar.md deleted file mode 100644 index a90cfee5e..000000000 --- a/docs/api/re/melange/Stdlib-Uchar.md +++ /dev/null @@ -1,144 +0,0 @@ - -# Module `Stdlib.Uchar` - -Unicode characters. - -since 4.03 -``` -type t -``` -The type for Unicode characters. - -A value of this type represents a Unicode [scalar value](http://unicode.org/glossary/#unicode_scalar_value) which is an integer in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`. - -``` -val min : t -``` -`min` is U+0000. - -``` -val max : t -``` -`max` is U+10FFFF. - -``` -val bom : t -``` -`bom` is U+FEFF, the [byte order mark](http://unicode.org/glossary/#byte_order_mark) (BOM) character. - -since 4.06 -``` -val rep : t -``` -`rep` is U+FFFD, the [replacement](http://unicode.org/glossary/#replacement_character) character. - -since 4.06 -``` -val succ : t -> t -``` -`succ u` is the scalar value after `u` in the set of Unicode scalar values. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is max. -``` -val pred : t -> t -``` -`pred u` is the scalar value before `u` in the set of Unicode scalar values. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u is min. -``` -val is_valid : int -> bool -``` -`is_valid n` is `true` if and only if `n` is a Unicode scalar value (i.e. in the ranges `0x0000`...`0xD7FF` or `0xE000`...`0x10FFFF`). - -``` -val of_int : int -> t -``` -`of_int i` is `i` as a Unicode character. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if i does not satisfy is\_valid. -``` -val to_int : t -> int -``` -`to_int u` is `u` as an integer. - -``` -val is_char : t -> bool -``` -`is_char u` is `true` if and only if `u` is a latin1 OCaml character. - -``` -val of_char : char -> t -``` -`of_char c` is `c` as a Unicode character. - -``` -val to_char : t -> char -``` -`to_char u` is `u` as an OCaml latin1 character. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if u does not satisfy is\_char. -``` -val equal : t -> t -> bool -``` -`equal u u'` is `u = u'`. - -``` -val compare : t -> t -> int -``` -`compare u u'` is `Stdlib.compare u u'`. - -``` -val seeded_hash : int -> t -> int -``` -`seeded_hash seed u` A seeded hash function with the same output value as [`Hashtbl.seeded_hash`](./Stdlib-Hashtbl.md#val-seeded_hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.MakeSeeded`](./Stdlib-Hashtbl-MakeSeeded.md). - -since 5.3 -``` -val hash : t -> int -``` -An unseeded hash function with the same output value as [`Hashtbl.hash`](./Stdlib-Hashtbl.md#val-hash). This function allows this module to be passed as an argument to the functor [`Hashtbl.Make`](./Stdlib-Hashtbl-Make.md). - -since 5.3 - -## UTF codecs tools - -since 4.14 -``` -type utf_decode -``` -The type for UTF decode results. Values of this type represent the result of a Unicode Transformation Format decoding attempt. - -``` -val utf_decode_is_valid : utf_decode -> bool -``` -`utf_decode_is_valid d` is `true` if and only if `d` holds a valid decode. - -``` -val utf_decode_uchar : utf_decode -> t -``` -`utf_decode_uchar d` is the Unicode character decoded by `d` if `utf_decode_is_valid d` is `true` and [`Uchar.rep`](./#val-rep) otherwise. - -``` -val utf_decode_length : utf_decode -> int -``` -`utf_decode_length d` is the number of elements from the source that were consumed by the decode `d`. This is always strictly positive and smaller or equal to `4`. The kind of source elements depends on the actual decoder; for the decoders of the standard library this function always returns a length in bytes. - -``` -val utf_decode : int -> t -> utf_decode -``` -`utf_decode n u` is a valid UTF decode for `u` that consumed `n` elements from the source for decoding. `n` must be positive and smaller or equal to `4` (this is not checked by the module). - -``` -val utf_decode_invalid : int -> utf_decode -``` -`utf_decode_invalid n` is an invalid UTF decode that consumed `n` elements from the source to error. `n` must be positive and smaller or equal to `4` (this is not checked by the module). The resulting decode has [`rep`](./#val-rep) as the decoded Unicode character. - -``` -val utf_8_byte_length : t -> int -``` -`utf_8_byte_length u` is the number of bytes needed to encode `u` in UTF-8. - -``` -val utf_16_byte_length : t -> int -``` -`utf_16_byte_length u` is the number of bytes needed to encode `u` in UTF-16. diff --git a/docs/api/re/melange/Stdlib-Unit.md b/docs/api/re/melange/Stdlib-Unit.md deleted file mode 100644 index 50428889e..000000000 --- a/docs/api/re/melange/Stdlib-Unit.md +++ /dev/null @@ -1,36 +0,0 @@ - -# Module `Stdlib.Unit` - -Unit values. - -since 4.08 - -## The unit type - -``` -type t = unit = -``` -``` -| () -``` -``` - -``` -The unit type. - -The constructor `()` is included here so that it has a path, but it is not intended to be used in user-defined data types. - -``` -val equal : t -> t -> bool -``` -`equal u1 u2` is `true`. - -``` -val compare : t -> t -> int -``` -`compare u1 u2` is `0`. - -``` -val to_string : t -> string -``` -`to_string b` is `"()"`. diff --git a/docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md b/docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md deleted file mode 100644 index 80efdc53c..000000000 --- a/docs/api/re/melange/Stdlib-Weak-Make-argument-1-H.md +++ /dev/null @@ -1,21 +0,0 @@ - -# Parameter `Make.H` - -``` -type t -``` -The type of the hashtable keys. - -``` -val equal : t -> t -> bool -``` -The equality predicate used to compare keys. - -``` -val hash : t -> int -``` -A hashing function on keys. It must be such that if two keys are equal according to `equal`, then they have identical hash values as computed by `hash`. Examples: suitable (`equal`, `hash`) pairs for arbitrary key types include - -- (`(=)`, [`hash`](./#val-hash)) for comparing objects by structure (provided objects do not contain floats) -- (`(fun x y -> compare x y = 0)`, [`hash`](./#val-hash)) for comparing objects by structure and handling [`Stdlib.nan`](./Stdlib.md#val-nan) correctly -- (`(==)`, [`hash`](./#val-hash)) for comparing objects by physical equality (e.g. for mutable or cyclic objects). \ No newline at end of file diff --git a/docs/api/re/melange/Stdlib-Weak-Make.md b/docs/api/re/melange/Stdlib-Weak-Make.md deleted file mode 100644 index a9786f098..000000000 --- a/docs/api/re/melange/Stdlib-Weak-Make.md +++ /dev/null @@ -1,90 +0,0 @@ - -# Module `Weak.Make` - -Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. - - -## Parameters - -``` -module H : Hashtbl.HashedType -``` - -## Signature - -``` -type data = H.t -``` -The type of the elements stored in the table. - -``` -type t -``` -The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. - -``` -val create : int -> t -``` -`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. - -``` -val clear : t -> unit -``` -Remove all elements from the table. - -``` -val merge : t -> data -> data -``` -`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. - -``` -val add : t -> data -> unit -``` -`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. - -``` -val remove : t -> data -> unit -``` -`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. - -``` -val find : t -> data -> data -``` -`find t x` returns an instance of `x` found in `t`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. -``` -val find_opt : t -> data -> data option -``` -`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. - -since 4.05 -``` -val find_all : t -> data -> data list -``` -`find_all t x` returns a list of all the instances of `x` found in `t`. - -``` -val mem : t -> data -> bool -``` -`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. - -``` -val iter : (data -> unit) -> t -> unit -``` -`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val count : t -> int -``` -Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. - -``` -val stats : t -> int * int * int * int * int * int -``` -Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/re/melange/Stdlib-Weak-module-type-S.md b/docs/api/re/melange/Stdlib-Weak-module-type-S.md deleted file mode 100644 index 22f814459..000000000 --- a/docs/api/re/melange/Stdlib-Weak-module-type-S.md +++ /dev/null @@ -1,81 +0,0 @@ - -# Module type `Weak.S` - -The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). - -``` -type data -``` -The type of the elements stored in the table. - -``` -type t -``` -The type of tables that contain elements of type `data`. Note that weak hash sets cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) or the functions of the [`Marshal`](./Stdlib-Marshal.md) module. - -``` -val create : int -> t -``` -`create n` creates a new empty weak hash set, of initial size `n`. The table will grow as needed. - -``` -val clear : t -> unit -``` -Remove all elements from the table. - -``` -val merge : t -> data -> data -``` -`merge t x` returns an instance of `x` found in `t` if any, or else adds `x` to `t` and return `x`. - -``` -val add : t -> data -> unit -``` -`add t x` adds `x` to `t`. If there is already an instance of `x` in `t`, it is unspecified which one will be returned by subsequent calls to `find` and `merge`. - -``` -val remove : t -> data -> unit -``` -`remove t x` removes from `t` one instance of `x`. Does nothing if there is no instance of `x` in `t`. - -``` -val find : t -> data -> data -``` -`find t x` returns an instance of `x` found in `t`. - -raises [`Not_found`](./Stdlib.md#exception-Not_found) if there is no such element. -``` -val find_opt : t -> data -> data option -``` -`find_opt t x` returns an instance of `x` found in `t` or `None` if there is no such element. - -since 4.05 -``` -val find_all : t -> data -> data list -``` -`find_all t x` returns a list of all the instances of `x` found in `t`. - -``` -val mem : t -> data -> bool -``` -`mem t x` returns `true` if there is at least one instance of `x` in `t`, false otherwise. - -``` -val iter : (data -> unit) -> t -> unit -``` -`iter f t` calls `f` on each element of `t`, in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val fold : (data -> 'acc -> 'acc) -> t -> 'acc -> 'acc -``` -`fold f t init` computes `(f d1 (... (f dN init)))` where `d1 ... dN` are the elements of `t` in some unspecified order. It is not specified what happens if `f` tries to change `t` itself. - -``` -val count : t -> int -``` -Count the number of elements in the table. `count t` gives the same result as `fold (fun _ n -> n+1) t 0` but does not delay the deallocation of the dead elements. - -``` -val stats : t -> int * int * int * int * int * int -``` -Return statistics on the table. The numbers are, in order: table length, number of entries, sum of bucket lengths, smallest bucket length, median bucket length, biggest bucket length. diff --git a/docs/api/re/melange/Stdlib-Weak.md b/docs/api/re/melange/Stdlib-Weak.md deleted file mode 100644 index 98afcfae4..000000000 --- a/docs/api/re/melange/Stdlib-Weak.md +++ /dev/null @@ -1,88 +0,0 @@ - -# Module `Stdlib.Weak` - -Arrays of weak pointers and hash sets of weak pointers. - - -## Low-level functions - -``` -type !'a t -``` -The type of arrays of weak pointers (weak arrays). A weak pointer is a value that the garbage collector may erase whenever the value is not used any more (through normal pointers) by the program. Note that finalisation functions are run before the weak pointers are erased, because the finalisation functions can make values alive again (before 4.03 the finalisation functions were run after). - -A weak pointer is said to be full if it points to a value, empty if the value was erased by the GC. - -Notes: - -- Integers are not allocated and cannot be stored in weak arrays. -- Weak arrays cannot be marshaled using [`Stdlib.output_value`](./Stdlib.md#val-output_value) nor the functions of the [`Marshal`](./Stdlib-Marshal.md) module. -``` -val create : int -> 'a t -``` -`Weak.create n` returns a new weak array of length `n`. All the pointers are initially empty. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not comprised between zero and Obj.Ephemeron.max\_ephe\_length (limits included). -``` -val length : 'a t -> int -``` -`Weak.length ar` returns the length (number of elements) of `ar`. - -``` -val set : 'a t -> int -> 'a option -> unit -``` -`Weak.set ar n (Some el)` sets the `n`th cell of `ar` to be a (full) pointer to `el`; `Weak.set ar n None` sets the `n`th cell of `ar` to empty. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -``` -val get : 'a t -> int -> 'a option -``` -`Weak.get ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is the value) if it is full. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -``` -val get_copy : 'a t -> int -> 'a option -``` -`Weak.get_copy ar n` returns None if the `n`th cell of `ar` is empty, `Some x` (where `x` is a (shallow) copy of the value) if it is full. In addition to pitfalls with mutable values, the interesting difference with `get` is that `get_copy` does not prevent the incremental GC from erasing the value in its current cycle (`get` may delay the erasure to the next GC cycle). - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -If the element is a custom block it is not copied. - -``` -val check : 'a t -> int -> bool -``` -`Weak.check ar n` returns `true` if the `n`th cell of `ar` is full, `false` if it is empty. Note that even if `Weak.check ar n` returns `true`, a subsequent [`Weak.get`](./#val-get)` ar n` can return `None`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if n is not in the range 0 to Weak.length ar - 1. -``` -val fill : 'a t -> int -> int -> 'a option -> unit -``` -`Weak.fill ar ofs len el` sets to `el` all pointers of `ar` from `ofs` to `ofs + len - 1`. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if ofs and len do not designate a valid subarray of ar. -``` -val blit : 'a t -> int -> 'a t -> int -> int -> unit -``` -`Weak.blit ar1 off1 ar2 off2 len` copies `len` weak pointers from `ar1` (starting at `off1`) to `ar2` (starting at `off2`). It works correctly even if `ar1` and `ar2` are the same. - -raises [`Invalid_argument`](./Stdlib.md#exception-Invalid_argument) if off1 and len do not designate a valid subarray of ar1, or if off2 and len do not designate a valid subarray of ar2. - -## Weak hash sets - -A weak hash set is a hashed set of values. Each value may magically disappear from the set when it is not used by the rest of the program any more. This is normally used to share data structures without inducing memory leaks. Weak hash sets are defined on values from a [`Hashtbl.HashedType`](./Stdlib-Hashtbl-module-type-HashedType.md) module; the `equal` relation and `hash` function are taken from that module. We will say that `v` is an instance of `x` if `equal x v` is `true`. - -The `equal` relation must be able to work on a shallow copy of the values and give the same result as with the values themselves. - -**Unsynchronized accesses** - -Unsynchronized accesses to weak hash sets are a programming error. Unsynchronized accesses to a weak hash set may lead to an invalid weak hash set state. Thus, concurrent accesses to weak hash sets must be synchronized (for instance with a [`Mutex.t`](./Stdlib-Mutex.md#type-t)). - -``` -module type S = sig ... end -``` -The output signature of the functor [`Weak.Make`](./Stdlib-Weak-Make.md). - -``` -module Make (H : Hashtbl.HashedType) : S with type data = H.t -``` -Functor building an implementation of the weak hash set structure. `H.equal` can't be the physical equality, since only shallow copies of the elements in the set are given to it. diff --git a/docs/api/re/melange/Stdlib.md b/docs/api/re/melange/Stdlib.md deleted file mode 100644 index ba13a16e8..000000000 --- a/docs/api/re/melange/Stdlib.md +++ /dev/null @@ -1,1565 +0,0 @@ - -# Module `Stdlib` - -The OCaml Standard library. - -This module is automatically opened at the beginning of each compilation. All components of this module can therefore be referred by their short name, without prefixing them by `Stdlib`. - -In particular, it provides the basic operations over the built-in types (numbers, booleans, byte sequences, strings, exceptions, references, lists, arrays, input-output channels, ...) and the [standard library modules](./#modules). - - -## Exceptions - -``` -val raise : exn -> 'a -``` -Raise the given exception value - -``` -val raise_notrace : exn -> 'a -``` -A faster version `raise` which does not record the backtrace. - -since 4.02 -``` -val invalid_arg : string -> 'a -``` -Raise exception `Invalid_argument` with the given string. - -``` -val failwith : string -> 'a -``` -Raise exception `Failure` with the given string. - -``` -exception Exit -``` -The `Exit` exception is not raised by any library function. It is provided for use in your programs. - -``` -exception Match_failure of string * int * int -``` -Exception raised when none of the cases of a pattern-matching apply. The arguments are the location of the match keyword in the source code (file name, line number, column number). - -``` -exception Assert_failure of string * int * int -``` -Exception raised when an assertion fails. The arguments are the location of the assert keyword in the source code (file name, line number, column number). - -``` -exception Invalid_argument of string -``` -Exception raised by library functions to signal that the given arguments do not make sense. The string gives some information to the programmer. As a general rule, this exception should not be caught, it denotes a programming error and the code should be modified not to trigger it. - -``` -exception Failure of string -``` -Exception raised by library functions to signal that they are undefined on the given arguments. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Failure \_ instead). - -``` -exception Not_found -``` -Exception raised by search functions when the desired object could not be found. - -``` -exception Out_of_memory -``` -Exception raised by the garbage collector when there is insufficient memory to complete the computation. (Not reliable for allocations on the minor heap.) - -``` -exception Stack_overflow -``` -Exception raised by the bytecode interpreter when the evaluation stack reaches its maximal size. This often indicates infinite or excessively deep recursion in the user's program. - -Before 4.10, it was not fully implemented by the native-code compiler. - -``` -exception Sys_error of string -``` -Exception raised by the input/output functions to report an operating system error. The string is meant to give some information to the programmer; you must not pattern match on the string literal because it may change in future versions (use Sys\_error \_ instead). - -``` -exception End_of_file -``` -Exception raised by input functions to signal that the end of file has been reached. - -``` -exception Division_by_zero -``` -Exception raised by integer division and remainder operations when their second argument is zero. - -``` -exception Sys_blocked_io -``` -A special case of Sys\_error raised when no I/O is possible on a non-blocking I/O channel. - -``` -exception Undefined_recursive_module of string * int * int -``` -Exception raised when an ill-founded recursive module definition is evaluated. The arguments are the location of the definition in the source code (file name, line number, column number). - - -## Comparisons - -``` -val (=) : 'a -> 'a -> bool -``` -`e1 = e2` tests for structural equality of `e1` and `e2`. Mutable structures (e.g. references and arrays) are equal if and only if their current contents are structurally equal, even if the two mutable objects are not the same physical object. Equality between functional values raises `Invalid_argument`. Equality between cyclic data structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (<>) : 'a -> 'a -> bool -``` -Negation of [`Stdlib.(=)`](./#val-\(=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (<) : 'a -> 'a -> bool -``` -See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (>) : 'a -> 'a -> bool -``` -See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (<=) : 'a -> 'a -> bool -``` -See [`Stdlib.(>=)`](./#val-\(>=\)). Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (>=) : 'a -> 'a -> bool -``` -Structural ordering functions. These functions coincide with the usual orderings over integers, characters, strings, byte sequences and floating-point numbers, and extend them to a total ordering over all types. The ordering is compatible with `( = )`. As in the case of `( = )`, mutable structures are compared by contents. Comparison between functional values raises `Invalid_argument`. Comparison between cyclic structures may not terminate. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val compare : 'a -> 'a -> int -``` -`compare x y` returns `0` if `x` is equal to `y`, a negative integer if `x` is less than `y`, and a positive integer if `x` is greater than `y`. The ordering implemented by `compare` is compatible with the comparison predicates `=`, `<` and `>` defined above, with one difference on the treatment of the float value [`Stdlib.nan`](./#val-nan). Namely, the comparison predicates treat `nan` as different from any other float value, including itself; while `compare` treats `nan` as equal to itself and less than any other float value. This treatment of `nan` ensures that `compare` defines a total ordering relation. - -`compare` applied to functional values may raise `Invalid_argument`. `compare` applied to cyclic structures may not terminate. - -The `compare` function can be used as the comparison function required by the [`Set.Make`](./Stdlib-Set-Make.md) and [`Map.Make`](./Stdlib-Map-Make.md) functors, as well as the [`List.sort`](./Stdlib-List.md#val-sort) and [`Array.sort`](./Stdlib-Array.md#val-sort) functions. - -``` -val min : 'a -> 'a -> 'a -``` -``` -val max : 'a -> 'a -> 'a -``` -``` -val (==) : 'a -> 'a -> bool -``` -`e1 == e2` tests for physical equality of `e1` and `e2`. On mutable types such as references, arrays, byte sequences, records with mutable fields and objects with mutable instance variables, `e1 == e2` is true if and only if physical modification of `e1` also affects `e2`. On non-mutable types, the behavior of `( == )` is implementation-dependent; however, it is guaranteed that `e1 == e2` implies `compare e1 e2 = 0`. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (!=) : 'a -> 'a -> bool -``` -Negation of [`Stdlib.(==)`](./#val-\(==\)). Left-associative operator, see `Ocaml_operators` for more information. - - -## Boolean operations - -``` -val not : bool -> bool -``` -The boolean negation. - -``` -val (&&) : bool -> bool -> bool -``` -The boolean 'and'. Evaluation is sequential, left-to-right: in `e1 && e2`, `e1` is evaluated first, and if it returns `false`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val (||) : bool -> bool -> bool -``` -The boolean 'or'. Evaluation is sequential, left-to-right: in `e1 || e2`, `e1` is evaluated first, and if it returns `true`, `e2` is not evaluated at all. Right-associative operator, see `Ocaml_operators` for more information. - - -## Debugging - -``` -val __LOC__ : string -``` -`__LOC__` returns the location at which this expression appears in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". - -since 4.02 -``` -val __FILE__ : string -``` -`__FILE__` returns the name of the file currently being parsed by the compiler. - -since 4.02 -``` -val __LINE__ : int -``` -`__LINE__` returns the line number at which this expression appears in the file currently being parsed by the compiler. - -since 4.02 -``` -val __MODULE__ : string -``` -`__MODULE__` returns the module name of the file being parsed by the compiler. - -since 4.02 -``` -val __POS__ : string * int * int * int -``` -`__POS__` returns a tuple `(file,lnum,cnum,enum)`, corresponding to the location at which this expression appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. - -since 4.02 -``` -val __FUNCTION__ : string -``` -`__FUNCTION__` returns the name of the current function or method, including any enclosing modules or classes. - -since 4.12 -``` -val __LOC_OF__ : 'a -> string * 'a -``` -`__LOC_OF__ expr` returns a pair `(loc, expr)` where `loc` is the location of `expr` in the file currently being parsed by the compiler, with the standard error format of OCaml: "File %S, line %d, characters %d-%d". - -since 4.02 -``` -val __LINE_OF__ : 'a -> int * 'a -``` -`__LINE_OF__ expr` returns a pair `(line, expr)`, where `line` is the line number at which the expression `expr` appears in the file currently being parsed by the compiler. - -since 4.02 -``` -val __POS_OF__ : 'a -> (string * int * int * int) * 'a -``` -`__POS_OF__ expr` returns a pair `(loc,expr)`, where `loc` is a tuple `(file,lnum,cnum,enum)` corresponding to the location at which the expression `expr` appears in the file currently being parsed by the compiler. `file` is the current filename, `lnum` the line number, `cnum` the character position in the line and `enum` the last character position in the line. - -since 4.02 - -## Composition operators - -``` -val (|>) : 'a -> ('a -> 'b) -> 'b -``` -Reverse-application operator: `x |> f |> g` is exactly equivalent to `g (f (x))`. Left-associative operator, see `Ocaml_operators` for more information. - -since 4.01 -``` -val (@@) : ('a -> 'b) -> 'a -> 'b -``` -Application operator: `g @@ f @@ x` is exactly equivalent to `g (f (x))`. Right-associative operator, see `Ocaml_operators` for more information. - -since 4.01 - -## Integer arithmetic - -Integers are `Sys.int_size` bits wide. All operations are taken modulo 2`Sys.int_size`. They do not fail on overflow. - -``` -val (~-) : int -> int -``` -Unary negation. You can also write `- e` instead of `~- e`. Unary operator, see `Ocaml_operators` for more information. - -``` -val (~+) : int -> int -``` -Unary addition. You can also write `+ e` instead of `~+ e`. Unary operator, see `Ocaml_operators` for more information. - -since 3.12 -``` -val succ : int -> int -``` -`succ x` is `x + 1`. - -``` -val pred : int -> int -``` -`pred x` is `x - 1`. - -``` -val (+) : int -> int -> int -``` -Integer addition. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (-) : int -> int -> int -``` -Integer subtraction. Left-associative operator, , see `Ocaml_operators` for more information. - -``` -val (*) : int -> int -> int -``` -Integer multiplication. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (/) : int -> int -> int -``` -Integer division. Integer division rounds the real quotient of its arguments towards zero. More precisely, if `x >= 0` and `y > 0`, `x / y` is the greatest integer less than or equal to the real quotient of `x` by `y`. Moreover, `(- x) / y = x / (- y) = - (x / y)`. Left-associative operator, see `Ocaml_operators` for more information. - -raises [`Division_by_zero`](./#exception-Division_by_zero) if the second argument is 0. -``` -val (mod) : int -> int -> int -``` -Integer remainder. If `y` is not zero, the result of `x mod y` satisfies the following properties: `x = (x / y) * y + x mod y` and `abs(x mod y) <= abs(y) - 1`. If `y = 0`, `x mod y` raises `Division_by_zero`. Note that `x mod y` is negative only if `x < 0`. Left-associative operator, see `Ocaml_operators` for more information. - -raises [`Division_by_zero`](./#exception-Division_by_zero) if y is zero. -``` -val abs : int -> int -``` -`abs x` is the absolute value of `x`. On `min_int` this is `min_int` itself and thus remains negative. - -``` -val max_int : int -``` -The greatest representable integer. - -``` -val min_int : int -``` -The smallest representable integer. - - -### Bitwise operations - -``` -val (land) : int -> int -> int -``` -Bitwise logical and. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (lor) : int -> int -> int -``` -Bitwise logical or. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (lxor) : int -> int -> int -``` -Bitwise logical exclusive or. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val lnot : int -> int -``` -Bitwise logical negation. - -``` -val (lsl) : int -> int -> int -``` -`n lsl m` shifts `n` to the left by `m` bits. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val (lsr) : int -> int -> int -``` -`n lsr m` shifts `n` to the right by `m` bits. This is a logical shift: zeroes are inserted regardless of the sign of `n`. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val (asr) : int -> int -> int -``` -`n asr m` shifts `n` to the right by `m` bits. This is an arithmetic shift: the sign bit of `n` is replicated. The result is unspecified if `m < 0` or `m > Sys.int_size`. Right-associative operator, see `Ocaml_operators` for more information. - - -## Floating-point arithmetic - -OCaml's floating-point numbers follow the IEEE 754 standard, using double precision (64 bits) numbers. Floating-point operations never raise an exception on overflow, underflow, division by zero, etc. Instead, special IEEE numbers are returned as appropriate, such as `infinity` for `1.0 /. 0.0`, `neg_infinity` for `-1.0 /. 0.0`, and `nan` ('not a number') for `0.0 /. 0.0`. These special numbers then propagate through floating-point computations as expected: for instance, `1.0 /. infinity` is `0.0`, basic arithmetic operations (`+.`, `-.`, `*.`, `/.`) with `nan` as an argument return `nan`, ... - -``` -val (~-.) : float -> float -``` -Unary negation. You can also write `-. e` instead of `~-. e`. Unary operator, see `Ocaml_operators` for more information. - -``` -val (~+.) : float -> float -``` -Unary addition. You can also write `+. e` instead of `~+. e`. Unary operator, see `Ocaml_operators` for more information. - -since 3.12 -``` -val (+.) : float -> float -> float -``` -Floating-point addition. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (-.) : float -> float -> float -``` -Floating-point subtraction. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (*.) : float -> float -> float -``` -Floating-point multiplication. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (/.) : float -> float -> float -``` -Floating-point division. Left-associative operator, see `Ocaml_operators` for more information. - -``` -val (**) : float -> float -> float -``` -Exponentiation. - -``` -val sqrt : float -> float -``` -Square root. - -``` -val exp : float -> float -``` -Exponential. - -``` -val log : float -> float -``` -Natural logarithm. - -``` -val log10 : float -> float -``` -Base 10 logarithm. - -``` -val expm1 : float -> float -``` -`expm1 x` computes `exp x -. 1.0`, giving numerically-accurate results even if `x` is close to `0.0`. - -since 3.12.0 -``` -val log1p : float -> float -``` -`log1p x` computes `log(1.0 +. x)` (natural logarithm), giving numerically-accurate results even if `x` is close to `0.0`. - -since 3.12.0 -``` -val cos : float -> float -``` -Cosine. Argument is in radians. - -``` -val sin : float -> float -``` -Sine. Argument is in radians. - -``` -val tan : float -> float -``` -Tangent. Argument is in radians. - -``` -val acos : float -> float -``` -Arc cosine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `0.0` and `pi`. - -``` -val asin : float -> float -``` -Arc sine. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan : float -> float -``` -Arc tangent. Result is in radians and is between `-pi/2` and `pi/2`. - -``` -val atan2 : float -> float -> float -``` -`atan2 y x` returns the arc tangent of `y /. x`. The signs of `x` and `y` are used to determine the quadrant of the result. Result is in radians and is between `-pi` and `pi`. - -``` -val hypot : float -> float -> float -``` -`hypot x y` returns `sqrt(x *. x + y *. y)`, that is, the length of the hypotenuse of a right-angled triangle with sides of length `x` and `y`, or, equivalently, the distance of the point `(x,y)` to origin. - -since 4.00.0 -``` -val cosh : float -> float -``` -Hyperbolic cosine. Argument is in radians. - -``` -val sinh : float -> float -``` -Hyperbolic sine. Argument is in radians. - -``` -val tanh : float -> float -``` -Hyperbolic tangent. Argument is in radians. - -``` -val acosh : float -> float -``` -Hyperbolic arc cosine. The argument must fall within the range `[1.0, inf]`. Result is in radians and is between `0.0` and `inf`. - -since 4.13.0 -``` -val asinh : float -> float -``` -Hyperbolic arc sine. The argument and result range over the entire real line. Result is in radians. - -since 4.13.0 -``` -val atanh : float -> float -``` -Hyperbolic arc tangent. The argument must fall within the range `[-1.0, 1.0]`. Result is in radians and ranges over the entire real line. - -since 4.13.0 -``` -val ceil : float -> float -``` -Round above to an integer value. `ceil f` returns the least integer value greater than or equal to `f`. The result is returned as a float. - -``` -val floor : float -> float -``` -Round below to an integer value. `floor f` returns the greatest integer value less than or equal to `f`. The result is returned as a float. - -``` -val abs_float : float -> float -``` -`abs_float f` returns the absolute value of `f`. - -``` -val copysign : float -> float -> float -``` -`copysign x y` returns a float whose absolute value is that of `x` and whose sign is that of `y`. If `x` is `nan`, returns `nan`. If `y` is `nan`, returns either `x` or `-. x`, but it is not specified which. - -since 4.00 -``` -val mod_float : float -> float -> float -``` -`mod_float a b` returns the remainder of `a` with respect to `b`. The returned value is `a -. n *. b`, where `n` is the quotient `a /. b` rounded towards zero to an integer. - -``` -val frexp : float -> float * int -``` -`frexp f` returns the pair of the significant and the exponent of `f`. When `f` is zero, the significant `x` and the exponent `n` of `f` are equal to zero. When `f` is non-zero, they are defined by `f = x *. 2 ** n` and `0.5 <= x < 1.0`. - -``` -val ldexp : float -> int -> float -``` -`ldexp x n` returns `x *. 2 ** n`. - -``` -val modf : float -> float * float -``` -`modf f` returns the pair of the fractional and integral part of `f`. - -``` -val float : int -> float -``` -Same as [`Stdlib.float_of_int`](./#val-float_of_int). - -``` -val float_of_int : int -> float -``` -Convert an integer to floating-point. - -``` -val truncate : float -> int -``` -Same as [`Stdlib.int_of_float`](./#val-int_of_float). - -``` -val int_of_float : float -> int -``` -Truncate the given floating-point number to an integer. The result is unspecified if the argument is `nan` or falls outside the range of representable integers. - -``` -val infinity : float -``` -Positive infinity. - -``` -val neg_infinity : float -``` -Negative infinity. - -``` -val nan : float -``` -``` -val max_float : float -``` -The largest positive finite value of type `float`. - -``` -val min_float : float -``` -The smallest positive, non-zero, non-denormalized value of type `float`. - -``` -val epsilon_float : float -``` -The difference between `1.0` and the smallest exactly representable floating-point number greater than `1.0`. - -``` -type fpclass = -``` -``` -| FP_normal -``` -Normal number, none of the below - -``` -| FP_subnormal -``` -Number very close to 0.0, has reduced precision - -``` -| FP_zero -``` -Number is 0.0 or \-0.0 - -``` -| FP_infinite -``` -Number is positive or negative infinity - -``` -| FP_nan -``` -Not a number: result of an undefined operation - -``` - -``` -The five classes of floating-point numbers, as determined by the [`Stdlib.classify_float`](./#val-classify_float) function. - -``` -val classify_float : float -> fpclass -``` - -## String operations - -More string operations are provided in module [`String`](./Stdlib-String.md). - -``` -val (^) : string -> string -> string -``` -String concatenation. Right-associative operator, see `Ocaml_operators` for more information. - -raises [`Invalid_argument`](./#exception-Invalid_argument) if the result is longer then than Sys.max\_string\_length bytes. - -## Character operations - -More character operations are provided in module [`Char`](./Stdlib-Char.md). - -``` -val int_of_char : char -> int -``` -Return the ASCII code of the argument. - -``` -val char_of_int : int -> char -``` -Return the character with the given ASCII code. - -raises [`Invalid_argument`](./#exception-Invalid_argument) if the argument is outside the range 0--255. - -## Unit operations - -``` -val ignore : 'a -> unit -``` -Discard the value of its argument and return `()`. For instance, `ignore(f x)` discards the result of the side-effecting function `f`. It is equivalent to `f x; ()`, except that the latter may generate a compiler warning; writing `ignore(f x)` instead avoids the warning. - - -## String conversion functions - -``` -val string_of_bool : bool -> string -``` -Return the string representation of a boolean. As the returned values may be shared, the user should not modify them directly. - -``` -val bool_of_string_opt : string -> bool option -``` -Convert the given string to a boolean. - -Return `None` if the string is not `"true"` or `"false"`. - -since 4.05 -``` -val bool_of_string : string -> bool -``` -Same as [`Stdlib.bool_of_string_opt`](./#val-bool_of_string_opt), but raise `Invalid_argument "bool_of_string"` instead of returning `None`. - -``` -val string_of_int : int -> string -``` -Return the string representation of an integer, in decimal. - -``` -val int_of_string_opt : string -> int option -``` -Convert the given string to an integer. The string is read in decimal (by default, or if the string begins with `0u`), in hexadecimal (if it begins with `0x` or `0X`), in octal (if it begins with `0o` or `0O`), or in binary (if it begins with `0b` or `0B`). - -The `0u` prefix reads the input as an unsigned integer in the range `[0, 2*max_int+1]`. If the input exceeds [`max_int`](./#val-max_int) it is converted to the signed integer `min_int + input - max_int - 1`. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -Return `None` if the given string is not a valid representation of an integer, or if the integer represented exceeds the range of integers representable in type `int`. - -since 4.05 -``` -val int_of_string : string -> int -``` -Same as [`Stdlib.int_of_string_opt`](./#val-int_of_string_opt), but raise `Failure "int_of_string"` instead of returning `None`. - -``` -val string_of_float : float -> string -``` -Return a string representation of a floating-point number. - -This conversion can involve a loss of precision. For greater control over the manner in which the number is printed, see [`Printf`](./Stdlib-Printf.md). - -``` -val float_of_string_opt : string -> float option -``` -Convert the given string to a float. The string is read in decimal (by default) or in hexadecimal (marked by `0x` or `0X`). - -The format of decimal floating-point numbers is ` [-] dd.ddd (e|E) [+|-] dd `, where `d` stands for a decimal digit. - -The format of hexadecimal floating-point numbers is ` [-] 0(x|X) hh.hhh (p|P) [+|-] dd `, where `h` stands for an hexadecimal digit and `d` for a decimal digit. - -In both cases, at least one of the integer and fractional parts must be given; the exponent part is optional. - -The `_` (underscore) character can appear anywhere in the string and is ignored. - -Depending on the execution platforms, other representations of floating-point numbers can be accepted, but should not be relied upon. - -Return `None` if the given string is not a valid representation of a float. - -since 4.05 -``` -val float_of_string : string -> float -``` -Same as [`Stdlib.float_of_string_opt`](./#val-float_of_string_opt), but raise `Failure "float_of_string"` instead of returning `None`. - - -## Pair operations - -``` -val fst : ('a * 'b) -> 'a -``` -Return the first component of a pair. - -``` -val snd : ('a * 'b) -> 'b -``` -Return the second component of a pair. - - -## List operations - -More list operations are provided in module [`List`](./Stdlib-List.md). - -``` -val (@) : 'a list -> 'a list -> 'a list -``` -`l0 @ l1` appends `l1` to `l0`. Same function as [`List.append`](./Stdlib-List.md#val-append). Right-associative operator, see `Ocaml_operators` for more information. - -since 5.1 this function is tail-recursive. - -## Input/output - -Note: all input/output functions can raise `Sys_error` when the system calls they invoke fail. - -``` -type in_channel -``` -The type of input channel. - -``` -type out_channel -``` -The type of output channel. - -``` -val stdin : in_channel -``` -The standard input for the process. - -``` -val stdout : out_channel -``` -The standard output for the process. - -``` -val stderr : out_channel -``` -The standard error output for the process. - - -### Output functions on standard output - -``` -val print_char : char -> unit -``` -Print a character on standard output. - -``` -val print_string : string -> unit -``` -Print a string on standard output. - -``` -val print_bytes : bytes -> unit -``` -Print a byte sequence on standard output. - -since 4.02 -``` -val print_int : int -> unit -``` -Print an integer, in decimal, on standard output. - -``` -val print_float : float -> unit -``` -Print a floating-point number, in decimal, on standard output. - -The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. - -``` -val print_endline : string -> unit -``` -Print a string, followed by a newline character, on standard output and flush standard output. - -``` -val print_newline : unit -> unit -``` -Print a newline character on standard output, and flush standard output. This can be used to simulate line buffering of standard output. - - -### Output functions on standard error - -``` -val prerr_char : char -> unit -``` -Print a character on standard error. - -``` -val prerr_string : string -> unit -``` -Print a string on standard error. - -``` -val prerr_bytes : bytes -> unit -``` -Print a byte sequence on standard error. - -since 4.02 -``` -val prerr_int : int -> unit -``` -Print an integer, in decimal, on standard error. - -``` -val prerr_float : float -> unit -``` -Print a floating-point number, in decimal, on standard error. - -The conversion of the number to a string uses [`string_of_float`](./#val-string_of_float) and can involve a loss of precision. - -``` -val prerr_endline : string -> unit -``` -Print a string, followed by a newline character on standard error and flush standard error. - -``` -val prerr_newline : unit -> unit -``` -Print a newline character on standard error, and flush standard error. - - -### Input functions on standard input - -``` -val read_line : unit -> string -``` -Flush standard output, then read characters from standard input until a newline character is encountered. - -Return the string of all characters read, without the newline character at the end. - -raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. -``` -val read_int_opt : unit -> int option -``` -Flush standard output, then read one line from standard input and convert it to an integer. - -Return `None` if the line read is not a valid representation of an integer. - -since 4.05 -``` -val read_int : unit -> int -``` -Same as [`Stdlib.read_int_opt`](./#val-read_int_opt), but raise `Failure "int_of_string"` instead of returning `None`. - -``` -val read_float_opt : unit -> float option -``` -Flush standard output, then read one line from standard input and convert it to a floating-point number. - -Return `None` if the line read is not a valid representation of a floating-point number. - -since 4.05 -``` -val read_float : unit -> float -``` -Same as [`Stdlib.read_float_opt`](./#val-read_float_opt), but raise `Failure "float_of_string"` instead of returning `None`. - - -### General output functions - -``` -type open_flag = -``` -``` -| Open_rdonly -``` -open for reading. - -``` -| Open_wronly -``` -open for writing. - -``` -| Open_append -``` -open for appending: always write at end of file. - -``` -| Open_creat -``` -create the file if it does not exist. - -``` -| Open_trunc -``` -empty the file if it already exists. - -``` -| Open_excl -``` -fail if Open\_creat and the file already exists. - -``` -| Open_binary -``` -open in binary mode (no conversion). - -``` -| Open_text -``` -open in text mode (may perform conversions). - -``` -| Open_nonblock -``` -open in non-blocking mode. - -``` - -``` -Opening modes for [`Stdlib.open_out_gen`](./#val-open_out_gen) and [`Stdlib.open_in_gen`](./#val-open_in_gen). - -``` -val open_out : string -> out_channel -``` -Open the named file for writing, and return a new output channel on that file, positioned at the beginning of the file. The file is truncated to zero length if it already exists. It is created if it does not already exists. - -``` -val open_out_bin : string -> out_channel -``` -Same as [`Stdlib.open_out`](./#val-open_out), but the file is opened in binary mode, so that no translation takes place during writes. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_out`](./#val-open_out). - -``` -val open_out_gen : open_flag list -> int -> string -> out_channel -``` -`open_out_gen mode perm filename` opens the named file for writing, as described above. The extra argument `mode` specifies the opening mode. The extra argument `perm` specifies the file permissions, in case the file must be created. [`Stdlib.open_out`](./#val-open_out) and [`Stdlib.open_out_bin`](./#val-open_out_bin) are special cases of this function. - -``` -val flush : out_channel -> unit -``` -Flush the buffer associated with the given output channel, performing all pending writes on that channel. Interactive programs must be careful about flushing standard output and standard error at the right time. - -``` -val flush_all : unit -> unit -``` -Flush all open output channels; ignore errors. - -``` -val output_char : out_channel -> char -> unit -``` -Write the character on the given output channel. - -``` -val output_string : out_channel -> string -> unit -``` -Write the string on the given output channel. - -``` -val output_bytes : out_channel -> bytes -> unit -``` -Write the byte sequence on the given output channel. - -since 4.02 -``` -val output : out_channel -> bytes -> int -> int -> unit -``` -`output oc buf pos len` writes `len` characters from byte sequence `buf`, starting at offset `pos`, to the given output channel `oc`. - -raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val output_substring : out_channel -> string -> int -> int -> unit -``` -Same as `output` but take a string as argument instead of a byte sequence. - -since 4.02 -``` -val output_byte : out_channel -> int -> unit -``` -Write one 8-bit integer (as the single character with that code) on the given output channel. The given integer is taken modulo 256. - -``` -val output_binary_int : out_channel -> int -> unit -``` -Write one integer in binary format (4 bytes, big-endian) on the given output channel. The given integer is taken modulo 232. The only reliable way to read it back is through the [`Stdlib.input_binary_int`](./#val-input_binary_int) function. The format is compatible across all machines for a given version of OCaml. - -``` -val output_value : out_channel -> 'a -> unit -``` -Write the representation of a structured value of any type to a channel. Circularities and sharing inside the value are detected and preserved. The object can be read back, by the function [`Stdlib.input_value`](./#val-input_value). See the description of module [`Marshal`](./Stdlib-Marshal.md) for more information. [`Stdlib.output_value`](./#val-output_value) is equivalent to [`Marshal.to_channel`](./Stdlib-Marshal.md#val-to_channel) with an empty list of flags. - -``` -val seek_out : out_channel -> int -> unit -``` -`seek_out chan pos` sets the current writing position to `pos` for channel `chan`. This works only for regular files. On files of other kinds (such as terminals, pipes and sockets), the behavior is unspecified. - -``` -val pos_out : out_channel -> int -``` -Return the current writing position for the given channel. Does not work on channels opened with the `Open_append` flag (returns unspecified results). For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_out`, then going back to this position using `seek_out` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - -``` -val out_channel_length : out_channel -> int -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. - -``` -val close_out : out_channel -> unit -``` -Close the given channel, flushing all buffered write operations. Output functions raise a `Sys_error` exception when they are applied to a closed output channel, except `close_out` and `flush`, which do nothing when applied to an already closed channel. Note that `close_out` may raise `Sys_error` if the operating system signals an error when flushing or closing. - -``` -val close_out_noerr : out_channel -> unit -``` -Same as `close_out`, but ignore all errors. - -``` -val set_binary_mode_out : out_channel -> bool -> unit -``` -`set_binary_mode_out oc true` sets the channel `oc` to binary mode: no translations take place during output. `set_binary_mode_out oc false` sets the channel `oc` to text mode: depending on the operating system, some translations may take place during output. For instance, under Windows, end-of-lines will be translated from `\n` to `\r\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. - - -### General input functions - -``` -val open_in : string -> in_channel -``` -Open the named file for reading, and return a new input channel on that file, positioned at the beginning of the file. - -``` -val open_in_bin : string -> in_channel -``` -Same as [`Stdlib.open_in`](./#val-open_in), but the file is opened in binary mode, so that no translation takes place during reads. On operating systems that do not distinguish between text mode and binary mode, this function behaves like [`Stdlib.open_in`](./#val-open_in). - -``` -val open_in_gen : open_flag list -> int -> string -> in_channel -``` -`open_in_gen mode perm filename` opens the named file for reading, as described above. The extra arguments `mode` and `perm` specify the opening mode and file permissions. [`Stdlib.open_in`](./#val-open_in) and [`Stdlib.open_in_bin`](./#val-open_in_bin) are special cases of this function. - -``` -val input_char : in_channel -> char -``` -Read one character from the given input channel. - -raises [`End_of_file`](./#exception-End_of_file) if there are no more characters to read. -``` -val input_line : in_channel -> string -``` -Read characters from the given input channel, until a newline character is encountered. Return the string of all characters read, without the newline character at the end. - -raises [`End_of_file`](./#exception-End_of_file) if the end of the file is reached at the beginning of line. -``` -val input : in_channel -> bytes -> int -> int -> int -``` -`input ic buf pos len` reads up to `len` characters from the given channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. It returns the actual number of characters read, between 0 and `len` (inclusive). A return value of 0 means that the end of file was reached. A return value between 0 and `len` exclusive means that not all requested `len` characters were read, either because no more characters were available at that time, or because the implementation found it convenient to do a partial read; `input` must be called again to read the remaining characters, if desired. (See also [`Stdlib.really_input`](./#val-really_input) for reading exactly `len` characters.) Exception `Invalid_argument "input"` is raised if `pos` and `len` do not designate a valid range of `buf`. - -``` -val really_input : in_channel -> bytes -> int -> int -> unit -``` -`really_input ic buf pos len` reads `len` characters from channel `ic`, storing them in byte sequence `buf`, starting at character number `pos`. - -raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. -raises [`Invalid_argument`](./#exception-Invalid_argument) if pos and len do not designate a valid range of buf. -``` -val really_input_string : in_channel -> int -> string -``` -`really_input_string ic len` reads `len` characters from channel `ic` and returns them in a new string. - -raises [`End_of_file`](./#exception-End_of_file) if the end of file is reached before len characters have been read. -since 4.02 -``` -val input_byte : in_channel -> int -``` -Same as [`Stdlib.input_char`](./#val-input_char), but return the 8-bit integer representing the character. - -raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached. -``` -val input_binary_int : in_channel -> int -``` -Read an integer encoded in binary format (4 bytes, big-endian) from the given input channel. See [`Stdlib.output_binary_int`](./#val-output_binary_int). - -raises [`End_of_file`](./#exception-End_of_file) if the end of file was reached while reading the integer. -``` -val input_value : in_channel -> 'a -``` -Read the representation of a structured value, as produced by [`Stdlib.output_value`](./#val-output_value), and return the corresponding value. This function is identical to [`Marshal.from_channel`](./Stdlib-Marshal.md#val-from_channel); see the description of module [`Marshal`](./Stdlib-Marshal.md) for more information, in particular concerning the lack of type safety. - -``` -val seek_in : in_channel -> int -> unit -``` -`seek_in chan pos` sets the current reading position to `pos` for channel `chan`. This works only for regular files. On files of other kinds, the behavior is unspecified. - -``` -val pos_in : in_channel -> int -``` -Return the current reading position for the given channel. For files opened in text mode under Windows, the returned position is approximate (owing to end-of-line conversion); in particular, saving the current position with `pos_in`, then going back to this position using `seek_in` will not work. For this programming idiom to work reliably and portably, the file must be opened in binary mode. - -``` -val in_channel_length : in_channel -> int -``` -Return the size (number of characters) of the regular file on which the given channel is opened. If the channel is opened on a file that is not a regular file, the result is meaningless. The returned size does not take into account the end-of-line translations that can be performed when reading from a channel opened in text mode. - -``` -val close_in : in_channel -> unit -``` -Close the given channel. Input functions raise a `Sys_error` exception when they are applied to a closed input channel, except `close_in`, which does nothing when applied to an already closed channel. - -``` -val close_in_noerr : in_channel -> unit -``` -Same as `close_in`, but ignore all errors. - -``` -val set_binary_mode_in : in_channel -> bool -> unit -``` -`set_binary_mode_in ic true` sets the channel `ic` to binary mode: no translations take place during input. `set_binary_mode_out ic false` sets the channel `ic` to text mode: depending on the operating system, some translations may take place during input. For instance, under Windows, end-of-lines will be translated from `\r\n` to `\n`. This function has no effect under operating systems that do not distinguish between text mode and binary mode. - - -### Operations on large files - -``` -module LargeFile : sig ... end -``` -Operations on large files. This sub-module provides 64-bit variants of the channel functions that manipulate file positions and file sizes. By representing positions and sizes by 64-bit integers (type `int64`) instead of regular integers (type `int`), these alternate functions allow operating on files whose sizes are greater than `max_int`. - - -## References - -``` -type 'a ref = { -``` -`mutable contents : 'a;` -``` -} -``` -The type of references (mutable indirection cells) containing a value of type `'a`. - -``` -val ref : 'a -> 'a ref -``` -Return a fresh reference containing the given value. - -``` -val (!) : 'a ref -> 'a -``` -`!r` returns the current contents of reference `r`. Equivalent to `fun r -> r.contents`. Unary operator, see `Ocaml_operators` for more information. - -``` -val (:=) : 'a ref -> 'a -> unit -``` -`r := a` stores the value of `a` in reference `r`. Equivalent to `fun r v -> r.contents <- v`. Right-associative operator, see `Ocaml_operators` for more information. - -``` -val incr : int ref -> unit -``` -Increment the integer contained in the given reference. Equivalent to `fun r -> r := succ !r`. - -``` -val decr : int ref -> unit -``` -Decrement the integer contained in the given reference. Equivalent to `fun r -> r := pred !r`. - - -## Result type - -``` -type ('a, 'b) result = -``` -``` -| Ok of 'a -``` -``` -| Error of 'b -``` -``` - -``` -since 4.03 - -## Operations on format strings - -Format strings are character strings with special lexical conventions that defines the functionality of formatted input/output functions. Format strings are used to read data with formatted input functions from module [`Scanf`](./Stdlib-Scanf.md) and to print data with formatted output functions from modules [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). - -Format strings are made of three kinds of entities: - -- *conversions specifications*, introduced by the special character `'%'` followed by one or more characters specifying what kind of argument to read or print, -- *formatting indications*, introduced by the special character `'@'` followed by one or more characters specifying how to read or print the argument, -- *plain characters* that are regular characters with usual lexical conventions. Plain characters specify string literals to be read in the input or printed in the output. -There is an additional lexical rule to escape the special characters `'%'` and `'@'` in format strings: if a special character follows a `'%'` character, it is treated as a plain character. In other words, `"%%"` is considered as a plain `'%'` and `"%@"` as a plain `'@'`. - -For more information about conversion specifications and formatting indications available, read the documentation of modules [`Scanf`](./Stdlib-Scanf.md), [`Printf`](./Stdlib-Printf.md) and [`Format`](./Stdlib-Format.md). - -Format strings have a general and highly polymorphic type `('a, 'b, 'c, 'd, 'e, 'f) format6`. The two simplified types, `format` and `format4` below are included for backward compatibility with earlier releases of OCaml. - -The meaning of format string type parameters is as follows: - -- `'a` is the type of the parameters of the format for formatted output functions (`printf`\-style functions); `'a` is the type of the values read by the format for formatted input functions (`scanf`\-style functions). -- `'b` is the type of input source for formatted input functions and the type of output target for formatted output functions. For `printf`\-style functions from module [`Printf`](./Stdlib-Printf.md), `'b` is typically `out_channel`; for `printf`\-style functions from module [`Format`](./Stdlib-Format.md), `'b` is typically [`Format.formatter`](./Stdlib-Format.md#type-formatter); for `scanf`\-style functions from module [`Scanf`](./Stdlib-Scanf.md), `'b` is typically [`Scanf.Scanning.in_channel`](./Stdlib-Scanf-Scanning.md#type-in_channel). -Type argument `'b` is also the type of the first argument given to user's defined printing functions for `%a` and `%t` conversions, and user's defined reading functions for `%r` conversion. - -- `'c` is the type of the result of the `%a` and `%t` printing functions, and also the type of the argument transmitted to the first argument of `kprintf`\-style functions or to the `kscanf`\-style functions. -- `'d` is the type of parameters for the `scanf`\-style functions. -- `'e` is the type of the receiver function for the `scanf`\-style functions. -- `'f` is the final result type of a formatted input/output function invocation: for the `printf`\-style functions, it is typically `unit`; for the `scanf`\-style functions, it is typically the result type of the receiver function. -``` -type ('a, 'b, 'c, 'd, 'e, 'f) format6 = - ('a, 'b, 'c, 'd, 'e, 'f) CamlinternalFormatBasics.format6 -``` -``` -type ('a, 'b, 'c, 'd) format4 = ('a, 'b, 'c, 'c, 'c, 'd) format6 -``` -``` -type ('a, 'b, 'c) format = ('a, 'b, 'c, 'c) format4 -``` -``` -val string_of_format : ('a, 'b, 'c, 'd, 'e, 'f) format6 -> string -``` -Converts a format string into a string. - -``` -val format_of_string : - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - ('a, 'b, 'c, 'd, 'e, 'f) format6 -``` -`format_of_string s` returns a format string read from the string literal `s`. Note: `format_of_string` can not convert a string argument that is not a literal. If you need this functionality, use the more general [`Scanf.format_from_string`](./Stdlib-Scanf.md#val-format_from_string) function. - -``` -val (^^) : - ('a, 'b, 'c, 'd, 'e, 'f) format6 -> - ('f, 'b, 'c, 'e, 'g, 'h) format6 -> - ('a, 'b, 'c, 'd, 'g, 'h) format6 -``` -`f1 ^^ f2` catenates format strings `f1` and `f2`. The result is a format string that behaves as the concatenation of format strings `f1` and `f2`: in case of formatted output, it accepts arguments from `f1`, then arguments from `f2`; in case of formatted input, it returns results from `f1`, then results from `f2`. Right-associative operator, see `Ocaml_operators` for more information. - - -## Program termination - -``` -val exit : int -> 'a -``` -Terminate the process, returning the given status code to the operating system: usually 0 to indicate no errors, and a small positive integer to indicate failure. All open output channels are flushed with `flush_all`. The callbacks registered with [`Domain.at_exit`](./Stdlib-Domain.md#val-at_exit) are called followed by those registered with [`Stdlib.at_exit`](./#val-at_exit). - -An implicit `exit 0` is performed each time a program terminates normally. An implicit `exit 2` is performed if the program terminates early because of an uncaught exception. - -``` -val at_exit : (unit -> unit) -> unit -``` -Register the given function to be called at program termination time. The functions registered with `at_exit` will be called when the program does any of the following: - -- executes [`Stdlib.exit`](./#val-exit) -- terminates, either normally or because of an uncaught exception -- executes the C function `caml_shutdown`. The functions are called in 'last in, first out' order: the function most recently added with `at_exit` is called first. - -## Standard library modules - -``` -module Arg : sig ... end -``` -Parsing of command line arguments. - -``` -module Array : sig ... end -``` -Array operations. - -``` -module ArrayLabels : sig ... end -``` -Array operations. - -``` -module Atomic : sig ... end -``` -Atomic references. - -``` -module Bool : sig ... end -``` -Boolean values. - -``` -module Buffer : sig ... end -``` -Extensible buffers. - -``` -module Bytes : sig ... end -``` -Byte sequence operations. - -``` -module BytesLabels : sig ... end -``` -Byte sequence operations. - -``` -module Char : sig ... end -``` -Character operations. - -``` -module Complex : sig ... end -``` -Complex numbers. - -``` -module Digest : sig ... end -``` -Message digest. - -``` -module Domain : sig ... end -``` -``` -module Dynarray : sig ... end -``` -Dynamic arrays. - -``` -module Effect : sig ... end -``` -``` -module Either : sig ... end -``` -Either type. - -``` -module Filename : sig ... end -``` -Operations on file names. - -``` -module Float : sig ... end -``` -Floating-point arithmetic. - -``` -module Format : sig ... end -``` -Pretty-printing. - -``` -module Fun : sig ... end -``` -Function manipulation. - -``` -module Gc : sig ... end -``` -Memory management control and statistics; finalised values. - -``` -module Hashtbl : sig ... end -``` -Hash tables and hash functions. - -``` -module In_channel : sig ... end -``` -Input channels. - -``` -module Int : sig ... end -``` -Integer values. - -``` -module Int32 : sig ... end -``` -32-bit integers. - -``` -module Int64 : sig ... end -``` -64-bit integers. - -``` -module Lazy : sig ... end -``` -Deferred computations. - -``` -module Lexing : sig ... end -``` -The run-time library for lexers generated by `ocamllex`. - -``` -module List : sig ... end -``` -List operations. - -``` -module ListLabels : sig ... end -``` -List operations. - -``` -module Map : sig ... end -``` -Association tables over ordered types. - -``` -module Marshal : sig ... end -``` -Marshaling of data structures. - -``` -module MoreLabels : sig ... end -``` -Extra labeled libraries. - -``` -module Mutex : sig ... end -``` -Locks for mutual exclusion. - -``` -module Obj : sig ... end -``` -Operations on internal representations of values. - -``` -module Oo : sig ... end -``` -Operations on objects - -``` -module Option : sig ... end -``` -Option values. - -``` -module Out_channel : sig ... end -``` -Output channels. - -``` -module Parsing : sig ... end -``` -The run-time library for parsers generated by `ocamlyacc`. - -``` -module Printexc : sig ... end -``` -Facilities for printing exceptions and inspecting current call stack. - -``` -module Printf : sig ... end -``` -Formatted output functions. - -``` -module Queue : sig ... end -``` -First-in first-out queues. - -``` -module Random : sig ... end -``` -Pseudo-random number generators (PRNG). - -``` -module Result : sig ... end -``` -Result values. - -``` -module Scanf : sig ... end -``` -Formatted input functions. - -``` -module Seq : sig ... end -``` -Sequences. - -``` -module Set : sig ... end -``` -Sets over ordered types. - -``` -module Stack : sig ... end -``` -Last-in first-out stacks. - -``` -module StdLabels : sig ... end -``` -Standard labeled libraries. - -``` -module String : sig ... end -``` -Strings. - -``` -module StringLabels : sig ... end -``` -Strings. - -``` -module Sys : sig ... end -``` -System interface. - -``` -module Type : sig ... end -``` -Type introspection. - -``` -module Uchar : sig ... end -``` -Unicode characters. - -``` -module Unit : sig ... end -``` -Unit values. - -``` -module Weak : sig ... end -``` -Arrays of weak pointers and hash sets of weak pointers. From 66fb0cc77a2bbbad4f61e54c1e6d385fec87caef Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Fri, 5 Sep 2025 13:32:58 +0200 Subject: [PATCH 12/19] Copy markdown from _build folder --- Makefile | 4 ++++ documentation-site.opam.template | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 0c5b8752a..f2e0372a3 100644 --- a/Makefile +++ b/Makefile @@ -91,5 +91,9 @@ pull-melange-docs: ## Pull melange docs cd melange.dev dune build @doc-markdown cd .. + rm -rf docs/api/ml + cp -r _build/default/_doc/_markdown/melange/ docs/api/ml cd melange.dev ODOC_SYNTAX="re" dune build @doc-markdown + rm -rf docs/api/re + cp -r _build/default/_doc/_markdown/melange/ docs/api/re diff --git a/documentation-site.opam.template b/documentation-site.opam.template index d3e2d61c8..b8a7818e1 100644 --- a/documentation-site.opam.template +++ b/documentation-site.opam.template @@ -4,5 +4,5 @@ pin-depends: [ ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] - ["dune.dev" "git+https://github.com/davesnx/dune.git#74cd7f053526cb4409a44f75f0a8505d100f51b4"] + ["dune.dev" "git+https://github.com/davesnx/dune.git#e2e04ac9da46185268c50b73f702973b483ed139"] ] From 25331e21d028c33c2d8ccb4f7fe9c6e23cce0a9a Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 18 Sep 2025 11:26:31 +0200 Subject: [PATCH 13/19] Remove ppxlib version --- Makefile | 8 ++------ documentation-site.opam | 1 - 2 files changed, 2 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index f2e0372a3..91232bcde 100644 --- a/Makefile +++ b/Makefile @@ -85,15 +85,11 @@ preview: ## Preview the docs .PHONY: pull-melange-docs pull-melange-docs: ## Pull melange docs - if [ ! -d "melange.dev" ]; then \ - opam source melange; \ - fi - cd melange.dev + opam reinstall -y melange --with-doc dune build @doc-markdown - cd .. rm -rf docs/api/ml cp -r _build/default/_doc/_markdown/melange/ docs/api/ml - cd melange.dev + opam reinstall -y melange --with-doc ODOC_SYNTAX="re" dune build @doc-markdown rm -rf docs/api/re cp -r _build/default/_doc/_markdown/melange/ docs/api/re diff --git a/documentation-site.opam b/documentation-site.opam index 6d19366b1..f7f16b592 100644 --- a/documentation-site.opam +++ b/documentation-site.opam @@ -27,7 +27,6 @@ depends: [ "odoc-parser" {dev} "melange-playground" {dev} "ocaml-lsp-server" {dev} - "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} From e2985f3f8fee4bbdbd19a669a3976f6d9f2476a7 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 18 Sep 2025 12:11:06 +0200 Subject: [PATCH 14/19] Install melange 501-53 --- Makefile | 5 +++-- documentation-site.opam | 3 +-- documentation-site.opam.template | 2 -- dune-project | 1 + 4 files changed, 5 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 91232bcde..158306dd8 100644 --- a/Makefile +++ b/Makefile @@ -85,11 +85,12 @@ preview: ## Preview the docs .PHONY: pull-melange-docs pull-melange-docs: ## Pull melange docs - opam reinstall -y melange --with-doc + if [ ! -d "melange.dev" ]; then \ + opam source melange \ + fi dune build @doc-markdown rm -rf docs/api/ml cp -r _build/default/_doc/_markdown/melange/ docs/api/ml - opam reinstall -y melange --with-doc ODOC_SYNTAX="re" dune build @doc-markdown rm -rf docs/api/re cp -r _build/default/_doc/_markdown/melange/ docs/api/re diff --git a/documentation-site.opam b/documentation-site.opam index f7f16b592..b93743bd5 100644 --- a/documentation-site.opam +++ b/documentation-site.opam @@ -44,9 +44,8 @@ build: [ ] dev-repo: "git+https://github.com/melange-re/melange-re.github.io.git" pin-depends: [ - ["melange.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] - ["melange-playground.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] + ["dune.dev" "git+https://github.com/davesnx/dune.git#e2e04ac9da46185268c50b73f702973b483ed139"] ] diff --git a/documentation-site.opam.template b/documentation-site.opam.template index b8a7818e1..a5f82d2be 100644 --- a/documentation-site.opam.template +++ b/documentation-site.opam.template @@ -1,6 +1,4 @@ pin-depends: [ - ["melange.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] - ["melange-playground.dev" "git+https://github.com/melange-re/melange.git#973fa8d80c55ea31e468bae390da2200580ddda6"] ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] diff --git a/dune-project b/dune-project index 3f510fe8d..369f9aed5 100644 --- a/dune-project +++ b/dune-project @@ -29,6 +29,7 @@ reason-react-ppx ocamlformat js_of_ocaml + (melange (= "5.0.1-53")) (cmarkit :dev) (melange :dev) (odoc :dev) From db7cd53046d7c2b4faabe7f856e4cd244843c013 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Thu, 18 Sep 2025 14:16:07 +0200 Subject: [PATCH 15/19] Install melange 501-53 --- Makefile | 8 ++++---- documentation-site.opam | 2 +- dune-project | 3 +-- 3 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Makefile b/Makefile index 158306dd8..5d05ea68b 100644 --- a/Makefile +++ b/Makefile @@ -85,12 +85,12 @@ preview: ## Preview the docs .PHONY: pull-melange-docs pull-melange-docs: ## Pull melange docs - if [ ! -d "melange.dev" ]; then \ - opam source melange \ + if [ ! -d "vendor/melange" ]; then \ + opam source melange.$$(opam show melange -f version) --dir vendor/melange; \ fi dune build @doc-markdown rm -rf docs/api/ml - cp -r _build/default/_doc/_markdown/melange/ docs/api/ml + cp -r _build/default/_doc/_markdown/melange/ docs/api/ml/melange ODOC_SYNTAX="re" dune build @doc-markdown rm -rf docs/api/re - cp -r _build/default/_doc/_markdown/melange/ docs/api/re + cp -r _build/default/_doc/_markdown/melange/ docs/api/re/melange diff --git a/documentation-site.opam b/documentation-site.opam index b93743bd5..ddf91bd0e 100644 --- a/documentation-site.opam +++ b/documentation-site.opam @@ -22,7 +22,7 @@ depends: [ "ocamlformat" "js_of_ocaml" "cmarkit" {dev} - "melange" {dev} + "melange" {= "5.0.1-53"} "odoc" {dev} "odoc-parser" {dev} "melange-playground" {dev} diff --git a/dune-project b/dune-project index 369f9aed5..57e524ae0 100644 --- a/dune-project +++ b/dune-project @@ -29,9 +29,8 @@ reason-react-ppx ocamlformat js_of_ocaml - (melange (= "5.0.1-53")) (cmarkit :dev) - (melange :dev) + (melange (= "5.0.1-53")) (odoc :dev) (odoc-parser :dev) (melange-playground :dev) From 68dadf36b16b423d2ccd38c7b9d80ec77b371e54 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Fri, 19 Sep 2025 14:31:31 +0200 Subject: [PATCH 16/19] Cleanup deps --- .gitignore | 2 +- Makefile | 7 +++---- documentation-site.opam | 8 ++------ documentation-site.opam.template | 4 +--- dune-project | 3 --- 5 files changed, 7 insertions(+), 17 deletions(-) diff --git a/.gitignore b/.gitignore index b70010a93..a7385a610 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,4 @@ docs/.vitepress/cache docs/.vitepress/dist docs/public/playground -melange.dev +melange diff --git a/Makefile b/Makefile index 5d05ea68b..e2f90430d 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,6 @@ project_name = documentation-site DUNE = opam exec -- dune - .DEFAULT_GOAL := help .PHONY: help @@ -13,7 +12,7 @@ help: ## Print this help message .PHONY: create-switch create-switch: ## Create opam switch - opam switch create . 5.3.0 -y --deps-only + opam switch create . 5.3.0 -y --deps-only --no-install .PHONY: init init: create-switch install ## Configure everything to develop this repository in local @@ -85,8 +84,8 @@ preview: ## Preview the docs .PHONY: pull-melange-docs pull-melange-docs: ## Pull melange docs - if [ ! -d "vendor/melange" ]; then \ - opam source melange.$$(opam show melange -f version) --dir vendor/melange; \ + if [ ! -d "melange" ]; then \ + opam source melange.$$(opam show melange -f version) --dir melange; \ fi dune build @doc-markdown rm -rf docs/api/ml diff --git a/documentation-site.opam b/documentation-site.opam index ddf91bd0e..e514a21f7 100644 --- a/documentation-site.opam +++ b/documentation-site.opam @@ -22,11 +22,9 @@ depends: [ "ocamlformat" "js_of_ocaml" "cmarkit" {dev} - "melange" {= "5.0.1-53"} "odoc" {dev} - "odoc-parser" {dev} - "melange-playground" {dev} "ocaml-lsp-server" {dev} + "odoc" {with-doc} ] build: [ ["dune" "subst"] {dev} @@ -44,8 +42,6 @@ build: [ ] dev-repo: "git+https://github.com/melange-re/melange-re.github.io.git" pin-depends: [ - ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] - ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] - ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] ["dune.dev" "git+https://github.com/davesnx/dune.git#e2e04ac9da46185268c50b73f702973b483ed139"] + ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ] diff --git a/documentation-site.opam.template b/documentation-site.opam.template index a5f82d2be..52e5df0c4 100644 --- a/documentation-site.opam.template +++ b/documentation-site.opam.template @@ -1,6 +1,4 @@ pin-depends: [ - ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] - ["odoc.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] - ["odoc-parser.dev" "git+https://github.com/davesnx/odoc.git#d03bd566013841bcc83af9d964859f1aa8a30324"] ["dune.dev" "git+https://github.com/davesnx/dune.git#e2e04ac9da46185268c50b73f702973b483ed139"] + ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ] diff --git a/dune-project b/dune-project index 57e524ae0..7bad1bce3 100644 --- a/dune-project +++ b/dune-project @@ -30,8 +30,5 @@ ocamlformat js_of_ocaml (cmarkit :dev) - (melange (= "5.0.1-53")) (odoc :dev) - (odoc-parser :dev) - (melange-playground :dev) (ocaml-lsp-server :dev))) From b093bff4f3811fa36159957f64f478306df2a33c Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Fri, 19 Sep 2025 20:51:57 +0200 Subject: [PATCH 17/19] Remove odoc {dev} --- documentation-site.opam | 1 - dune-project | 1 - 2 files changed, 2 deletions(-) diff --git a/documentation-site.opam b/documentation-site.opam index e514a21f7..45f7808f1 100644 --- a/documentation-site.opam +++ b/documentation-site.opam @@ -22,7 +22,6 @@ depends: [ "ocamlformat" "js_of_ocaml" "cmarkit" {dev} - "odoc" {dev} "ocaml-lsp-server" {dev} "odoc" {with-doc} ] diff --git a/dune-project b/dune-project index 7bad1bce3..004f6f686 100644 --- a/dune-project +++ b/dune-project @@ -30,5 +30,4 @@ ocamlformat js_of_ocaml (cmarkit :dev) - (odoc :dev) (ocaml-lsp-server :dev))) From c16aca020b5d5e4b6b9f9c477762c857a36a81a5 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Fri, 19 Sep 2025 20:53:29 +0200 Subject: [PATCH 18/19] Remove dune-project --- dune-project | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/dune-project b/dune-project index 004f6f686..69c2d1b9c 100644 --- a/dune-project +++ b/dune-project @@ -2,32 +2,4 @@ (using melange 0.1) -(generate_opam_files true) - (name documentation-site) - -(license MIT) -(maintainers - "Antonio Nuno Monteiro " - "Javier Chávarri ") -(authors - "Antonio Nuno Monteiro " - "Javier Chávarri ") - -(source - (github melange-re/melange-re.github.io)) - -(package - (name documentation-site) - (synopsis "Melange documentation site") - (description "Content for the Melange documentation site") - (depends - ocaml - dune - reason - reason-react - reason-react-ppx - ocamlformat - js_of_ocaml - (cmarkit :dev) - (ocaml-lsp-server :dev))) From db2dac063e6e2343b0c17774f97d3a4f17779529 Mon Sep 17 00:00:00 2001 From: David Sancho Moreno Date: Wed, 15 Oct 2025 14:10:50 +0800 Subject: [PATCH 19/19] Updates dune and generates files --- .github/workflows/deploy-docs.yml | 6 ++++-- Makefile | 15 +++++++++------ documentation-site.opam.template | 2 +- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml index 1e62d5b45..427a53f31 100644 --- a/.github/workflows/deploy-docs.yml +++ b/.github/workflows/deploy-docs.yml @@ -23,8 +23,10 @@ jobs: dune-cache: false # can cause trouble when generating melange docs in step below: https://github.com/ocaml/dune/issues/7720 - name: Install all deps run: make install - - name: Generate melange library docs - run: make pull-melange-docs + - name: Generate melange library docs for OCaml syntax + run: make pull-melange-docs SYNTAX=ml + - name: Generate melange library docs for Reason syntax + run: make pull-melange-docs SYNTAX=re - name: Run canonical script run: opam exec -- dune exec add_canonical docs/public/api - name: Check Reason syntax diff --git a/Makefile b/Makefile index e2f90430d..1f73afb5a 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,7 @@ project_name = documentation-site DUNE = opam exec -- dune +SYNTAX ?= ml .DEFAULT_GOAL := help .PHONY: help @@ -84,12 +85,14 @@ preview: ## Preview the docs .PHONY: pull-melange-docs pull-melange-docs: ## Pull melange docs + if [ ! -d "melange" ]; then \ opam source melange.$$(opam show melange -f version) --dir melange; \ fi - dune build @doc-markdown - rm -rf docs/api/ml - cp -r _build/default/_doc/_markdown/melange/ docs/api/ml/melange - ODOC_SYNTAX="re" dune build @doc-markdown - rm -rf docs/api/re - cp -r _build/default/_doc/_markdown/melange/ docs/api/re/melange + ODOC_SYNTAX=$(SYNTAX) $(DUNE) build @doc-markdown + rm -rf docs/api/$(SYNTAX) + mkdir -p docs/api/$(SYNTAX) + cp -r _build/default/_doc/_markdown/melange docs/api/$(SYNTAX)/ + # Keep only Js*, Belt*, Dom*, and Node* files (but exclude Js_parser) + cd docs/api/$(SYNTAX)/melange && find . -type f -name "Js_parser*.md" -delete + cd docs/api/$(SYNTAX)/melange && find . -type f -name "*.md" ! -name "Js*.md" ! -name "Belt*.md" ! -name "Dom*.md" ! -name "Node*.md" ! -name "index.md" -delete diff --git a/documentation-site.opam.template b/documentation-site.opam.template index 52e5df0c4..fdba05a76 100644 --- a/documentation-site.opam.template +++ b/documentation-site.opam.template @@ -1,4 +1,4 @@ pin-depends: [ - ["dune.dev" "git+https://github.com/davesnx/dune.git#e2e04ac9da46185268c50b73f702973b483ed139"] + ["dune.dev" "git+https://github.com/davesnx/dune.git#08114d521b1d9b3c7323694aa785c218a1db2ae0"] ["cmarkit.dev" "git+https://github.com/dbuenzli/cmarkit.git#f37c8ea86fd0be8dba7a8babcee3682e0e047d91"] ]