From 59b5b2df49521f88855222f9802a5f2c55c885a0 Mon Sep 17 00:00:00 2001 From: Alex Coventry Date: Sat, 19 Aug 2017 04:58:19 +0000 Subject: [PATCH] Utils: fix `list_rev` complexity. Using fold_left here iterates over the entire list, whereas you only need to iterate over the first `n` elements. --- src/minutils/utils.ml | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/minutils/utils.ml b/src/minutils/utils.ml index 189aede0f..54d24e972 100644 --- a/src/minutils/utils.ml +++ b/src/minutils/utils.ml @@ -80,9 +80,15 @@ let filter_map f l = List.rev @@ List.fold_left (fun acc x -> may_cons acc (f x)) [] l let list_rev_sub l n = - ListLabels.fold_left l ~init:(n, []) ~f:begin fun (n, l) elt -> - if n <= 0 then (n, l) else (n - 1, elt :: l) - end |> snd + if n < 0 then + invalid_arg "Utils.list_rev_sub: `n` must be non-negative."; + let rec append_rev_sub acc l = function + | 0 -> acc + | n -> + match l with + | [] -> acc + | hd :: tl -> append_rev_sub (hd :: acc) tl (n - 1) in + append_rev_sub [] l n let list_sub l n = list_rev_sub l n |> List.rev