[haXe] Deep Copy of an array? how can it be done generically
Franco Ponticelli
franco.ponticelli at gmail.com
Sun Apr 22 16:17:23 CEST 2007
Does this help?
class ArrayUtil
{
static public function main() {
var test : Array<Array<Int>> = [[0,1,2],[3,4,5]];
var copy = deepCopy(test);
for(i in 0...copy.length)
for(j in 0...copy[i].length)
trace(copy[i][j]);
}
/**
* Does a deep copy on the array, assuming the items are
* further arrays or have "copy" semantics (such as fundamentals)
*/
static public function deepCopy<T>( arr : Array<T> ) : Array<T>
{
var r = new Array<T>();
for( i in 0...arr.length )
r.push(copy(arr[i]));
return r;
}
static private function copy<T>( value : Dynamic) : T {
if( Std.is( value, Array ) )
return cast deepCopy( value );
else
return value;
}
}
Of course, if you are not copying arrays of primitives you will have to call
some copy/clone method ...
On 4/22/07, edA-qa mort-ora-y <eda-qa at disemia.com> wrote:
>
> I often used Matrix like constructs such as:
> Array<Array<Int>>
> The problem is that I don't have an easy way to produce a copy of these
> structures. A simple "copy" will just reuse the second level objects,
> but I want a proper deep copy.
>
> Obviously it is easy enough for a given case to do a copy, but I would
> like to have some kind of generic function which can do the copy,
> otherwise I'm forced to write a copy operation for every matrix like
> type that I have.
>
> I tried to get something like the following possible, but I always get
> some kind of compilation error that I can't figure out how to get rid of.
>
>
> class ArrayUtil<T>
> {
> /**
> * Does a deep copy on the array, assuming the items are
> * further arrays or have "copy" semantics (such as fundamentals)
> */
> static public function deepCopy( arr : Array<ArrayUtil.T> ) :
> Array<ArrayUtil.T>
> {
> var r = new Array<ArrayUtil.T>();
> for( i in 0...arr.length )
> {
> if( Std.is( arr[i], Array ) ) //How to do this
> line?!
> r.push( deepCopy( arr[i] ) );
> else
> r.push( arr[i].copy() );
> }
>
> return r;
> }
> }
>
> --
> edA-qa mort-ora-y
> Idea Architect
> http://disemia.com/
>
> Sign: Please digitally sign your emails.
> Encrypt: I'm also happy to receive encrypted mail.
>
>
> --
> haXe - an open source web programming language
> http://haxe.org
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.motion-twin.com/pipermail/haxe/attachments/20070422/29548d12/attachment.htm
More information about the Haxe
mailing list