Re: To be or not to be - these are the options for Option.map

"Jeremy Yallop [email protected] [ocaml_beginners]" <[email protected]>
Newsgroups gmane.comp.lang.ocaml.beginners
Message-ID <CAAxsn=HwqX-LBy3che8ur=YW_SsQ9ori=GKZsoN=LGh5a7bWCw@mail.gmail.com>
On 6 September 2014 17:02, [email protected] [ocaml_beginners]
<[email protected]> wrote:
> However, looking in ~/.opam/system/lib/core_kernel/option.mli reveals no definition of the map function. The closest match is "val map2 : 'a t -> 'b t -> f:('a -> 'b -> 'c) -> 'c t".
>
> How can the code compile just fine when the 'map' definition isn't there?

The signature for the Option module has an 'include' line:

   include Monad.S with type 'a t := 'a t
   https://github.com/janestreet/core_kernel/blob/5aa53f/lib/option.mli#L8

This line means, roughly, "copy the contents of Monad.S at this
point".  The Monad.S signature has a map function

   val map : 'a t -> f:('a -> 'b) -> 'b t
   https://github.com/janestreet/core_kernel/blob/5aa53f/lib/monad.ml#L44-L45

so the result of the 'include' is that Option ends up with a map
function as well.

Note that these are just the type signatures, not the actual
definitions.  The definitions themselves are found in the
implementation files:

   let map =
   match M.map with
   | `Define_using_bind -> map_via_bind
   | `Custom x -> x
   https://github.com/janestreet/core_kernel/blob/5aa53f/lib/monad.ml#L64-L67

However, the definition of 'map' in Core is split into several parts
that might make it tricky to understand if you don't have a lot of
experience reading OCaml code.  It might be easier to start by looking
at the more straightforward definition in the "batteries included"
library:

   let map f = function
   | None -> None
   | Some v -> Some (f v)
   https://github.com/ocaml-batteries-team/batteries-included/blob/47a416/src/batOption.ml#L36-L38
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.