Browse thread
The Implicit Accumulator: a design pattern using optional arguments
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Jon Harrop <jon@f...> |
| Subject: | Re: [Caml-list] The Implicit Accumulator: a design pattern using optional arguments |
On Thursday 28 June 2007 12:01:34 Thomas Fischbacher wrote:
> 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?
I would write:
let rec work sum = function
| 0 -> sum
| todo -> work (sum + todo) (todo - 1)
let sum_nums n = work 0 n
because it is shorter, clearer, 65% faster and it is idiomatic ML rather than
idiomatic Lisp.
--
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
The OCaml Journal
http://www.ffconsultancy.com/products/ocaml_journal/?e