Version franēaise
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[NEWBIE] is there an in-place map?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2008-01-02 (17:36)
From: Brian Hurt <bhurt@j...>
Subject: Re: [Caml-list] [NEWBIE] is there an in-place map?
Edgar Friendly wrote:

>Kuba Ober wrote:
>>I need functionality of map, but done in such a way that the output array
>>is given as the argument, not as a return value. The closest I could get was
>>let inplace_map f a b = Array.blit (map f a) 0 b 0 (Array.length a)
>>Arrays a and b are of the same size.
>>This seems very inelegant.
>>One could use an adapter function and iteri, but that adds very noticeable 
>>overhead, and doesn't seem too elegant either.
>>let inplace_map f a b = Array.iteri (fun i src -> b.(i) <- f src; ()) a
>>There must be a better way of doing it, right? The given here is that the 
>>arrays a and b are there to stay, so we have to use them in-place.
>>Cheers, Kuba
>let blit_map f a b =
>	for i = 0 to (min (Array.length b) (Array.length a)) - 1 do
>		b.(i) <- f a.(i);
>	done
I was thinking more like:

let modify f a =
    for i = 0 to (Array.length a) - 1 do
       a.(i) <- f a.(i)

The OP did say "in place modification.

>But as I've been finding out in trying to performance tune for the
>Shootout, 'for' loops seem faster than even tail-recursion.  I'd say
>something about function call overhead, but tail recursion shouldn't
>have such.  Maybe the work of updating the loop counter in the recursive
>case makes the difference...
It depends.  If you have to use multiple references to make the for-loop 
work, then I've seen tail recursion be faster (and clearer).  Also, if 
you recalculate the ending requirement every recursive call, recursion 
can be slower (in the above for loop above, for example, Array.length is 
gaurenteed to be called only once).