logo       
Google Custom Search
    AddThis Social Bookmark Button

Re: Extra function for List: msg#00002

Subject: Re: Extra function for List
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 =
    let rec loop x dst = function
        | [] -> x
        | h :: t ->
      let (x', h') = f x h in
      let r = {hd = h'; tl = []} in
      dst.tl <- inj r;
      loop x' r t
    in
    let dummy = dummy_node() in
    let e = loop b dummy l in
    (e, dummy.tl)
   
cheers,
Christophe

On 12/6/05, Christophe Poucet <christophe.poucet@xxxxxxxxx> 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 variable 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 =
  let (e, l') = List.fold_left
   (fun (x, t) a -> let (x', a') = 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] => (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 want to gradually build up a functional environment as you pass down this list.

Cheers,
Christophe


Try Searching:
servers, voip, java, networking, microsoft ...
<Prev in Thread] Current Thread [Next in Thread>