Version franaise
Home About Download Resources Contact us
Browse thread
The Implicit Accumulator: a design pattern using optional arguments
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Thomas Fischbacher <tf@f...>
Subject: Re: [Caml-list] The Implicit Accumulator: a design pattern using optional arguments
Jon Harrop wrote:

> I think Thomas is referring to continuation passing style (CPS). That isn't an 
> optimization though (it slows things down) but it does let you abstract away 
> mutation. However, it is not entirely safe in the absence of linear types.

Which one do you prefer?

let sum_nums n =
   let rec work sum todo =
     if todo=0 then sum
     else work (sum+todo) (todo-1)
   in work 0 n
;;

let sum_nums2 n =
   let rec work (sum,todo) =
     if todo=0 then sum
     else work ((sum+todo),(todo-1))
   in work (0,n)
;;

Certainly the first one, right? On the one hand, it is simpler,
and on the other hand, also faster, because it avoids consing the
pair cells that are passed around in the second example.

It is important to note that the recursive call to work can not only
be seen as a tail call, but in particular also as a continuation call.
Viewed in such a way, this is a strategy to provide more than one
"return value" to a continuation. The call to "work" could just as
much be a call to any other continuation that takes two arguments,
so this can be a nice way to reduce unnecessary consing - provided you
can make sure the continuation closures are not heap-allocated over
and over again.

Having said that, it is just as easy to get carried away by all these
nice little oprimization ideas in a functional language as it is in an
imperative language. While for some parts of the code, and in particular
in library functions, optimization is an issue, this more often than not
is not a good thing...

-- 
best regards,
Thomas Fischbacher
tf@functionality.de