Walter Cazzola wrote:
> On Thu, 29 Sep 2011, David Allsopp wrote:
> 
> > I think it's probably something to do with optional arguments not
> > behaving as you expect.
> 
> uhm, would be interesting to see what is wrong on my use of the optional
> arguments.

Separately answered...

> > But this is a bad use for optional arguments - you should instead use
> > a nested function to pass the accumulator values. This works fine:
> 
> yes my first attempt was implemented with nested functions but ,,,
> 
> > 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
> 
> ... my nested function had a different name than the nextee function and I
> was passing l to it too. Could you explain me why your code works? in
> particular where does it take the list to enumerate? Silly question I know
> but it seems magic to me written in such a way

OCaml allows a name to hide a previous use of a name in the scope chain. The 
closest name moving up the "let .. in .." chains will always be the one used. 
Very occasionally that can cause some weird bugs but as the types will often 
differ, it's a clearer way of writing (rather than inventing arbitrary new 
names or using lots of prime symbols). I defined the innermost [enumerate] 
using the [function] keyword. You could equivalently write:

let rec enumerate acc n l =
  match l with
    h::ls -> ...

but the function keyword gives you that for free (it's the keyword for 
introducing an anonymous function with match and simply gives you a match over 
a single anonymous parameter).

> > 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.
> 
> Ok, thanks for the note, but efficiency issues are still far in my
> learning curve ;-)

Learning not to concatenate lists is part of learning tail recursion - it 
should be higher up your list ;o)

HTH,


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

Reply via email to