# -*- mode: org; coding: utf-8 -*-
#+TITLE: TODO List for prelude
#+AUTHOR: Keith Waclena
#+EMAIL:
#+STARTUP: overview
#+OPTIONS: toc:nil num:nil tags:nil email:off ^:{}
#+LaTeX_CLASS: tuftehandout
* [#A] *MAJOR DEVEL REFACTOR*
:PROPERTIES:
:VISIBILITY: all
:END:
- i think i will strip the GNUmakefile of all mentions of erg and of
  the test suite!
- i will move the test suite and all erg convenience features (eg
  .merlin generation) into a Makefile.dev
- then when I work on prelude i will just have to manually change my
  default M-x compile command to be make -f Makefile.dev
- and i will make sure not to even ship Makefile.dev in the tar file.
- then there can't be any problems building in an opam install because
  the only makefile in the tarfile will 100% pure ocaml-makefile
* NOTES
** Writing QCheck Generators
#+BEGIN_SRC ocaml
QCheck.Gen.(list_size (int_range 1 10) (string_size ~gen:numeral (int_range 1 6)))
#+END_SRC
Run it like so:
: generate ~n:1 QCheck.Gen.(list_size (int_range 1 10) (string_size ~gen:numeral (int_range 1 6)))
Make it into an =arbitrary= for use in tests:
#+BEGIN_SRC ocaml
QCheck.(make Gen.(list_size (int_range 1 10) (string_size ~gen:numeral (int_range 1 6))))
#+END_SRC
* IDEAS
** APL- / J-like Vectors / Matrices
See Rob Pike's Ivy source code or just his slide deck!
https://github.com/robpike/ivy
** Prelude.top
Need a module with top-level printers for every Prelude data type!
** To_String Module
+ /Needs Very Short Name!  Like, S.../
#+BEGIN_SRC ocaml
  module S = struct
    let int = Int.to_string
    let list = List.to_string
    let string = id
  end
#+END_SRC
** Print Module like To_String?
** crazy K / J / APL operator
#+BEGIN_QUOTE
silentbicycle avatar silentbicycle 3 days ago | link |

| is max. It’s also boolean or. If you wanted the minimum, it’d be &/, because & is min/boolean and. |

The APLs have teased apart lots of common operations into atomic parts
that combine cleanly, sometimes unpacking them further than other
languages go. The single-argument form of & (“where”) is a good
example:

  &1 2 3 0 1 1 2 2 2

It counts up, repeating each successive number based on the next
number in the argument.

  &5 5 5 0 0 0 0 0 1 1 1 1 1 2 2 2 2 2

Okay, so that makes the pattern clearer. By why is that useful?

  & 0 0 0 1 0 1 1 0 1 0 3 5 6 8

Ah ha – “what are the offsets of the 1s?”

  x:10?!1000 / draw 10 random numbers 0 to 999
  x / print them
  379 998 594 106 191 686 123 845 495 700
  x < 500 / what values are less than 500
  1 0 0 1 1 0 1 0 1 0
  x[&x<500] / slice x by indices where x is less than 500
  379 106 191 123 495

So it combines with a conditional to become a sort of SELECT, but it
also combines with other operators in a predictable way, and the
implementation is straightforward.

-- https://lobste.rs/s/apalf0/stages_denial_learning_k#c_ojfmlc
#+END_QUOTE
** hyper abstract combinators

  u, u1, and u2 are unary functions
  @, b, b1, and b2 are binary functions

*** combinators for two functions
**** DONE unary unary

***** function composition
let ($.) u1 u2 x = u1 (u2 x)

***** reverse function composition
let ($) u1 u2 x = u2 (u1 x)

**** unary binary
the same as binary unary, so just define the latter and use flip
let (??) u (@) x y = u x @ u y
let (??) u (@) x   = u x @ u x

**** DONE binary unary
let (??) (@) u x y = u x @ u y  (* =  on **)
let (??) (@) u x   = u x @ u x  (** =? on1 *)
let (??) b u x y = b (u x)    y  (* =? lefthook;  lefthook cons = conswith *)
let (??) b u x y = b    x  (u y) (* =? righthook; righthook snoc = snocwith *)

**** binary binary
J's fork
let (??) ( + ) ( * ) x y = (x*y) + (x*y)

*** combinators for three functions

**** binary unary unary
let (??) (+) u1 u2 x y = u1 x + u2 y

**** DONE binary binary binary
J's fork = fork
let fork (+) ( * ) (/) x y = (x * y) + (x / y)

** How to do the Extended modules
[From: https://discuss.ocaml.org/t/create-copy-of-module-with-modified-submodule/1910/11

Create copy of module with modified submodule

Hi,

I am in a situation where I need to create a module Graph that is
exactly like Graph0, except that I would like to add a function in
Graph.V. Since OCaml does not allow shadowing submodules, the only way
I’ve found is to repeat every definition of the original module:

#+BEGIN_SRC ocaml
module Graph = struct
  type t = Graph0.t
  module V = struct
    include Graph0.V
    let pretty = VImpl.pretty
  end
  module E = Graph0.E
  let fold_pred_e = Graph0.fold_pred_e
  let copy = Graph0.copy
  (* ... *)
end
#+END_SRC
Is there a less contrived way to write that?

octachronMaintainer 23h

It is possible to use destructive substitution of module here:

#+BEGIN_SRC ocaml
module type graphm =
  module type of struct include Graph0 end with module E := Graph0.E

module Graph = struct
  include (Graph0 : graphm)
  module E = struct
    include Graph0.E
    ...
  end
end
#+END_SRC

But I don’t think I would go as far as calling this solution less contrived.

bluddy 23h

#+BEGIN_SRC ocaml
module type graphm = module type of struct include Graph0 end with module E := Graph0.E
#+END_SRC

@octachron could you explain this? It’s a destructive substitution,
but how come E doesn’t appear in the final type of graphm? (I’m trying
a simple example in utop)

octachronMaintainer  21h

Because the destructive substitution removes the original definition
and replaces all subsequent occurences with the right hand side of the
substitution?

This is quite close of the behavior with types and is generally very
useful to combine together related signature. For instance, I can
start with a ring

#+BEGIN_SRC ocaml
module type ring= sig
  type t
  val (+): t -> t -> t
  val ( * ): t -> t -> t
  ...
end
#+END_SRC
define a module type for division related operations

#+BEGIN_SRC ocaml
module type division= sig type t val (/): t -> t -> t end
#+END_SRC
and then extend the ring module type to a field module type:

#+BEGIN_SRC ocaml
module type field = sig include ring include division with type t := t end

#+END_SRC

Similarly, if I start with a module type for modules (the abstract
algebra ones), it can be quite nice to have an inner submodule for
scalars:

#+BEGIN_SRC ocaml
module type module' = sig
  module Scalar: ring
  type vec
  type matrix
  val det: matrix -> Scalar.t  ...
end
#+END_SRC

But then if I want to extend this module type to a module type for a
vector space, I need to promote the Scalar module to a field, and not
a ring. At this point, destructive substitution of module is the right
solution:

#+BEGIN_SRC ocaml
module type vector_space = sig
  module Scalar: field
  include (module' with module Scalar := Scalar )
 ...
end
#+END_SRC

bluddy 21h

These other examples make sense. But let me make a simple one that matches the OP’s case:

#+BEGIN_SRC ocaml
module A = struct
  type t = int
  module B = struct
    let foo x = x
  end
end
#+END_SRC
: > module A : sig type t = int module B : sig val foo : 'a -> 'a end end

#+BEGIN_SRC ocaml
module AP = struct include A end
#+END_SRC
: > module AP : sig type t = int module B = A.B end

#+BEGIN_SRC ocaml
module AP = struct
  include A
  module B = struct
    include A.B
    let bar y = y
  end
end
#+END_SRC
: > Error: Multiple definition of the module name B.
:       Names must be unique in a given structure or signature.

#+BEGIN_SRC ocaml
(* OK, trying @octachron's trick *)
module type AT = module type of struct include A end with module B := A.B;;
#+END_SRC
: > module type AT = sig type t = int end   (* huh? where did B go? *)

#+BEGIN_SRC ocaml
module AP = struct
  include (A:AT)
  module B = struct
    include A.B
    let bar y = y
  end
end
#+END_SRC
: > module AP :
:   sig type t = int module B : sig val foo : 'a -> 'a val bar : 'a -> 'a end end

It succeeded because we got rid of B in AT… but why did B go away in
the first place?

octachronMaintainer 21h

#+BEGIN_SRC ocaml
module type AT = module type of struct include A end with module B := A.B;;
#+END_SRC

First, in this case, since A does not define new types, it is possible
to go with the simpler

#+BEGIN_SRC ocaml
module type AT = module type of A with module B:= A.B
#+END_SRC

Then, we can extend

#+BEGIN_SRC ocaml
module type a = module type of A
(* ≡ sig type t = int module B : sig val foo : 'a -> 'a end *)
#+END_SRC

The substitution a with module B := A.B then implies to remove the
definition of B, aka module B: sig ... end and replace all ulterior
apparition of B by A.B (which is an already defined module). Since no
components of B is used after its definition this means that we can
simply erase B from the signature

#+BEGIN_SRC ocaml
module type at = a with module B:= A.B (* ≡ sig type t =int end *)
#+END_SRC

It is essentially the same thing as

#+BEGIN_SRC ocaml
module type empty = sig type t end with type t := int
(* ≡ sig end *)
#+END_SRC

bluddy 20h

    The substitution a with module B := A.B then implies to remove the
    definition of B, aka module B: sig … end and replace all ulterior
    apparition of B by A.B (which is an already defined module). Since
    no components of B is used after its definition this means that we
    can simply erase B from the signature

I’m not clear about this part. No component of B is used within A, but
B has a function foo that can be used from the outside: shouldn’t that
appear as part of the signature of A? What made the typechecker decide
that B is now irrelevant? I’m missing how the destructive substitution
works in this case.

octachronMaintainer 20h

I think that you are confusing the module type level and the module
level. At the module type level, there is no concrete values, just a
high-level specification of the components of potential modules. All
the with constraints manipulate this high-level specification but not
modules per se. It is thus perfectly fine to remove mention of a
function B.f in a specification.

bluddy 19h

OK, but how does the typechecker know that this is what we wanted? We
never told it to hide B – we just said we’ll substitute the current B
with another one (that happened to be the exact same one). It seems
like we should be able to remove elements from module types (is weaken
the right word for this?), but what we did doesn’t seem like it should
have any impact on the type, at least not in a way that seems obvious
to me.

Are we expressing weakening (again, not sure if correct here) by
tautology? Is that the idea? Would a different syntax like with B :=#
signifying deletion make more sense? What am I missing?
octachronMaintainer 11h

The aim of destructive substitution is exactly to remove a
component. The substitution part is here to fill any gaping hole in
the heart of the signature left by such removal. Consider a universe
containing only

#+BEGIN_SRC ocaml
module type s = sig
    module Unique: sig type t end
   val do_singular_things: Unique.t -> Unique.t -> Unique.t -> Unique.t
end
#+END_SRC

If we could simply remove the Unique module from the module type s
what would be the type of do_singular_things ? ___.t -> ___.t -> ___.t
->___.t ? After all, there are no more a type Unique.t to refer to.
Having a substitution part in module type s with module Unique :=
Example makes it possible to both remove the Unique module and replace
its components appearing in s with the corresponding Example
component.

** Selecting and Deselecting
See [[http://skarnet.org/software/s6/s6-log.html][s6-log]]:
#+BEGIN_EXAMPLE
  Selection directives

  These directives tell s6-log whether to select or deselect lines it
  reads from stdin; actions will only happen on selected lines. By
  default, every line is selected.

   +regexp: select yet-unselected lines that match regexp, which must be a POSIX Extended Regular Expression.
   -regexp: deselect yet-selected lines that match regexp, which must be a POSIX Extended Regular Expression.

   f: select exactly lines that have not yet been acted upon (i.e. that
      were always deselected when the script encountered an action
      directive).

#+END_EXAMPLE
Just a predicate-definer?
#+BEGIN_SRC ocaml
  let script = Select.Posix.[ D "";  S "^fatal "; A print_endline;  R;  S "foo";  D "foobar" ]
  let script = Select.Posix.( d "" $ s "^fatal "$ A print_endline $ R $ S "foo" $ D "foobar")
  let _ = Gen.catch readline |> Select.run script |> to_list |> len |> printf "%d remaining\n"
#+END_SRC
* BUILD
** TODO convert GNUmakefile to new erg USEOCAMLMAKEILE style
See [[file:~/src/versioj/GNUmakefile::ifdef USEOCAMLMAKEFILE]]
* REFACTORING
** TODO eliminate Prelude-versions of functions in Stdlib
- Lists.{hd,tl,concat,rev.map,mapi,map2,filter,mem,partition,iter,iteri,iter2}
** TODO rewrite =String.parens= to use =Seq= instead of =Stream=
** TODO Move all System functions into a proper System module
And of course =include System= for compatibility.
** TODO replace all stdlib-only-no-unix implementations with Unix
E.g. =File.squiggle=
** TODO reimplement generators as per Cruanes' sequences
After benchmarking...  but his will be faster.

But, it might be a good idea to support both...  Buenzli says:
#+BEGIN_QUOTE
When you are streaming from/to files you need to be able to handle
errors and resource disposal, these thing won’t do it and simply
plugging file reading functions in there will easily result in pain
like too many open fds etc. (you would be doing the equivalent of
Haskell’s lazy IO, google for that you should be able to find plenty
of discussion about its shortcomings).

One way to side step the issue with these iterators is to first read
the whole file in memory and start from that, but then you are no
longer streaming (and the error handling story e.g. for decoders is
still spoty).
#+END_QUOTE
[[https://discuss.ocaml.org/t/alternative-to-streams/1020/5][streams / gen]]
* BUGS
** TODO Char.Hex.is doesn't handle a-f!
** TODO =Refer.assemble=: bad fixing
This fix adds a bogus field!
#+begin_example
  # Refer.assemble ~fix:true ["X", "foo\n\n%X foo"] |> print;;
  %X foo
  %X foo
#+end_example
Should return:
#+begin_example
  %X foo %X foo
#+end_example
** TODO Map.to_string should wrap string repr in {}'s
** TODO =Lists.transpose= is buggy
Matt's replacement code:
#+begin_src ocaml
  let transpose arr =
    let open Prelude.List in
    let open Prelude.List.Ops in
    let width = maximumBy (map length arr) - 1 in
    let* idx = 0 -- width in
    let eachRow row = take (idx + 1) row |> drop idx in
    return (map eachRow arr |> concat)
#+end_src
Needs to be a new function, eg =transpose'.= Unlike =transpose= it never
raises an exception, but on the other hand it doesn't guarantee a
rectangular result (which =transpose= can, when =~def= is used).
** TODO figure out a better way to know when we're building via OPAM
better than this in GNUmakefile:
: ifeq ($(wildcard .hg),.hg)
** TODO =Unix.Shell= error message
Need to unquote the pipeline!
#+begin_example
# Unix.Shell.(read (cmd ["opam"; "var"; "flerg:lib"])) |> String.trimright "\r\n";;
[ERROR] Variable flerg:lib not found in switch 4.14.1
Exception:
Failure "exit 5: \\o\\p\\a\\m \\v\\a\\r \\f\\l\\e\\r\\g\\:\\l\\i\\b".
# print "exit 5: \\o\\p\\a\\m \\v\\a\\r \\f\\l\\e\\r\\g\\:\\l\\i\\b";;
exit 5: \o\p\a\m \v\a\r \f\l\e\r\g\:\l\i\b
- : unit = ()
#
#+end_example
** TODO improve Interval.{between,contains,inbounds}
E.g.
#+begin_src ocaml
  let contains (x,y) n =
    let lo, hi = min x y, max x y in
    lo <= n && n <= hi

#+end_src
** TODO Unix.Proc.run bug
: Unix.Proc.rw ["tr"; "a-z"; "A-Z"] "ocaml";;
just hangs!  need a flush or close!
** TODO [#A] breaking change with 4.12!
#+begin_quote
  • *breaking change* [9668]: List.equal, List.compare (This could break
     code using "open List" by shadowing Stdlib.{equal,compare}.)
     (Gabriel Scherer, review by Nicolás Ojeda Bär, Daniel Bünzli and
     Alain Frisch)
#+end_quote
** TODO change all references tp Pervasives to Stdlib
** TODO rewrite =File.follow= without =~max=
=stat= and maintain a cache of =(st_dev, st_ino)= pairs.
** TODO test suite portability bugs on Mac OS X
#+BEGIN_EXAMPLE
random seed: 411342113
 [1537+5 2! / 1567] >input>./prelude.ml:11825                 tr: Illegal byte sequence
tr: Illegal byte sequence
 [1541+6 2! / 1567] >write>./prelude.ml:11894                 dd: unknown operand status
dd: unknown operand status
dd: unknown operand status
dd: unknown operand status
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Error: >write>./prelude.ml:11894test `./prelude.ml:11894: Q.small_string (fun s -> () = write (cmd [“dd”;“of=/dev/null”;“status=none”]) s)`
raised exception `Failure(“exit 1: \\d\\d \\o\\f\\=\\/\\d\\e\\v\\/\\n\\u\\l\\l \\s\\t\\a\\t\\u\\s\\=\\n\\o\\n\\e”)`
on `“” (after 3 shrink steps)`
///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Failure: >input>./prelude.ml:11825test `./prelude.ml:11825: Q.small_string (fun s -> let s = String.translate “\000\n” ” ” s in (WEXITED 0, String.uppercase_ascii (“x”^s^“\n”)) = input Prelude.read (pipeline [[“echo”;“x”^s];[“tr”;“a-z”;“A-Z”]]))`
failed on ≥ 1 cases: “\227" (after 1 shrink steps)///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Error: >rwlines>./prelude.ml:11474test `./prelude.ml:11474: Q.(small_list small_string) (fun xs -> xs = [“”] || rwlines [“tr”;“a-z”;“A-Z”] xs = (map String.(uppercase_ascii $ postpend “\n”) xs |> String.concat “”))`
raised exception `Failure(“exit 1”)` on `[“\139"] (after 6 shrink steps)`
///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Error: >rw>./prelude.ml:11461test `./prelude.ml:11461: Q.small_string (fun s -> rw [“tr”;“a-z”;“A-Z”] s = String.uppercase_ascii s)`
raised exception `Failure(“exit 1")` on `“\246” (after 1 shrink steps)`
///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Failure: >run>./prelude.ml:11330./prelude.ml:11330: run () |> map checker |> all okay
///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Failure: >withtempfile>./prelude.ml:8523./prelude.ml:8523: (withtempfile Filename.(fun fn _ -> dirname fn = get_temp_dir_name ()))
///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Failure: >glob>./prelude.ml:8065./prelude.ml:8065: (glob (fun p -> (Filename.basename p).[0] = ‘d’) testing |> sort compare) = [!“d1"; !“d2”]
///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Failure: >glob>./prelude.ml:8064./prelude.ml:8064: (glob (k true) testing |> sort compare) = [!“d1"; !“d2”; !“f1"]
///////////////////////////////////////////////////////////////////////////////
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
Failure: >withcd>./prelude.ml:8046./prelude.ml:8046: (let dir = “/etc” in withcd (fun d -> d = dir && Sys.getcwd () = dir) dir)
///////////////////////////////////////////////////////////////////////////////
Ran: 1567 tests in: 42.19 seconds.
WARNING! SOME TESTS ARE NEITHER SUCCESSES NOR FAILURES!
FAILURE
#+END_EXAMPLE
** TODO =File.fold= is too complex
Replace with simple version with no ~err.
** TODO nested macro calls don't work
if the nested call has parms:
#+BEGIN_EXAMPLE
{q|hello {i|there} my friend}
#+END_EXAMPLE
when fixed improve Trillion Year Spree.
** TODO need to use =Format= with break hints in all =to_string= functions!
** TODO Units.Time.expand
#+BEGIN_EXAMPLE
# [1; 12; 0; 0; 0; 0; 0; 0] |> Units.Time.expand;;
- : string list =
["1 year"; "12 years"; "0 months"; "0 weeks"; "0 days"; "0 hours";
 "0 minutes"; "0 seconds"]
#
#+END_EXAMPLE
** TODO classify functions are all different!
This needs to be though through more carefully...
#+BEGIN_SRC ocaml
Hashtbl.classify;;
- : ('a -> ('a, 'b) Prelude.Pre.Hashtbl.t) ->
    ('c -> 'b -> 'b) -> 'b -> 'a -> 'c -> unit
= <fun>
# Assoc.classify;;
- : ('a -> 'b) ->
    ('a -> 'c -> 'c) -> 'c -> 'a -> ('b * 'c) list -> ('b * 'c) list
= <fun>
# module M = Map.Make (Int);;
# M.classify;;
- : ('a -> M.key) -> ('a -> 'b -> 'b) -> 'b -> 'a -> 'b M.t -> 'b M.t = <fun>
#
#+END_SRC
** DONE Refer.Random needs total rewrite
Use =assemble ~fix:true=!!
** DONE =Multiset= API change
All accessors --- =fold=, =map=, etc --- must process all the repeats.
E.g. =fold='s function shouldn't take an extra parm --- should match
=Set.fold= exactly.  Instead, it should apply the function to each of
the repeats.  =Multiset.Indentity= should apply it N times to each
element, and =Multiset.Equivalent= should apply it to each repetition.
** DONE Unix can't be kept out!
Gotta allow it.  Stupid idea.
* FEATURES
** TODO new: =Format.pp_to_string=
#+begin_src ocaml
  # let pp_to_string pp = fun x -> pp Format.str_formatter x; Format.flush_str_formatter ();;
  val pp_to_string : (Prelude.Format.formatter -> 'a -> 'b) -> 'a -> string =
    <fun>
  # Uri.of_string "http://foo.com/" |> pp_to_string Uri.pp;;
  - : string = "http://foo.com/"
#+end_src
** TODO new Result.validate
#+begin_src ocaml
  let validate ?fmt f x format =  (* TODO PROMOTE to Prelude.Result *)
    let fmt exn = match fmt with Some f -> f exn x | None -> Exn.to_string exn in
    match Result.trap fmt f x with
    | Error msg -> Error (sprintf format msg)
    | ok        -> ok
#+end_src
Usage:
#+begin_src ocaml
  let main' ngramsize number =
    let open Result.Ops in
    let fmt _exn str = sprintf "not a number: %s" str in
    let* size = validate ~fmt int_of_string ngramsize "%s" in
    let* size = if size > 0 then Ok size else Error ("NGRAMSIZE (%d) must be > 0" % size) in
    let* num = validate ~fmt int_of_string number "%s" in
    let* num = if num > 0 then Ok num else Error ("NUMBER (%d) must be > 0" % num) in
    let db, inits = readdata pathToText ngramSize in
    foreach (eachsentence inits db) (1,num);
    Ok ()
#+end_src
** TODO new Bool.to_result
#+begin_src ocaml
  module Bool = struct
    include Stdlib.Bool
    include Bool
    let to_result ok error b = if b then Ok ok else Error error
  end
#+end_src
** TODO add =pp= functions to all modules
#+begin_src emacs-lisp
  module M = Map.Specialize (StringList) (String)
  let pp ppf map = Format.pp_print_string ppf (M.to_string map)
#+end_src
#+begin_quote
There is a convention, that modules that define abstract types also
provide a function called pp which specifies how this value should be
printed, e.g.,

let () = printf "Hello, abstract student %a\n%!" Student.pp s

Where the Student module might be defined as:
#+end_quote
#+begin_src ocaml
  struct Student : sig
     type t
     val create : string -> int -> t
     val pp : Format.formatter -> t -> unit
  end = struct
     type t = {name : string; cls : int}
     let create name cls  = {name; cls}
     let pp ppf {name; cls} =
        Format.fprintf ppf "%s of %d" name cls
  end
#+end_src
** TODO =Prelude.Map.adjust= like Haskell's
#+begin_src ocaml
  let adjust f key map =
    match M.find key map with
    | exception Not_found -> map
    | v -> M.replace key (f v) map
#+end_src
** TODO new: =add_with_overflow=
By Nicolas Ojeda Bar:
#+begin_src ocaml
  let add_with_overflow a b =
    let a = Int64.of_int a and b = Int64.of_int b in
    let r = Int64.add a b in
    if r > Int64.of_int max_int || r < Int64.of_int min_int then
      failwith "overflow";
    Int64.to_int r
#+end_src
** TODO overloaded =(::)= for =List1=
: type 'a t = ( :: ) of 'a * 'a list
** TODO =Time.parse=: needs =?locale= parameter
** TODO =Time.parse=: should it take an =?escape= Bool parameter?
to allow user to do: parse "%B +%e, +%Y"?
or should it /never/ escape?  just let caller use =Str.quote= on the
input?  does that work?
** TODO Char.random_set
Generate random char from a set (i.e. array) of restricted candidates.
** TODO =let&= operator
https://discuss.ocaml.org/t/in-cygwin-ocaml-outputs-crlf-line-endings-but-inputs-only-lfs-leading-to-end-of-file/8014/5
#+begin_quote
This is interesting and reminds me of a suggestion I made recently, i.e. if we define a let-operator:
#+end_quote
#+begin_src ocaml
let ( let& ) ch fn =
  Fun.protect ~finally:(fun () -> close_in ch) begin fun () ->
    fn ch
  end
#+end_src
#+begin_quote
Then we can express this as:
#+end_quote
#+begin_src ocaml
let read_all filename =
  let& ic = open_in_bin filename in
  let len = in_channel_length ic in
  really_input_string ic len
#+end_src
** TODO add to Prelude Examples
#+BEGIN_SRC ocaml
let ls dir =
  let open Result.Ops in
  Result.trap Exn.to_string Unix.opendir dir
  >>| finalize (foldex ~exn:End_of_file (conswith Unix.readdir) []) Unix.closedir

# Result.Ops.(ls "/etc" >>| len);;
- : (int, string) result = Ok 182
# Result.Ops.(ls "/etc/sudoers.d" >>| len);;
- : (int, string) result = Error "/etc/sudoers.d: Permission denied"
#
#+END_SRC
** TODO =Units.Time=: generalize
Redefine in terms of a functor which requires, in addition to =Num=,
=factors=, and defines all the general functions.
** TODO add [[./tsort.ml][tsort]]
** TODO extensible arrays
Steal the code of Buffer.
** DONE Relational Operators for Partial Application Only
#+BEGIN_SRC ocaml
  let lt n u = u < n
  let gt n u = u > n
  let eq = (=)
#+END_SRC
** DONE Gen: Update external refs
+ Add link to Cruane's Gen https://github.com/c-cube/gen
+ Correct Sequence to Iter
** DONE Multiset.alist
#+BEGIN_SRC ocaml
M.fold (fun x acc -> (x, M.count x ms) :: acc) ms []
#+END_SRC
** DONE update to 4.08.1
*** deprecated Pervasives
Alert deprecated: module Stdlib.Pervasives
Use Stdlib instead.

If you need to stay compatible with OCaml < 4.07, you can use the
stdlib-shims library: https://github.com/ocaml/stdlib-shims
* DOCUMENTATION
** TODO contradiction                                              :message:
doc says:
: (message ~myself:None "starting up") prints "starting up"
but really:
#+begin_example
  utop[68]> Message.message ~myself:None "starting up";;
  Error: This expression has type 'a option
         but an expression was expected of type string
#+end_example
This is either a doc error or a bug!

If it's not a bug, then this is: excess seps should be elided when "":
#+begin_example
  Message.warning ~prefix:"" "starting up";;
  - : unit = ()
  utop.exe: : starting up
#+end_example
** DONE move docstrings from module to sig                         :leftist:
[[file:prelude.ml::module Make (M : MinMax) (Ord : OrderedType) : S with type elt = Ord.t = struct]]
* TESTS
** DONE change all =Q.(list int)= to =Q.(list small_int)=
#+BEGIN_QUOTE
Duplicate Elements in Lists

When generating lists, avoid Q.list Q.int unless you have a good
reason to do so. The reason is that, given the size of the Q.int
space, you are unlikely to generate any duplicate elements. If you
wish to test your function’s behaviour with duplicates, prefer Q.list
Q.small_int.
#+END_QUOTE
[[https://github.com/vincent-hugot/iTeML]]
* OPTIMIZATION
** TODO benchmark this new =List.nub2=
#+begin_src ocaml
  let nub2 lst =
    let each acc x = x :: filter ((<>) x) acc in
    rev lst |> foldl each []
#+end_src
