Stdlib: add List.split_n

This commit is contained in:
Grégoire Henry 2018-06-02 16:33:45 +02:00 committed by Benjamin Canou
parent 22bf535d68
commit 39ca91cd57
2 changed files with 7 additions and 3 deletions

View File

@ -69,13 +69,15 @@ let rec remove nb = function
let rec repeat n x = if n <= 0 then [] else x :: repeat (pred n) x let rec repeat n x = if n <= 0 then [] else x :: repeat (pred n) x
let take_n_unsorted n l = let split_n n l =
let rec loop acc n = function let rec loop acc n = function
| [] -> l | [] -> l, []
| _ when n <= 0 -> List.rev acc | rem when n <= 0 -> List.rev acc, rem
| x :: xs -> loop (x :: acc) (pred n) xs in | x :: xs -> loop (x :: acc) (pred n) xs in
loop [] n l loop [] n l
let take_n_unsorted n l = fst (split_n n l)
module Bounded(E: Set.OrderedType) : sig module Bounded(E: Set.OrderedType) : sig
type t type t

View File

@ -23,6 +23,8 @@ val product : 'a list -> 'b list -> ('a * 'b) list
is provided, it returns the [n] greatest element of [l]. *) is provided, it returns the [n] greatest element of [l]. *)
val take_n: ?compare:('a -> 'a -> int) -> int -> 'a list -> 'a list val take_n: ?compare:('a -> 'a -> int) -> int -> 'a list -> 'a list
val split_n: int -> 'a list -> 'a list * 'a list
(** Bounded sequence: keep only the [n] greatest elements. *) (** Bounded sequence: keep only the [n] greatest elements. *)
module Bounded(E: Set.OrderedType) : sig module Bounded(E: Set.OrderedType) : sig
type t type t