janestreet / base

Standard library for OCaml
MIT License
860 stars 125 forks source link

Extend `Monad` for folding over lists #133

Open gfngfn opened 2 years ago

gfngfn commented 2 years ago

The present PR suggests adding the following two values to Base.Monad.S:

val fold_list : f:('a -> 'b -> 'a t) -> init:'a -> 'b list -> 'a t

val map_list : f:('a -> 'b t) -> 'a list -> 'b list t

This will provide implementations of the functions above for modules that implement Monad.Basic such as Option or Result.

The function fold_list roughly corresponds to Haskell’s foldM of Control.Monad and map_list to mapM (though they do not generalize list to any type constructor of class Foldable as foldM and mapM do). As a special case, the newly introduced Result.fold_list corresponds to List.fold_result.

I would appreciate it if you could give any comment or suggestion.

(* PS: I couldn’t guess how to run tests and thereby don’t extend them so far. The following procedure seems promising, but it causes conflicts during the build:

  1. Add (inline_tests) to test/dune,
  2. Remove sexp_grammar from test/dune,
  3. Invoke opam pin add base . at the repository,
  4. Install necessary dependencies, i.e., core v0.15.0 and expect_test_helpers_core, and
  5. Invoke dune test.
$ dune test                            
Error: Conflict between the following libraries:
- "base" in _build/default/src
- "base" in $HOME/.opam/4.12.0/lib/base
  -> required by library "core.base_for_tests" in
     $HOME/.opam/4.12.0/lib/core/base_for_tests
Error: Conflict between the following libraries:
- "base" in _build/default/src
- "base" in $HOME/.opam/4.12.0/lib/base
  -> required by library "ppx_compare.runtime-lib" in
     $HOME/.opam/4.12.0/lib/ppx_compare/runtime-lib

*)