package batteries
Install
dune-project
Dependency
Authors
Maintainers
Sources
md5=1fd7bddce07cf5d244fc9427f7b5e4d4
sha512=c0f2a0fdc8253e0ea999d8d4c58bfbf32b18d251a2e1d9656bf279de5f01a33e9aabac3af4d95f465f8b671e7711ebd37218043face233340a0c11b08fa62f78
doc/batteries.unthreaded/BatOption/index.html
Module BatOption
Source
Functions for the option type.
Options are an Ocaml standard type that can be either None
(undefined) or Some x
where x can be any value. Options are widely used in Ocaml to represent undefined values (a little like NULL in C, but in a type and memory safe way). This module adds some functions for working with options.
some x
returns Some x
.
may f (Some x)
calls f x
and may f None
does nothing.
map f (Some x)
returns Some (f x)
and map f None
returns None
.
bind (Some x) f
returns f x
and bind None f
returns None
.
@example "Our functions return option types. Compose them to propagate None
."
let pick_long case =
try
Some (List.find (fun data -> List.length data > 1000) case)
with Not_found -> None
let last_null data = List.rindex_of 0 data
let interesting_positions dataset =
List.filter_map
(fun case -> Option.bind last_null (pick_long case))
dataset
apply None x
returns x
and apply (Some f) x
returns f x
filter f None
returns None
, filter f (Some x)
returns Some x
if f x
is true, and None
otherwise.
default x (Some v)
returns v
and default x None
returns x
.
Like default
, with the arguments reversed. None |? 10
returns 10
, while Some "foo" |? "bar"
returns "foo"
.
Note This operator does not short circuit like ( || )
and ( && )
. Both arguments will be evaluated.
Like default
, but the default value is passed as a thunk that is only computed if needed.
map_default f x (Some v)
returns f v
and map_default f x None
returns x
.
Like map_default
, but the default value is passed as a thunk that is only computed if needed.
is_none None
returns true
otherwise it returns false
.
is_some (Some x)
returns true
otherwise it returns false
.
get (Some x)
returns x
.
get_exn (Some x) e
returns x
and get_exn None e
raises e
.
Compare two options, possibly using custom comparators for the value. None
is always assumed to be less than Some _
. The parameter cmp
defaults to Pervasives.compare
.
Test for equality between option types, possibly using a custom equality predicate. The parameter eq
defaults to Pervasives.(=)
.
enum (Some x)
returns the singleton x
, while enum None
returns the empty enumeration.
of_enum e
consumes the first element of e
, if it exists, and returns Some e
. If e
is empty, return None
.
The Option Monad
This module provides everything needed to write and execute computations in the Option monad.
Boilerplate code
Comparison between optional values