Multiple distinct objects: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, made p2js compatible)
m (syntax highlighting fixup automation)
Line 17: Line 17:
{{trans|Python}}
{{trans|Python}}


<lang 11l>(1..n).map(i -> Foo())</lang>
<syntaxhighlight lang="11l">(1..n).map(i -> Foo())</syntaxhighlight>


=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>DEFINE PTR="CARD"
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
DEFINE OBJSIZE="4"
DEFINE OBJSIZE="4"
TYPE Record=[BYTE b CHAR c INT i]
TYPE Record=[BYTE b CHAR c INT i]
Line 76: Line 76:


LMARGIN=oldLMARGIN ;restore left margin on the screen
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Multiple_distinct_objects.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Multiple_distinct_objects.png Screenshot from Atari 8-bit computer]
Line 96: Line 96:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>A : array (1..N) of T;</lang>
<syntaxhighlight lang="ada">A : array (1..N) of T;</syntaxhighlight>
Here N can be unknown until run-time. T is any constrained type. In [[Ada]] all objects are always initialized, though some types may have null initialization. When T requires a non-null initialization, it is done for each array element. For example, when T is a [[task]] type, N tasks start upon initialization of A. Note that T can be a ''limited'' type like task. Limited types do not have predefined copy operation. Arrays of non-limited types can also be initialized by aggregates of:
Here N can be unknown until run-time. T is any constrained type. In [[Ada]] all objects are always initialized, though some types may have null initialization. When T requires a non-null initialization, it is done for each array element. For example, when T is a [[task]] type, N tasks start upon initialization of A. Note that T can be a ''limited'' type like task. Limited types do not have predefined copy operation. Arrays of non-limited types can also be initialized by aggregates of:
<lang ada>A : array (1..N) of T := (others => V);</lang>
<syntaxhighlight lang="ada">A : array (1..N) of T := (others => V);</syntaxhighlight>
Here V is some value or expression of the type T. As an expression V may have side effects, in that case it is evaluated exactly N times, though the order of evaluation is not defined. Also an aggregate itself can be considered as a solution of the task:
Here V is some value or expression of the type T. As an expression V may have side effects, in that case it is evaluated exactly N times, though the order of evaluation is not defined. Also an aggregate itself can be considered as a solution of the task:
<lang ada>(1..N => V)</lang>
<syntaxhighlight lang="ada">(1..N => V)</syntaxhighlight>


=={{header|Aime}}==
=={{header|Aime}}==
<lang aime>void
<syntaxhighlight lang="aime">void
show_sublist(list l)
show_sublist(list l)
{
{
Line 160: Line 160:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> [4] [4] [4] [7] [4] [4] [4] [4]</pre>
<pre> [4] [4] [4] [7] [4] [4] [4] [4]</pre>
Line 170: Line 170:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<lang algol68>MODE FOO = STRUCT(CHAR u,l);
<syntaxhighlight lang="algol68">MODE FOO = STRUCT(CHAR u,l);
INT n := 26;
INT n := 26;
[n]FOO f;
[n]FOO f;
Line 177: Line 177:
FOR i TO UPB f DO f[i] := (REPR(ABS("A")-1+i), REPR(ABS("a")-1+i)) OD;
FOR i TO UPB f DO f[i] := (REPR(ABS("A")-1+i), REPR(ABS("a")-1+i)) OD;


print((f, new line))</lang>
print((f, new line))</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 184: Line 184:


=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
record T ( integer n, m );
record T ( integer n, m );
reference(T) singleT;
reference(T) singleT;
Line 207: Line 207:
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " )
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " )
end
end
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 215: Line 215:


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript>-- MULTIPLE DISTINCT OBJECTS -------------------------------------------------
<syntaxhighlight lang="applescript">-- MULTIPLE DISTINCT OBJECTS -------------------------------------------------


-- nObjects Constructor -> Int -> [Object]
-- nObjects Constructor -> Int -> [Object]
Line 274: Line 274:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}}</lang>
<syntaxhighlight lang="applescript">{{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}}</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
{{works with|AutoHotkey_L}}
<lang AutoHotkey>a := []
<syntaxhighlight lang="autohotkey">a := []
Loop, %n%
Loop, %n%
a[A_Index] := new Foo()</lang>
a[A_Index] := new Foo()</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> REM Determine object count at runtime:
<syntaxhighlight lang="bbcbasic"> REM Determine object count at runtime:
n% = RND(1000)
n% = RND(1000)
Line 302: Line 302:
FOR i% = 0 TO DIM(objects%(),1)
FOR i% = 0 TO DIM(objects%(),1)
objects%(i%) = object{}
objects%(i%) = object{}
NEXT</lang>
NEXT</syntaxhighlight>


=={{header|Brat}}==
=={{header|Brat}}==
The wrong way, which creates an array of ''n'' references to the same new ''foo'':
The wrong way, which creates an array of ''n'' references to the same new ''foo'':


<lang brat>n.of foo.new</lang>
<syntaxhighlight lang="brat">n.of foo.new</syntaxhighlight>


The right way, which calls the block ''n'' times and creates an array of new ''foo''s:
The right way, which calls the block ''n'' times and creates an array of new ''foo''s:


<lang brat>n.of { foo.new }</lang>
<syntaxhighlight lang="brat">n.of { foo.new }</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>foo *foos = malloc(n * sizeof(*foos));
<syntaxhighlight lang="c">foo *foos = malloc(n * sizeof(*foos));
for (int i = 0; i < n; i++)
for (int i = 0; i < n; i++)
init_foo(&foos[i]);</lang>
init_foo(&foos[i]);</syntaxhighlight>


(Or if no particular initialization is needed, skip that part, or use <tt>calloc</tt>.)
(Or if no particular initialization is needed, skip that part, or use <tt>calloc</tt>.)
Line 322: Line 322:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Linq;
using System.Collections.Generic;
using System.Collections.Generic;


List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();</lang>
List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Line 332: Line 332:


Using only language primitives:
Using only language primitives:
<lang cpp>// this assumes T is a default-constructible type (all built-in types are)
<syntaxhighlight lang="cpp">// this assumes T is a default-constructible type (all built-in types are)
T* p = new T[n]; // if T is POD, the objects are uninitialized, otherwise they are default-initialized
T* p = new T[n]; // if T is POD, the objects are uninitialized, otherwise they are default-initialized


Line 340: Line 340:


// when you don't need the objects any more, get rid of them
// when you don't need the objects any more, get rid of them
delete[] p;</lang>
delete[] p;</syntaxhighlight>


Using the standard library
Using the standard library
<lang cpp>#include <vector>
<syntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <algorithm>
#include <iterator>
#include <iterator>
Line 355: Line 355:
// To initialise each value differently
// To initialise each value differently
std::generate_n(std::back_inserter(vec), n, makeT); //makeT is a function of type T(void)
std::generate_n(std::back_inserter(vec), n, makeT); //makeT is a function of type T(void)
</syntaxhighlight>
</lang>


In C++ reference semantics are achieved by holding objects by pointer. Here is an example of the error, and a correct way of achieving distinctness.
In C++ reference semantics are achieved by holding objects by pointer. Here is an example of the error, and a correct way of achieving distinctness.
Line 361: Line 361:
These examples assume T has a public copy constructor, and that p is a pointer to T;
These examples assume T has a public copy constructor, and that p is a pointer to T;


<lang cpp>#include <vector>
<syntaxhighlight lang="cpp">#include <vector>
#include <tr1/memory>
#include <tr1/memory>
using namespace std;
using namespace std;
Line 384: Line 384:
bvec2.push_back(TPtr_t(new T(*p));
bvec2.push_back(TPtr_t(new T(*p));


</syntaxhighlight>
</lang>
Of course, also in this case one can use the other sequence containers or plain new/delete instead of <tt>vector</tt>.
Of course, also in this case one can use the other sequence containers or plain new/delete instead of <tt>vector</tt>.


=={{header|Clojure}}==
=={{header|Clojure}}==
An example using pseudo-random numbers:
An example using pseudo-random numbers:
<lang clojure>user> (take 3 (repeat (rand))) ; repeating the same random number three times
<syntaxhighlight lang="clojure">user> (take 3 (repeat (rand))) ; repeating the same random number three times
(0.2787011365537204 0.2787011365537204 0.2787011365537204)
(0.2787011365537204 0.2787011365537204 0.2787011365537204)
user> (take 3 (repeatedly rand)) ; creating three different random number
user> (take 3 (repeatedly rand)) ; creating three different random number
(0.8334795669220695 0.08405601245793926 0.5795448744634744)
(0.8334795669220695 0.08405601245793926 0.5795448744634744)
user></lang>
user></syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
The mistake is often written as one of these:
The mistake is often written as one of these:
<lang lisp>(make-list n :initial-element (make-the-distinct-thing))
<syntaxhighlight lang="lisp">(make-list n :initial-element (make-the-distinct-thing))
(make-array n :initial-element (make-the-distinct-thing))</lang>
(make-array n :initial-element (make-the-distinct-thing))</syntaxhighlight>
which are incorrect since the form <code>(make-the-distinct-thing)</code> is only evaluated once and the single object is put in every position of the sequence. A commonly used correct version is:
which are incorrect since the form <code>(make-the-distinct-thing)</code> is only evaluated once and the single object is put in every position of the sequence. A commonly used correct version is:
<lang lisp>(loop repeat n collect (make-the-distinct-thing))</lang>
<syntaxhighlight lang="lisp">(loop repeat n collect (make-the-distinct-thing))</syntaxhighlight>
which evaluates <code>(make-the-distinct-thing)</code> <var>n</var> times and collects each result in a list.
which evaluates <code>(make-the-distinct-thing)</code> <var>n</var> times and collects each result in a list.


It is also possible to use <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_map_in.htm map-into]</code>, the destructive map operation, to do this since it may take zero input sequences; this method can produce any sequence type, such as a vector (array) rather than a list, and takes a function rather than a form to specify the thing created:
It is also possible to use <code>[http://www.lispworks.com/documentation/HyperSpec/Body/f_map_in.htm map-into]</code>, the destructive map operation, to do this since it may take zero input sequences; this method can produce any sequence type, such as a vector (array) rather than a list, and takes a function rather than a form to specify the thing created:


<lang lisp>(map-into (make-list n) #'make-the-distinct-thing)
<syntaxhighlight lang="lisp">(map-into (make-list n) #'make-the-distinct-thing)
(map-into (make-array n) #'make-the-distinct-thing)</lang>
(map-into (make-array n) #'make-the-distinct-thing)</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
For reference types (classes):
For reference types (classes):
<lang d>auto fooArray = new Foo[n];
<syntaxhighlight lang="d">auto fooArray = new Foo[n];
foreach (ref item; fooArray)
foreach (ref item; fooArray)
item = new Foo();
item = new Foo();
</syntaxhighlight>
</lang>


For value types:
For value types:
<lang d>auto barArray = new Bar[n];
<syntaxhighlight lang="d">auto barArray = new Bar[n];
barArray[] = initializerValue;</lang>
barArray[] = initializerValue;</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==


Same object accessed multiple times (bad)
Same object accessed multiple times (bad)
<syntaxhighlight lang="delphi">var
<lang Delphi>var
i: Integer;
i: Integer;
lObject: TMyObject;
lObject: TMyObject;
Line 431: Line 431:
for i := 1 to 10 do
for i := 1 to 10 do
lList.Add(lObject);
lList.Add(lObject);
// ...</lang>
// ...</syntaxhighlight>


Distinct objects (good)
Distinct objects (good)
<syntaxhighlight lang="delphi">var
<lang Delphi>var
i: Integer;
i: Integer;
lList: TObjectList<TMyObject>;
lList: TObjectList<TMyObject>;
Line 441: Line 441:
for i := 1 to 10 do
for i := 1 to 10 do
lList.Add(TMyObject.Create);
lList.Add(TMyObject.Create);
// ...</lang>
// ...</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
Line 447: Line 447:
[[Category:E examples needing attention]] E needs development of better map/filter/stream facilities. The easiest way to do this so far is with the accumulator syntax, which is officially experimental because we're not satisfied with it as yet.
[[Category:E examples needing attention]] E needs development of better map/filter/stream facilities. The easiest way to do this so far is with the accumulator syntax, which is officially experimental because we're not satisfied with it as yet.


<lang e>pragma.enable("accumulator")
<syntaxhighlight lang="e">pragma.enable("accumulator")
...
...


accum [] for _ in 1..n { _.with(makeWhatever()) }</lang>
accum [] for _ in 1..n { _.with(makeWhatever()) }</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang="scheme">
;; wrong - make-vector is evaluated one time - same vector
;; wrong - make-vector is evaluated one time - same vector


Line 469: Line 469:


L → (#(0 🔵 0 0) #(0 0 0 0) #(0 0 0 0)) ;; OK
L → (#(0 🔵 0 0) #(0 0 0 0) #(0 0 0 0)) ;; OK
</syntaxhighlight>
</lang>
=={{header|Elena}}==
=={{header|Elena}}==
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import extensions;
import extensions;


Line 484: Line 484:
{
{
var foos := fill(10);
var foos := fill(10);
}</lang>
}</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>randoms = for _ <- 1..10, do: :rand.uniform(1000)</lang>
<syntaxhighlight lang="elixir">randoms = for _ <- 1..10, do: :rand.uniform(1000)</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 497: Line 497:
=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
The wrong way:
The wrong way:
<lang fsharp>>List.replicate 3 (System.Guid.NewGuid());;
<syntaxhighlight lang="fsharp">>List.replicate 3 (System.Guid.NewGuid());;


val it : Guid list =
val it : Guid list =
[485632d7-1fd6-4d9e-8910-7949d7b2b485; 485632d7-1fd6-4d9e-8910-7949d7b2b485;
[485632d7-1fd6-4d9e-8910-7949d7b2b485; 485632d7-1fd6-4d9e-8910-7949d7b2b485;
485632d7-1fd6-4d9e-8910-7949d7b2b485]</lang>
485632d7-1fd6-4d9e-8910-7949d7b2b485]</syntaxhighlight>


The right way:
The right way:
<lang fsharp>> List.init 3 (fun _ -> System.Guid.NewGuid());;
<syntaxhighlight lang="fsharp">> List.init 3 (fun _ -> System.Guid.NewGuid());;


val it : Guid list =
val it : Guid list =
[447acb0c-092e-4f85-9c3a-d369e4539dae; 5f41c04d-9bc0-4e96-8165-76b41fe8cd93;
[447acb0c-092e-4f85-9c3a-d369e4539dae; 5f41c04d-9bc0-4e96-8165-76b41fe8cd93;
1086400c-72ff-4763-9bb9-27e17bd4c7d2]</lang>
1086400c-72ff-4763-9bb9-27e17bd4c7d2]</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
clone is the important word here to have distinct objects. This creates an array of arrays.
clone is the important word here to have distinct objects. This creates an array of arrays.
<lang factor>1000 [ { 1 } clone ] replicate</lang>
<syntaxhighlight lang="factor">1000 [ { 1 } clone ] replicate</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
The value of n can be determined at runtime, and the array is automatically initialized to zeroes.
The value of n can be determined at runtime, and the array is automatically initialized to zeroes.
<lang freebasic>dim as foo array(1 to n)</lang>
<syntaxhighlight lang="freebasic">dim as foo array(1 to n)</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
Line 524: Line 524:
Needs the FMS-SI (single inheritance) library code located here:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
http://soton.mpeforth.com/flag/fms/index.html
<lang forth>include FMS-SI.f
<syntaxhighlight lang="forth">include FMS-SI.f
include FMS-SILib.f
include FMS-SILib.f


Line 547: Line 547:
list each: drop . 1301600
list each: drop . 1301600
list each: drop . 1301600
list each: drop . 1301600
</syntaxhighlight>
</lang>


=={{header|Fortran}}==
=={{header|Fortran}}==


<lang fortran>
<syntaxhighlight lang="fortran">
program multiple
program multiple
! Define a simple type
! Define a simple type
Line 594: Line 594:


end program multiple
end program multiple
</syntaxhighlight>
</lang>


=={{header|Go}}==
=={{header|Go}}==
Useful:
Useful:
<lang go>func nxm(n, m int) [][]int {
<syntaxhighlight lang="go">func nxm(n, m int) [][]int {
d2 := make([][]int, n)
d2 := make([][]int, n)
for i := range d2 {
for i := range d2 {
Line 604: Line 604:
}
}
return d2
return d2
}</lang>
}</syntaxhighlight>
Probably not what the programmer wanted:
Probably not what the programmer wanted:
<lang go>func nxm(n, m int) [][]int {
<syntaxhighlight lang="go">func nxm(n, m int) [][]int {
d1 := make([]int, m)
d1 := make([]int, m)
d2 := make([][]int, n)
d2 := make([][]int, n)
Line 613: Line 613:
}
}
return d2
return d2
}</lang>
}</syntaxhighlight>


=={{header|Groovy}}==
=={{header|Groovy}}==


Correct Solution:
Correct Solution:
<lang groovy>def createFoos1 = { n -> (0..<n).collect { new Foo() } }</lang>
<syntaxhighlight lang="groovy">def createFoos1 = { n -> (0..<n).collect { new Foo() } }</syntaxhighlight>


Incorrect Solution:
Incorrect Solution:
<lang groovy>// Following fails, creates n references to same object
<syntaxhighlight lang="groovy">// Following fails, creates n references to same object
def createFoos2 = {n -> [new Foo()] * n }</lang>
def createFoos2 = {n -> [new Foo()] * n }</syntaxhighlight>


Test:
Test:
<lang groovy>[createFoos1, createFoos2].each { createFoos ->
<syntaxhighlight lang="groovy">[createFoos1, createFoos2].each { createFoos ->
print "Objects distinct for n = "
print "Objects distinct for n = "
(2..<20).each { n ->
(2..<20).each { n ->
Line 637: Line 637:
}
}
println()
println()
}</lang>
}</syntaxhighlight>


Output:
Output:
Line 654: Line 654:


Below, we are assuming that <tt>makeTheDistinctThing</tt> is a monadic expression (i.e. it has type <code>m a</code> where <code>m</code> is some monad, like <code>IO</code> or <code>ST</code>), and we are talking about distinctness in the context of the monad. Otherwise, this task is pretty meaningless in Haskell, because Haskell is referentially transparent (so two values that are equal to the same expression are necessarily not distinct) and all values are immutable.
Below, we are assuming that <tt>makeTheDistinctThing</tt> is a monadic expression (i.e. it has type <code>m a</code> where <code>m</code> is some monad, like <code>IO</code> or <code>ST</code>), and we are talking about distinctness in the context of the monad. Otherwise, this task is pretty meaningless in Haskell, because Haskell is referentially transparent (so two values that are equal to the same expression are necessarily not distinct) and all values are immutable.
<lang haskell>replicateM n makeTheDistinctThing</lang>
<syntaxhighlight lang="haskell">replicateM n makeTheDistinctThing</syntaxhighlight>
in an appropriate do block. If it is distinguished by, say, a numeric label, one could write
in an appropriate do block. If it is distinguished by, say, a numeric label, one could write
<lang haskell>mapM makeTheDistinctThing [1..n]</lang>
<syntaxhighlight lang="haskell">mapM makeTheDistinctThing [1..n]</syntaxhighlight>


An incorrect version:
An incorrect version:
<lang haskell>do x <- makeTheDistinctThing
<syntaxhighlight lang="haskell">do x <- makeTheDistinctThing
return (replicate n x)</lang>
return (replicate n x)</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 666: Line 666:
An incorrect approach uses, e.g., the list constructor procedure with an initial value:
An incorrect approach uses, e.g., the list constructor procedure with an initial value:


<syntaxhighlight lang="icon">
<lang Icon>
items_wrong := list (10, [])
items_wrong := list (10, [])
# prints '0' for size of each item
# prints '0' for size of each item
Line 674: Line 674:
# now prints '1' for size of each item
# now prints '1' for size of each item
every item := !items_wrong do write (*item)
every item := !items_wrong do write (*item)
</syntaxhighlight>
</lang>


A correct approach initialises each element separately:
A correct approach initialises each element separately:


<syntaxhighlight lang="icon">
<lang Icon>
items := list(10)
items := list(10)
every i := 1 to 10 do items[i] := []
every i := 1 to 10 do items[i] := []
</syntaxhighlight>
</lang>


=={{header|J}}==
=={{header|J}}==
<lang J>i.</lang>
<syntaxhighlight lang="j">i.</syntaxhighlight>


Example use:
Example use:


<lang J> i. 4
<syntaxhighlight lang="j"> i. 4
0 1 2 3</lang>
0 1 2 3</syntaxhighlight>


J almost always uses pass-by-value, so this topic is not very relevant to J.
J almost always uses pass-by-value, so this topic is not very relevant to J.
Line 698: Line 698:
{{works with|Java|1.5+}}
{{works with|Java|1.5+}}
simple array:
simple array:
<lang java>Foo[] foos = new Foo[n]; // all elements initialized to null
<syntaxhighlight lang="java">Foo[] foos = new Foo[n]; // all elements initialized to null
for (int i = 0; i < foos.length; i++)
for (int i = 0; i < foos.length; i++)
foos[i] = new Foo();
foos[i] = new Foo();
Line 704: Line 704:
// incorrect version:
// incorrect version:
Foo[] foos_WRONG = new Foo[n];
Foo[] foos_WRONG = new Foo[n];
Arrays.fill(foos, new Foo()); // new Foo() only evaluated once</lang>
Arrays.fill(foos, new Foo()); // new Foo() only evaluated once</syntaxhighlight>


simple list:
simple list:
<lang java5>List<Foo> foos = new ArrayList<Foo>();
<syntaxhighlight lang="java5">List<Foo> foos = new ArrayList<Foo>();
for (int i = 0; i < n; i++)
for (int i = 0; i < n; i++)
foos.add(new Foo());
foos.add(new Foo());


// incorrect:
// incorrect:
List<Foo> foos_WRONG = Collections.nCopies(n, new Foo()); // new Foo() only evaluated once</lang>
List<Foo> foos_WRONG = Collections.nCopies(n, new Foo()); // new Foo() only evaluated once</syntaxhighlight>


Generic version for class given at runtime:
Generic version for class given at runtime:


It's not pretty but it gets the job done. The first method here is the one that does the work. The second method is a convenience method so that you can pass in a <tt>String</tt> of the class name. When using the second method, be sure to use the full class name (ex: "java.lang.String" for "String"). <tt>InstantiationException</tt>s will be thrown when instantiating classes that you would not normally be able to call <tt>new</tt> on (abstract classes, interfaces, etc.). Also, this only works on classes that have a no-argument constructor, since we are using <code>newInstance()</code>.
It's not pretty but it gets the job done. The first method here is the one that does the work. The second method is a convenience method so that you can pass in a <tt>String</tt> of the class name. When using the second method, be sure to use the full class name (ex: "java.lang.String" for "String"). <tt>InstantiationException</tt>s will be thrown when instantiating classes that you would not normally be able to call <tt>new</tt> on (abstract classes, interfaces, etc.). Also, this only works on classes that have a no-argument constructor, since we are using <code>newInstance()</code>.
<lang java5>public static <E> List<E> getNNewObjects(int n, Class<? extends E> c){
<syntaxhighlight lang="java5">public static <E> List<E> getNNewObjects(int n, Class<? extends E> c){
List<E> ans = new LinkedList<E>();
List<E> ans = new LinkedList<E>();
try {
try {
Line 733: Line 733:
throws ClassNotFoundException{
throws ClassNotFoundException{
return getNNewObjects(n, Class.forName(className));
return getNNewObjects(n, Class.forName(className));
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 739: Line 739:
===ES5===
===ES5===


<lang javascript>var a = new Array(n);
<syntaxhighlight lang="javascript">var a = new Array(n);
for (var i = 0; i < n; i++)
for (var i = 0; i < n; i++)
a[i] = new Foo();</lang>
a[i] = new Foo();</syntaxhighlight>




===ES6===
===ES6===


<lang JavaScript>(n => {
<syntaxhighlight lang="javascript">(n => {


let nObjects = n => Array.from({
let nObjects = n => Array.from({
Line 759: Line 759:
return nObjects(6);
return nObjects(6);


})(6);</lang>
})(6);</syntaxhighlight>




{{Out}}
{{Out}}
<lang JavaScript>[{"index":0}, {"index":1}, {"index":2}, {"index":3},
<syntaxhighlight lang="javascript">[{"index":0}, {"index":1}, {"index":2}, {"index":3},
{"index":4}, {"index":5}, {"index":6}]</lang>
{"index":4}, {"index":5}, {"index":6}]</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
jq does not have mutable data types, and therefore in the context of jq, the given task is probably of little interest. However, it is possible to fulfill the task requirements for jq types other than "null" and "boolean":<lang jq>
jq does not have mutable data types, and therefore in the context of jq, the given task is probably of little interest. However, it is possible to fulfill the task requirements for jq types other than "null" and "boolean":<syntaxhighlight lang="jq">
def Array(atype; n):
def Array(atype; n):
if atype == "number" then [ range(0;n) ]
if atype == "number" then [ range(0;n) ]
Line 786: Line 786:
# Example:
# Example:


Array("object"; 4)</lang>
Array("object"; 4)</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
A potential mistake would be writing:
A potential mistake would be writing:
<syntaxhighlight lang="julia">
<lang Julia>
foo() = rand() # repeated calls change the result with each call
foo() = rand() # repeated calls change the result with each call
repeat([foo()], outer=5) # but this only calls foo() once, clones that first value
repeat([foo()], outer=5) # but this only calls foo() once, clones that first value
</syntaxhighlight>
</lang>
If the effect of calling foo() with every iteration is desired, better to use:
If the effect of calling foo() with every iteration is desired, better to use:
<syntaxhighlight lang="julia">
<lang Julia>
[foo() for i in 1:5] # Code this to call the function within each iteration
[foo() for i in 1:5] # Code this to call the function within each iteration
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


class Foo {
class Foo {
Line 825: Line 825:
val fooList2 = List(n) { f }
val fooList2 = List(n) { f }
for (foo in fooList2) println(foo.id)
for (foo in fooList2) println(foo.id)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 841: Line 841:
We construct an array of the appropriate length and then replace each element with a new object.
We construct an array of the appropriate length and then replace each element with a new object.


<lang latitude>arr := n times to (Array) map { Object clone. }.</lang>
<syntaxhighlight lang="latitude">arr := n times to (Array) map { Object clone. }.</syntaxhighlight>


We can verify that these are in fact distinct objects by checking their ID.
We can verify that these are in fact distinct objects by checking their ID.


<lang latitude>;; Will print 10 distinct, arbitrary numbers.
<syntaxhighlight lang="latitude">;; Will print 10 distinct, arbitrary numbers.
arr visit {
arr visit {
Kernel id printObject.
Kernel id printObject.
}.</lang>
}.</syntaxhighlight>


=={{header|Logtalk}}==
=={{header|Logtalk}}==
Using prototypes, we first dynamically create a protocol to declare a predicate and then create ten prototypes implementing that protocol, which one with a different definition for the predicate:
Using prototypes, we first dynamically create a protocol to declare a predicate and then create ten prototypes implementing that protocol, which one with a different definition for the predicate:
<lang logtalk>
<syntaxhighlight lang="logtalk">
| ?- create_protocol(statep, [], [public(state/1)]),
| ?- create_protocol(statep, [], [public(state/1)]),
findall(
findall(
Line 861: Line 861:
).
).
Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].
Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].
</syntaxhighlight>
</lang>
Using classes, we first dynamically create a class (that is its own metaclass) to declare a predicate (and define a default value for it) and then create ten instances of the class, which one with a different definition for the predicate:
Using classes, we first dynamically create a class (that is its own metaclass) to declare a predicate (and define a default value for it) and then create ten instances of the class, which one with a different definition for the predicate:
<lang logtalk>
<syntaxhighlight lang="logtalk">
| ?- create_object(state, [instantiates(state)], [public(state/1)], [state(0)]),
| ?- create_object(state, [instantiates(state)], [public(state/1)], [state(0)]),
findall(
findall(
Line 872: Line 872:
).
).
Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].
Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].
</syntaxhighlight>
</lang>


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>-- This concept is relevant to tables in Lua
<syntaxhighlight lang="lua">-- This concept is relevant to tables in Lua
local table1 = {1,2,3}
local table1 = {1,2,3}


Line 891: Line 891:
-- Now we can create a table of independent copies of table1
-- Now we can create a table of independent copies of table1
local copyTab = {}
local copyTab = {}
for i = 1, 10 do copyTab[i] = copy(table1) end</lang>
for i = 1, 10 do copyTab[i] = copy(table1) end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
Module CheckIt {
Form 60, 40
Form 60, 40
Line 936: Line 936:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The mistake is often written as:
The mistake is often written as:
<lang Mathematica>{x, x, x, x} /. x -> Random[]</lang>
<syntaxhighlight lang="mathematica">{x, x, x, x} /. x -> Random[]</syntaxhighlight>


Here Random[] can be any expression that returns a new value which is incorrect since Random[] is only evaluated once. e.g.
Here Random[] can be any expression that returns a new value which is incorrect since Random[] is only evaluated once. e.g.
Line 947: Line 947:
A correct version is:
A correct version is:


<lang Mathematica>{x, x, x, x} /. x :> Random[]</lang>
<syntaxhighlight lang="mathematica">{x, x, x, x} /. x :> Random[]</syntaxhighlight>
which evaluates Random[] each time e.g.
which evaluates Random[] each time e.g.
Line 953: Line 953:


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>a: [1, 2]$
<syntaxhighlight lang="maxima">a: [1, 2]$


b: makelist(copy(a), 3);
b: makelist(copy(a), 3);
Line 961: Line 961:


b;
b;
[[1,1000],[1,2],[1,2]]</lang>
[[1,1000],[1,2],[1,2]]</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
Similar to the [[Ada]] version above:
Similar to the [[Ada]] version above:
<lang modula3>VAR a: ARRAY[1..N] OF T</lang>
<syntaxhighlight lang="modula3">VAR a: ARRAY[1..N] OF T</syntaxhighlight>
This creates an array of distinct elements of type <code>T</code>. A type may specify a default value for its fields, so long as the values are compile-time constants. Similarly, an array can initialize its entries to multiple different values, also compile-time constants. Naturally, a program may initialize this data at run-time using a <code>FOR</code> loop.
This creates an array of distinct elements of type <code>T</code>. A type may specify a default value for its fields, so long as the values are compile-time constants. Similarly, an array can initialize its entries to multiple different values, also compile-time constants. Naturally, a program may initialize this data at run-time using a <code>FOR</code> loop.


Line 971: Line 971:


The example program below demonstrates each of these methods, including the mistaken way, so is a bit long.
The example program below demonstrates each of these methods, including the mistaken way, so is a bit long.
<lang modula3>MODULE DistinctObjects EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE DistinctObjects EXPORTS Main;


IMPORT IO, Random;
IMPORT IO, Random;
Line 1,026: Line 1,026:
IO.PutChar('\n');
IO.PutChar('\n');


END DistinctObjects.</lang>
END DistinctObjects.</syntaxhighlight>
{{out}}
{{out}}
Each line interleaves the initial values of <code>a</code> and <code>b</code>. The first one has default values; the second replaces the values of <code>a</code> with random, "re-initialized" integers. Only <code>a[3]</code> starts with the default value for <code>T</code>; see the seventh number in the first line. On the other hand, the modification of "one" element of <code>c</code> actually modifies every element, precisely because it is a reference and not an object.
Each line interleaves the initial values of <code>a</code> and <code>b</code>. The first one has default values; the second replaces the values of <code>a</code> with random, "re-initialized" integers. Only <code>a[3]</code> starts with the default value for <code>T</code>; see the seventh number in the first line. On the other hand, the modification of "one" element of <code>c</code> actually modifies every element, precisely because it is a reference and not an object.
Line 1,037: Line 1,037:


Incorrect, same object n times:
Incorrect, same object n times:
<lang NGS>{ [foo()] * n }</lang>
<syntaxhighlight lang="ngs">{ [foo()] * n }</syntaxhighlight>


Correct:
Correct:
<lang NGS>{ foo * n }</lang>
<syntaxhighlight lang="ngs">{ foo * n }</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
Line 1,047: Line 1,047:
We give some examples with sequences of sequences and sequences of references:
We give some examples with sequences of sequences and sequences of references:


<lang Nim>import sequtils, strutils
<syntaxhighlight lang="nim">import sequtils, strutils


# Creating a sequence containing sequences of integers.
# Creating a sequence containing sequences of integers.
Line 1,076: Line 1,076:
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1
s4[0][] = 2
s4[0][] = 2
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 2, 2, 2, 2, 2</lang>
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 2, 2, 2, 2, 2</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 1,082: Line 1,082:


Incorrect:
Incorrect:
<lang ocaml>Array.make n (new foo);;
<syntaxhighlight lang="ocaml">Array.make n (new foo);;
(* here (new foo) can be any expression that returns a new object,
(* here (new foo) can be any expression that returns a new object,
record, array, or string *)</lang>
record, array, or string *)</syntaxhighlight>
which is incorrect since <code>new foo</code> is only evaluated once. A correct version is:
which is incorrect since <code>new foo</code> is only evaluated once. A correct version is:
<lang ocaml>Array.init n (fun _ -> new foo);;</lang>
<syntaxhighlight lang="ocaml">Array.init n (fun _ -> new foo);;</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==
Line 1,092: Line 1,092:
The right way : the block sent as parameter is performed n times :
The right way : the block sent as parameter is performed n times :


<lang Oforth>ListBuffer init(10, #[ Float rand ]) println</lang>
<syntaxhighlight lang="oforth">ListBuffer init(10, #[ Float rand ]) println</syntaxhighlight>


{{out}}
{{out}}
Line 1,103: Line 1,103:
The "wrong" way : the same value is stored n times into the list buffer
The "wrong" way : the same value is stored n times into the list buffer


<lang Oforth>ListBuffer initValue(10, Float rand) println</lang>
<syntaxhighlight lang="oforth">ListBuffer initValue(10, Float rand) println</syntaxhighlight>


{{out}}
{{out}}
Line 1,113: Line 1,113:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>-- get an array of directory objects
<syntaxhighlight lang="oorexx">-- get an array of directory objects
array = fillArrayWith(3, .directory)
array = fillArrayWith(3, .directory)
say "each object will have a different identityHash"
say "each object will have a different identityHash"
Line 1,131: Line 1,131:
end
end


return array</lang>
return array</syntaxhighlight>
{{out}}
{{out}}
<pre>each object will have a different identityHash
<pre>each object will have a different identityHash
Line 1,141: Line 1,141:
=={{header|Oz}}==
=={{header|Oz}}==
With lists, it is difficult to do wrong.
With lists, it is difficult to do wrong.
<lang oz>declare
<syntaxhighlight lang="oz">declare
Xs = {MakeList 5} %% a list of 5 unbound variables
Xs = {MakeList 5} %% a list of 5 unbound variables
in
in
{ForAll Xs OS.rand} %% fill it with random numbers (CORRECT)
{ForAll Xs OS.rand} %% fill it with random numbers (CORRECT)
{Show Xs}</lang>
{Show Xs}</syntaxhighlight>


With arrays on the other hand, it is easy to get wrong:
With arrays on the other hand, it is easy to get wrong:
<lang oz>declare
<syntaxhighlight lang="oz">declare
Arr = {Array.new 0 10 {OS.rand}} %% WRONG: contains ten times the same number
Arr = {Array.new 0 10 {OS.rand}} %% WRONG: contains ten times the same number
in
in
Line 1,154: Line 1,154:
for I in {Array.low Arr}..{Array.high Arr} do
for I in {Array.low Arr}..{Array.high Arr} do
Arr.I := {OS.rand}
Arr.I := {OS.rand}
end</lang>
end</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
Line 1,161: Line 1,161:
=={{header|Perl}}==
=={{header|Perl}}==
incorrect:
incorrect:
<lang perl>(Foo->new) x $n
<syntaxhighlight lang="perl">(Foo->new) x $n
# here Foo->new can be any expression that returns a reference representing
# here Foo->new can be any expression that returns a reference representing
# a new object</lang>
# a new object</syntaxhighlight>
which is incorrect since <code>Foo->new</code> is only evaluated once.
which is incorrect since <code>Foo->new</code> is only evaluated once.


A correct version is:
A correct version is:
<lang perl>map { Foo->new } 1 .. $n;</lang>
<syntaxhighlight lang="perl">map { Foo->new } 1 .. $n;</syntaxhighlight>
which evaluates <tt>Foo->new</tt> <var>$n</var> times and collects each result in a list.
which evaluates <tt>Foo->new</tt> <var>$n</var> times and collects each result in a list.


Line 1,175: Line 1,175:


However, JavaScript uses pass-by-sharing semantics, so if (and only if) we specify "with javascript_semantics" (or just "with js" for short) the last line triggers a "p2js violation" error on desktop/Phix, indicating it must be changed (as shown).
However, JavaScript uses pass-by-sharing semantics, so if (and only if) we specify "with javascript_semantics" (or just "with js" for short) the last line triggers a "p2js violation" error on desktop/Phix, indicating it must be changed (as shown).
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
Line 1,182: Line 1,182:
<span style="color: #000080;font-style:italic;">-- s[2] = s ?s</span>
<span style="color: #000080;font-style:italic;">-- s[2] = s ?s</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 1,192: Line 1,192:
Note that the last statement did not create a circular structure, something that is not possible in Phix, except (perhaps) via index-emulation.<br>
Note that the last statement did not create a circular structure, something that is not possible in Phix, except (perhaps) via index-emulation.<br>
I suppose it is possible that someone could write
I suppose it is possible that someone could write
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">my_func</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">my_func</span><span style="color: #0000FF;">(),</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
and expect my_func() to be invoked 5 times, but for that you need a loop
and expect my_func() to be invoked 5 times, but for that you need a loop
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">my_func</span><span style="color: #0000FF;">()</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">my_func</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
There are in fact two "reference" types in phix: dictionaries and classes, which are created using the function calls new_dict() and new() respectively.<br>
There are in fact two "reference" types in phix: dictionaries and classes, which are created using the function calls new_dict() and new() respectively.<br>
In the same manner as above if you want five distinct dictionaries or classes, you must invoke new_dict()/new() five times.
In the same manner as above if you want five distinct dictionaries or classes, you must invoke new_dict()/new() five times.
Line 1,207: Line 1,207:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
Create 5 distinct (empty) objects:
Create 5 distinct (empty) objects:
<lang PicoLisp>: (make (do 5 (link (new))))
<syntaxhighlight lang="picolisp">: (make (do 5 (link (new))))
-> ($384717187 $384717189 $384717191 $384717193 $384717195)</lang>
-> ($384717187 $384717189 $384717191 $384717193 $384717195)</syntaxhighlight>
Create 5 anonymous symbols with the values 1 .. 5:
Create 5 anonymous symbols with the values 1 .. 5:
<lang PicoLisp>: (mapcar box (range 1 5))
<syntaxhighlight lang="picolisp">: (mapcar box (range 1 5))
-> ($384721107 $384721109 $384721111 $384721113 $384721115)
-> ($384721107 $384721109 $384721111 $384721113 $384721115)
: (val (car @))
: (val (car @))
-> 1
-> 1
: (val (cadr @@))
: (val (cadr @@))
-> 2</lang>
-> 2</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Do some randomization that could easily return three equal values (but each value is a separate value in the array):
Do some randomization that could easily return three equal values (but each value is a separate value in the array):
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} |
1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} |
Select-Object -Unique |
Select-Object -Unique |
ForEach-Object {$_.ToString()}
ForEach-Object {$_.ToString()}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,231: Line 1,231:
</pre>
</pre>
Run the same commands a few times and the <code>Select-Object -Unique</code> command filters equal (but separate values):
Run the same commands a few times and the <code>Select-Object -Unique</code> command filters equal (but separate values):
<syntaxhighlight lang="powershell">
<lang PowerShell>
1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} |
1..3 | ForEach-Object {((Get-Date -Hour ($_ + (1..4 | Get-Random))).AddDays($_ + (1..4 | Get-Random)))} |
Select-Object -Unique |
Select-Object -Unique |
ForEach-Object {$_.ToString()}
ForEach-Object {$_.ToString()}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,243: Line 1,243:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>n=Random(50)+25
<syntaxhighlight lang="purebasic">n=Random(50)+25
Dim A.i(n)
Dim A.i(n)
; Creates a Array of n [25-75] elements depending on the outcome of Random().
; Creates a Array of n [25-75] elements depending on the outcome of Random().
Line 1,267: Line 1,267:
Next
Next
; Verify by sending each value of A() via *PointersToA()
; Verify by sending each value of A() via *PointersToA()
; to the debugger's output.</lang>
; to the debugger's output.</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
The mistake is often written as:
The mistake is often written as:
<lang python>[Foo()] * n # here Foo() can be any expression that returns a new object</lang>
<syntaxhighlight lang="python">[Foo()] * n # here Foo() can be any expression that returns a new object</syntaxhighlight>
which is incorrect since <tt>Foo()</tt> is only evaluated once. A common correct version is:
which is incorrect since <tt>Foo()</tt> is only evaluated once. A common correct version is:
<lang python>[Foo() for i in range(n)]</lang>
<syntaxhighlight lang="python">[Foo() for i in range(n)]</syntaxhighlight>
which evaluates <tt>Foo()</tt> <var>n</var> times and collects each result in a list. This last form is also discussed [[Two-dimensional array (runtime)#Python|here]], on the correct construction of a two dimensional array.
which evaluates <tt>Foo()</tt> <var>n</var> times and collects each result in a list. This last form is also discussed [[Two-dimensional array (runtime)#Python|here]], on the correct construction of a two dimensional array.


=={{header|R}}==
=={{header|R}}==
The mistake is often written as:
The mistake is often written as:
<lang r>rep(foo(), n) # foo() is any code returning a value</lang>
<syntaxhighlight lang="r">rep(foo(), n) # foo() is any code returning a value</syntaxhighlight>
A common correct version is:
A common correct version is:
<lang r>replicate(n, foo())</lang>
<syntaxhighlight lang="r">replicate(n, foo())</syntaxhighlight>
which evaluates foo() n times and collects each result in a list. (Using simplify=TRUE lets the function return an array, where possible.)
which evaluates foo() n times and collects each result in a list. (Using simplify=TRUE lets the function return an array, where possible.)


=={{header|Racket}}==
=={{header|Racket}}==


<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket


Line 1,293: Line 1,293:
;; a list of 10 distinct vectors
;; a list of 10 distinct vectors
(build-list 10 (λ (n) (make-vector 10 0)))
(build-list 10 (λ (n) (make-vector 10 0)))
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,300: Line 1,300:
Unlike in Perl 5, the list repetition operator evaluates the left argument thunk each time, so
Unlike in Perl 5, the list repetition operator evaluates the left argument thunk each time, so


<lang perl6>my @a = Foo.new xx $n;</lang>
<syntaxhighlight lang="raku" line>my @a = Foo.new xx $n;</syntaxhighlight>


produces <code>$n</code> distinct objects.
produces <code>$n</code> distinct objects.
Line 1,307: Line 1,307:
=={{header|REXX}}==
=={{header|REXX}}==
This entry is modeled after the '''Erlang''' entry.
This entry is modeled after the '''Erlang''' entry.
<lang rexx>/*REXX program does a list comprehension that will create N random integers, all unique.*/
<syntaxhighlight lang="rexx">/*REXX program does a list comprehension that will create N random integers, all unique.*/
parse arg n lim . /*obtain optional argument from the CL.*/
parse arg n lim . /*obtain optional argument from the CL.*/
if n=='' | n=="," then n= 1000 /*Not specified? Then use the default.*/
if n=='' | n=="," then n= 1000 /*Not specified? Then use the default.*/
Line 1,323: Line 1,323:
end /*j*/
end /*j*/


say words(randoms) ' unique numbers generated.' /*stick a fork in it, we're all done. */</lang>
say words(randoms) ' unique numbers generated.' /*stick a fork in it, we're all done. */</syntaxhighlight>
<br><br>
<br><br>


=={{header|Ruby}}==
=={{header|Ruby}}==
The mistake is often written as one of these:
The mistake is often written as one of these:
<lang ruby>[Foo.new] * n # here Foo.new can be any expression that returns a new object
<syntaxhighlight lang="ruby">[Foo.new] * n # here Foo.new can be any expression that returns a new object
Array.new(n, Foo.new)</lang>
Array.new(n, Foo.new)</syntaxhighlight>
which are incorrect since <code>Foo.new</code> is only evaluated once, and thus you now have <var>n</var> references to the ''same'' object. A common correct version is:
which are incorrect since <code>Foo.new</code> is only evaluated once, and thus you now have <var>n</var> references to the ''same'' object. A common correct version is:
<lang ruby>Array.new(n) { Foo.new }</lang>
<syntaxhighlight lang="ruby">Array.new(n) { Foo.new }</syntaxhighlight>
which evaluates <code>Foo.new</code> <var>n</var> times and collects each result in an Array. This last form is also discussed [[Two-dimensional array (runtime)#Ruby|here]], on the correct construction of a two dimensional array.
which evaluates <code>Foo.new</code> <var>n</var> times and collects each result in an Array. This last form is also discussed [[Two-dimensional array (runtime)#Ruby|here]], on the correct construction of a two dimensional array.


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>use std::rc::Rc;
<syntaxhighlight lang="rust">use std::rc::Rc;
use std::cell::RefCell;
use std::cell::RefCell;


Line 1,355: Line 1,355:
v[0].borrow_mut().push('a');
v[0].borrow_mut().push('a');
println!("{:?}", v);
println!("{:?}", v);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>["a", "", ""]
<pre>["a", "", ""]
Line 1,365: Line 1,365:
if created with the same constructor arguments.
if created with the same constructor arguments.


<lang scala>for (i <- (0 until n)) yield new Foo()</lang>
<syntaxhighlight lang="scala">for (i <- (0 until n)) yield new Foo()</syntaxhighlight>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 1,396: Line 1,396:
The [http://seed7.sourceforge.net/libraries/array.htm#%28in_integer%29times%28in_baseType%29 times] operator creates a new array value with a specified size.
The [http://seed7.sourceforge.net/libraries/array.htm#%28in_integer%29times%28in_baseType%29 times] operator creates a new array value with a specified size.
Finally multiple distinct objects are assigned to the array elements.
Finally multiple distinct objects are assigned to the array elements.
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func array file: openFiles (in array string: fileNames) is func
const func array file: openFiles (in array string: fileNames) is func
Line 1,415: Line 1,415:
begin
begin
files := openFiles([] ("abc.txt", "def.txt", "ghi.txt", "jkl.txt"));
files := openFiles([] ("abc.txt", "def.txt", "ghi.txt", "jkl.txt"));
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>[Foo.new] * n; # incorrect (only one distinct object is created)</lang>
<syntaxhighlight lang="ruby">[Foo.new] * n; # incorrect (only one distinct object is created)</syntaxhighlight>
<lang ruby>n.of {Foo.new}; # correct</lang>
<syntaxhighlight lang="ruby">n.of {Foo.new}; # correct</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==


<lang smalltalk>|c|
<syntaxhighlight lang="smalltalk">|c|
"Create an ordered collection that will grow while we add elements"
"Create an ordered collection that will grow while we add elements"
c := OrderedCollection new.
c := OrderedCollection new.
Line 1,435: Line 1,435:
1 to: 9 do: [ :i | (c at: i) at: 4 put: i ].
1 to: 9 do: [ :i | (c at: i) at: 4 put: i ].
"show it"
"show it"
c do: [ :e | e printNl ].</lang>
c do: [ :e | e printNl ].</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>class Foo { }
<syntaxhighlight lang="swift">class Foo { }


var foos = [Foo]()
var foos = [Foo]()
Line 1,446: Line 1,446:


// incorrect version:
// incorrect version:
var foos_WRONG = [Foo](count: n, repeatedValue: Foo()) // Foo() only evaluated once</lang>
var foos_WRONG = [Foo](count: n, repeatedValue: Foo()) // Foo() only evaluated once</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
Line 1,452: Line 1,452:


{{works with|Tcl|8.6}} or {{libheader|TclOO}}
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<lang Tcl>package require TclOO
<syntaxhighlight lang="tcl">package require TclOO


# The class that we want to make unique instances of
# The class that we want to make unique instances of
Line 1,464: Line 1,464:
for {set i 0} {$i<$n} {incr i} {
for {set i 0} {$i<$n} {incr i} {
lappend theList [$theClass new]
lappend theList [$theClass new]
}</lang>
}</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>class Foo {
<syntaxhighlight lang="ecmascript">class Foo {
static init() { __count = 0 } // set object counter to zero
static init() { __count = 0 } // set object counter to zero


Line 1,491: Line 1,491:
// Show they're the same by printing out their object numbers
// Show they're the same by printing out their object numbers
foos2.each { |f| System.write("%(f.number) ") }
foos2.each { |f| System.write("%(f.number) ") }
System.print()</lang>
System.print()</syntaxhighlight>


{{out}}
{{out}}
Line 1,501: Line 1,501:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>code Reserve=3, IntIn=10;
<syntaxhighlight lang="xpl0">code Reserve=3, IntIn=10;
char A; int N, I;
char A; int N, I;
[N:= IntIn(8); \get number of items from command line
[N:= IntIn(8); \get number of items from command line
Line 1,507: Line 1,507:
for I:= 0 to N-1 do A(I):= I*3; \initialize items with different values
for I:= 0 to N-1 do A(I):= I*3; \initialize items with different values
for I:= 0 to N-1 do A:= I*3; \error: "references to the same mutable object"
for I:= 0 to N-1 do A:= I*3; \error: "references to the same mutable object"
]</lang>
]</syntaxhighlight>


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>sub test()
<syntaxhighlight lang="yabasic">sub test()
print "Random number: " + str$(ran(100))
print "Random number: " + str$(ran(100))
end sub
end sub
Line 1,529: Line 1,529:
for i = 1 to n
for i = 1 to n
execute(func$(i))
execute(func$(i))
next i</lang>
next i</syntaxhighlight>




Line 1,535: Line 1,535:
Variables in assembly languages don't work the same as they do in high-level languages, so the "n references to the same object mistake" isn't really a thing in your typical assembly language. This is as simple as creating an array of ascending values. Being an 8-bit computer, you're limited in how big <i>n</i> can be before the values repeat.
Variables in assembly languages don't work the same as they do in high-level languages, so the "n references to the same object mistake" isn't really a thing in your typical assembly language. This is as simple as creating an array of ascending values. Being an 8-bit computer, you're limited in how big <i>n</i> can be before the values repeat.


<lang z80>ld hl,RamArea ;a label for an arbitrary section of RAM
<syntaxhighlight lang="z80">ld hl,RamArea ;a label for an arbitrary section of RAM
ld a,(foo) ;load the value of some memory location. "foo" is the label of a 16-bit address.
ld a,(foo) ;load the value of some memory location. "foo" is the label of a 16-bit address.
ld b,a ;use this as a loop counter.
ld b,a ;use this as a loop counter.
Line 1,544: Line 1,544:
inc a ;ensures each value is different.
inc a ;ensures each value is different.
inc hl ;next element of list
inc hl ;next element of list
djnz loop</lang>
djnz loop</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
The pump and partial application methods are useful tools for creating initialized lists.
The pump and partial application methods are useful tools for creating initialized lists.
<lang zkl>n:=3;
<syntaxhighlight lang="zkl">n:=3;
n.pump(List) //-->L(0,1,2)
n.pump(List) //-->L(0,1,2)


Line 1,565: Line 1,565:
class C{ var n; fcn init(x){n=x} }
class C{ var n; fcn init(x){n=x} }
n.pump(List,C) //--> L(C,C,C)
n.pump(List,C) //--> L(C,C,C)
n.pump(List,C).apply("n") //-->L(0,1,2) ie all classes distinct</lang>
n.pump(List,C).apply("n") //-->L(0,1,2) ie all classes distinct</syntaxhighlight>