From fd88f102169a276f6379fbbc1a2baa68aa3b2621 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sat, 31 May 2014 12:36:15 +0200 Subject: [PATCH] safe version of fold_right --- core/CCList.ml | 20 ++++++++++++++++++++ core/CCList.mli | 3 +++ 2 files changed, 23 insertions(+) diff --git a/core/CCList.ml b/core/CCList.ml index a60428db..45a31ccc 100644 --- a/core/CCList.ml +++ b/core/CCList.ml @@ -61,6 +61,26 @@ let append l1 l2 = let (@) = append +let fold_right f l acc = + let rec direct i f l acc = match l with + | [] -> acc + | _ when i=0 -> safe f (List.rev l) acc + | x::l' -> + let acc = direct (i-1) f l' acc in + f x acc + and safe f l acc = match l with + | [] -> acc + | x::l' -> + let acc = f x acc in + safe f l' acc + in + direct _direct_depth f l acc + +(*$T + fold_right (+) (1 -- 1_000_000) 0 = \ + List.fold_left (+) 0 (1 -- 1_000_000) +*) + let rec compare f l1 l2 = match l1, l2 with | [], [] -> 0 | _, [] -> 1 diff --git a/core/CCList.mli b/core/CCList.mli index 6f9adf77..f06284f1 100644 --- a/core/CCList.mli +++ b/core/CCList.mli @@ -36,6 +36,9 @@ val append : 'a t -> 'a t -> 'a t val (@) : 'a t -> 'a t -> 'a t +val fold_right : ('a -> 'b -> 'b) -> 'a t -> 'b -> 'b +(** Safe version of [fold_right] *) + val compare : ('a -> 'a -> int) -> 'a t -> 'a t -> int val equal : ('a -> 'a -> bool) -> 'a t -> 'a t -> bool