Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copying an array to another array

Suppose if I have the following array:

(def my-array @[1 2 3 4])

I tried doing:

(array/copy my-array my-array-copy)

but I get an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

compile error: unknown symbol array/copy

>Solution :

You can make a shallow copy:

(def my-array @[1 2 3 4])
(def my-array-copy my-array)

but when you use (set()) with my-array, it will be reflected in my-array-copy:

# 3 -> 69
(set (my-array 2) 69)
my-array-copy # Output: @[1 2 69 4])

If you don’t want any changes in my-array to be reflected in my-array-copy then
use a while or each loop to copy the elements to the new array:

(def my-array @[1 2 3 4])
(def my-array-copy (array/new (length my-array)))

(var counter 0)
(while (< counter (length my-array))
    (put my-array-copy counter (get my-array counter))
    (++ counter))

# If you dislike readability and love hunting for missing brackets
(each number my-array (put my-array-copy counter 
                      (get my-array counter))(++ counter))

(set (my-array 2) 69)
my-array # Output: @[1 2 69 4])
my-array-copy # Output: @[1 2 3 4])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading