Walter Cazzola wrote:
> Dear all,
> waiting for some hints on my other issue for functors and generic I was
> playing with an enumerate function (with tail recursion):
>
> let rec enumerate ?(l':((int * 'a) list)=[]) ?(n=0) l =
> match l with
> h::l1 -> enumerate (l'@[(n,h)]) (n+1) l1
> | [] -> l'
>
> this should just take a list and return a list of couple whose first entry
> is the position in the list of the element; to be clearer:
>
> enumerate ['a'; 'b'; 'c'] -> [(0,'a'); (1,'b'); (2,'c')];
>
> but this doesn't work as by type mismatch:
>
> Error: This expression has type (int * 'a) list
> but an expression was expected of type 'a list
I think it's probably something to do with optional arguments not behaving as
you expect. But this is a bad use for optional arguments - you should instead
use a nested function to pass the accumulator values. This works fine:
let enumerate l =
let rec enumerate acc n = function
h::ls -> enumerate ((n, h)::acc) (n + 1) ls
| [] -> List.rev acc
in
enumerate [] 0 l
Concatenating lists is also expensive in terms of the left list so your
function is about as slow as possible! Much better when aiming for tail
recursion, accumulate a reversed list and then reverse it in the basis case.
David
--
Caml-list mailing list. Subscription management and archives:
https://sympa-roc.inria.fr/wws/info/caml-list
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs