From: Christophe P. <chr...@gm...> - 2005-12-06 14:32:24
|
Hello, I have looked inside extList.ml and noticed the hackery used to forgo List.rev to keep functions tail-recursive. Anyways, here is a new fold_map that uses the same hackery: let fold_map f b l =3D let rec loop x dst =3D function | [] -> x | h :: t -> let (x', h') =3D f x h in let r =3D {hd =3D h'; tl =3D []} in dst.tl <- inj r; loop x' r t in let dummy =3D dummy_node() in let e =3D loop b dummy l in (e, dummy.tl) cheers, Christophe On 12/6/05, Christophe Poucet <chr...@gm...> wrote: > > Hello, > I have here a function I would like to propose for the list module. It's > a foldmap. Basically it's a map but it allows you to pass along a variab= le > among the different calls. Perhaps it could be called foldmap_left such > that a foldmap_right could be implemented as well. > > let foldmap f b l =3D > let (e, l') =3D List.fold_left > (fun (x, t) a -> let (x', a') =3D f x a in (x', a'::t)) (b, []) l > in (e, List.rev l') > > > An example of it's use: > foldmap (fun a e -> (a+1, e)) 0 [1;2;3] =3D> (3, [1;2;3]) > > The motivation for this is that sometimes you want to map a certain list > (imagine for instance a list of statements in a compiler), but you also w= ant > to gradually build up a functional environment as you pass down this list= . > > Cheers, > Christophe > |