This site is updated infrequently. For up-to-date information, please visit the new OCaml website at ocaml.org.

[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: 2004-08-17 (15:13) From: Anil Madhavapeddy Subject: Re: [Caml-list] Are map and iter guaranteed to be called in forwards order?
```On Tue, Aug 17, 2004 at 03:56:53PM +0100, Richard Jones wrote:
> 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.
>

Would List.combine come in handy?

Something like:

# let rec numlist n a = match n with |0 -> a |x -> numlist (n-1) (x::a);;
val numlist : int -> int list -> int list = <fun>
# let number l = List.combine (numlist (List.length l) []) l;;
val number : 'a list -> (int * 'a) list = <fun>
# let items = ['a';'c';'e';'g';'i'];;
val items : char list = ['a'; 'c'; 'e'; 'g'; 'i']
# number items;;
- : (int * char) list = [(1, 'a'); (2, 'c'); (3, 'e'); (4, 'g'); (5, 'i')]

--