Commit b972a0b2 authored by POTTIER Francois's avatar POTTIER Francois

Added [Misc.best].

parent 86433053
......@@ -317,3 +317,27 @@ let new_encode_decode capacity =
in
encode, decode, verbose
let rec best (preferable : 'a -> 'a -> bool) (xs : 'a list) : 'a option =
match xs with
| [] ->
assert false
| [x] ->
Some x
| x :: xs ->
(* If [x] is preferable to every element of [xs], then it is the
best element of [x :: xs]. *)
if List.for_all (preferable x) xs then
Some x
else
match best preferable xs with
| Some y ->
if preferable y x then
(* If [y] is the best element of [xs] and [y] is preferable to
[x], then [y] is the best element of [x :: xs]. *)
Some y
else
(* There is no best element. *)
None
| None ->
(* There is no best element. *)
None
......@@ -178,3 +178,8 @@ val new_intern: int -> (string -> string) * (unit -> unit)
so far. *)
val new_encode_decode: int -> (string -> int) * (int -> string) * (unit -> unit)
(* If [xs] is a nonempty list and [preferable] is a partial order on elements,
then [best preferable xs] returns the best (least) element of [xs], if there
is one. Its complexity is quadratic. *)
val best: ('a -> 'a -> bool) -> 'a list -> 'a option
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment