Version française
Home     About     Download     Resources     Contact us    
Browse thread
Optimizing Float Ref's
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Goswin von Brederlow <goswin-v-b@w...>
Subject: Re: [Caml-list] Optimizing Float Ref's
Dmitry Bely <dmitry.bely@gmail.com> writes:

> rewrite the function to get rid of it? My best achievement so far is
>
> let max_val (a:float array) =
>   let m = [|-.min_float|] in
>   for i = 0 to (Array.length a) - 1 do
>     if a.(i) > m.(0)
>     then m.(0) <- a.(i)
>   done;
>   m.(0)
>
> but it looks ugly...
>
> - Dmitry Bely

Why not store the index of the max element instead of the float itself?
Recursively, to avoid the ref as well, this could look like this:

let max_val (a:float array) =
  let len = Array.length a in
  let rec loop max i =
    if i = len
    then a.(max)
    else
      if a.(max) > a.(i)
      then loop max (i + 1)
      else loop i (i + 1)
  in
    if len = 0
    then -.min_float
    else loop 0 1

MfG
        Goswin