Version franaise
Home About Download Resources Contact us
Browse thread
Function inlining and functor
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jon Harrop <jon@f...>
Subject: Re: [Caml-list] Function inlining and functor
On Monday 25 June 2007 16:36:53 you wrote:
> How would MetaOCaml help here?

You rewrite higher-order functions that accept closures (e.g. Array.fold_left) 
as higher-order functions that accept code. Then the inlining is up to you.

In the case of Array.fold_left, you make partial application generate and 
compile specialized implementations, giving you a type-specialized closure:

let fold_left f =
  .<
    fun accu a ->
      let accu = ref accu in
      for i=0 to Array.length a - 1 do
        accu := .~f !accu a.(i)
      done;
      !accu
  >.;;

Partial application of "f" now gives you a specialized function:

# fold_left .<( +. )>.;;
- : ('a, float -> float array -> float) code =
.<fun accu_1 ->
   fun a_2 ->
    let accu_3 = (ref accu_1) in
    for i_4 = 0 to ((Array.length a_2) - 1) do
     (accu_3 := ((! accu_3) +. a_2.(i_4)))
    done;
    (! accu_3)>.

Run-time compilation of this gives you the efficiency of inlining and, 
therefore, type specialization:

# .!(fold_left .<( +. )>.);;
- : float -> float array -> float = <fun>

Instead of:

  Array.fold_left ( +. ) 0.

You write:

  .!(fold_left .<( +. )>.) 0. a

which is twice as fast on my machine. MetaOCaml rocks. I do hope it becomes 
mainstream... :-)

-- 
Dr Jon D Harrop, Flying Frog Consultancy Ltd.
The OCaml Journal
http://www.ffconsultancy.com/products/ocaml_journal/?e