Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Are map and iter guaranteed to be called in forwards order?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jean-Marie Gaillourdert <jmg@g...>
Subject: Re: [Caml-list] Are map and iter guaranteed to be called in forwards order?
Hi,

Am Dienstag, 17. August 2004 16:56 schrieb Richard Jones:
> This came up because I wanted a sensible way to number a list of
> items.  The obvious imperative approach is:
>
>   # let items = ['a';'c';'e';'g';'i'];;
>   val items : char list = ['a'; 'c'; 'e'; 'g'; 'i']
>   # let i = ref 0;;
>   val i : int ref = {contents = 0}
>   # let items = List.map (fun item -> let n = !i in incr i; n, item)
> items;; val items : (int * char) list =
>     [(0, 'a'); (1, 'c'); (2, 'e'); (3, 'g'); (4, 'i')]
>
> The functional approach is comparatively long-winded: you have to
> effectively write your own loop explicitly, and the obvious way to
> write it isn't tail recursive, so you have to do it with accumulators.
>
> It'd be nicer to have a library HOF to do this.

There is a higher order function to do this: fold

List.rev 
  (List.fold_left (fun xs x -> 
    match xs with 
      [] -> [(0,x)] 
    | (i,_)::_ -> (i+1,x)::xs) [] items);;

Regards,
  Jean-Marie

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners