Multiple distinct objects: Difference between revisions

m
m (Remove from object-oriented category.)
imported>Arakov
 
(38 intermediate revisions by 25 users not shown)
Line 1:
{{task}}
 
Create a [[sequence]] (array, list, whatever) consisting of <var>n</var> distinct, initialized items of the same type. <var>n</var> should be determined at runtime.
 
Line 10 ⟶ 12:
 
See also: [[Closures/Value capture]]
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">(1..n).map(i -> Foo())</syntaxhighlight>
 
=={{header|Action!}}==
<syntaxhighlight lang="action!">DEFINE PTR="CARD"
DEFINE OBJSIZE="4"
TYPE Record=[BYTE b CHAR c INT i]
 
PROC PrintObjects(PTR ARRAY items BYTE count)
Record POINTER r
BYTE n
 
FOR n=0 TO count-1
DO
r=items(n)
PrintF("(%B ""%C"" %I) ",r.b,r.c,r.i)
IF n MOD 3=2 THEN PutE() FI
OD
PutE()
RETURN
 
PROC Main()
DEFINE MIN="1"
DEFINE MAX="20"
DEFINE BUFSIZE="80"
BYTE ARRAY buffer(BUFSIZE)
PTR ARRAY items(MAX)
BYTE count=[0],n,LMARGIN=$52,oldLMARGIN
Record POINTER r
 
oldLMARGIN=LMARGIN
LMARGIN=0 ;remove left margin on the screen
Put(125) PutE() ;clear the screen
 
WHILE count<min OR count>max
DO
PrintF("How many objects (%I-%I)?",MIN,MAX)
count=InputB()
OD
 
FOR n=0 TO count-1
DO
items(n)=buffer+n*OBJSIZE
OD
 
PutE()
PrintE("Uninitialized objects:")
PrintObjects(items,count)
 
FOR n=0 TO count-1
DO
r=items(n)
r.b=n r.c=n+'A r.i=-n
OD
 
PutE()
PrintE("Initialized objects:")
PrintObjects(items,count)
 
LMARGIN=oldLMARGIN ;restore left margin on the screen
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Multiple_distinct_objects.png Screenshot from Atari 8-bit computer]
<pre>
How many objects (1-20)?20
 
Uninitialized objects:
(0 "♥" 80) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0)
(0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0)
(0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0) (0 "♥" 0)
(0 "♥" 0) (0 "♥" 0)
 
Initialized objects:
(0 "A" 0) (1 "B" -1) (2 "C" -2) (3 "D" -3) (4 "E" -4) (5 "F" -5)
(6 "G" -6) (7 "H" -7) (8 "I" -8) (9 "J" -9) (10 "K" -10) (11 "L" -11)
(12 "M" -12) (13 "N" -13) (14 "O" -14) (15 "P" -15) (16 "Q" -16) (17 "R" -17)
(18 "S" -18) (19 "T" -19)
</pre>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">A : array (1..N) of T;</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="ada">A : array (1..N) of T := (others => V);</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="ada">(1..N => V)</langsyntaxhighlight>
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">void
show_sublist(list l)
{
integer i, v;
 
for (i, v in =l) 0;{
while (i < l_length o_space(lsign(i)) {;
if o_integer(iv) {;
o_space(1);
}
o_integer(l_q_integer(l, i));
i += 1;
}
}
Line 38 ⟶ 118:
{
integer i;
list v;
 
for (i, v in =l) 0;{
while (i < l_length(l)) {
o_text(" [");
show_sublist(l_q_list(l, i)v);
o_text("]");
i += 1;
}
 
Line 55 ⟶ 134:
list l;
 
while call_n(n), {l_append, l, o);
l_append(l, o);
n -= 1;
}
 
return l;
Line 78 ⟶ 154:
 
# modify one of the sublists
l_r_integer(l_q_list(l, 3), [0,] = 7);
 
# display the list of lists
Line 84 ⟶ 160:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre> [4] [4] [4] [7] [4] [4] [4] [4]</pre>
Line 94 ⟶ 170:
{{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}}
<langsyntaxhighlight lang="algol68">MODE FOO = STRUCT(CHAR u,l);
INT n := 26;
[n]FOO f;
Line 101 ⟶ 177:
FOR i TO UPB f DO f[i] := (REPR(ABS("A")-1+i), REPR(ABS("a")-1+i)) OD;
 
print((f, new line))</langsyntaxhighlight>
Output:
<pre>
Line 107 ⟶ 183:
</pre>
 
=={{header|ALGOL W}}==
<syntaxhighlight lang="algolw">begin
record T ( integer n, m );
reference(T) singleT;
integer numberOfElements;
singleT := T( 0, 0 );
numberOfElements := 3;
begin
reference(T) array tArray ( 1 :: numberOfElements );
% initialise the "right" way %
for i := 1 until numberOfElements do begin
tArray( i ) := T( i, i * 2 );
m(tArray( i )) := m(tArray( i )) + 1;
end for_i ;
write();
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " );
% initialise the "wrong" way %
for i := 1 until numberOfElements do begin
tArray( i ) := singleT;
m(tArray( i )) := m(tArray( i )) + 1;
end for_i ;
write();
for i := 1 until numberOfElements do writeon( i_w := 1, s_w := 0, n(tArray( i )), ", ", m(tArray( i )), "; " )
end
end.</syntaxhighlight>
{{out}}
<pre>
1, 3; 2, 5; 3, 7;
0, 3; 0, 3; 0, 3;
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">-- MULTIPLE DISTINCT OBJECTS -------------------------------------------------
 
-- nObjects Constructor -> Int -> [Object]
<lang AppleScript>
--on nObjects(f, Int -> Constructor -> [Object]n)
map(f, enumFromTo(1, n))
on nObjects(n, foo)
map(foo, range(1, n))
end nObjects
 
-- TEST ----------------------------------------------------------------------
 
-- TEST
 
on run
nObjects(6,-- someConstructor) :: a -> Int -> b
script someConstructor
end run
on |λ|(_, i)
 
{index:i}
-- someConstructor :: a -> Int -> b
end |λ|
on someConstructor(_, i)
{index:i}
end someConstructor
 
 
 
 
 
-- GENERIC LIBRARY FUNCTIONS
 
-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
script mf
property lambda : f
end script
nObjects(someConstructor, 6)
set lng to length of xs
set lst to {}
--> {{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}}
repeat with i from 1 to lng
end run
set end of lst to mf's lambda(item i of xs, i, xs)
 
end repeat
-- GENERIC FUNCTIONS ---------------------------------------------------------
return lst
end map
 
-- rangeenumFromTo :: Int -> Int -> [Int]
on rangeenumFromTo(m, n)
if nm <> mn then
set d to -1
else
Line 160 ⟶ 250:
end repeat
return lst
end rangeenumFromTo
 
-- map :: (a -> b) -> [a] -> [b]
</lang>
on map(f, xs)
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map
 
-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then
f
else
script
property |λ| : f
end script
end if
end mReturn</syntaxhighlight>
{{Out}}
<langsyntaxhighlight AppleScriptlang="applescript">{{index:1}, {index:2}, {index:3}, {index:4}, {index:5}, {index:6}}</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">a := []
Loop, %n%
a[A_Index] := new Foo()</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> REM Determine object count at runtime:
n% = RND(1000)
Line 191 ⟶ 302:
FOR i% = 0 TO DIM(objects%(),1)
objects%(i%) = object{}
NEXT</langsyntaxhighlight>
 
=={{header|Brat}}==
The wrong way, which creates an array of ''n'' references to the same new ''foo'':
 
<syntaxhighlight lang ="brat">n.of foo.new</langsyntaxhighlight>
 
The right way, which calls the block ''n'' times and creates an array of new ''foo''s:
 
<langsyntaxhighlight lang="brat">n.of { foo.new }</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">foo *foos = malloc(n * sizeof(*foos));
for (int i = 0; i < n; i++)
init_foo(&foos[i]);</langsyntaxhighlight>
 
(Or if no particular initialization is needed, skip that part, or use <tt>calloc</tt>.)
 
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Collections.Generic;
 
List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();</syntaxhighlight>
 
=={{header|C++}}==
Line 213 ⟶ 332:
 
Using only language primitives:
<langsyntaxhighlight 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
 
Line 221 ⟶ 340:
 
// when you don't need the objects any more, get rid of them
delete[] p;</langsyntaxhighlight>
 
Using the standard library
<langsyntaxhighlight lang="cpp">#include <vector>
#include <algorithm>
#include <iterator>
Line 236 ⟶ 355:
// To initialise each value differently
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.
Line 242 ⟶ 361:
These examples assume T has a public copy constructor, and that p is a pointer to T;
 
<langsyntaxhighlight lang="cpp">#include <vector>
#include <tr1/memory>
using namespace std;
Line 265 ⟶ 384:
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>.
 
=={{header|C sharp|C#}}==
 
<lang csharp>using System;
using System.Linq;
using System.Collections.Generic;
 
List<Foo> foos = Enumerable.Range(1, n).Select(x => new Foo()).ToList();</lang>
 
=={{header|Clojure}}==
An example using pseudo-random numbers:
<langsyntaxhighlight lang="clojure">user> (take 3 (repeat (rand))) ; repeating the same random number three times
(0.2787011365537204 0.2787011365537204 0.2787011365537204)
user> (take 3 (repeatedly rand)) ; creating three different random number
(0.8334795669220695 0.08405601245793926 0.5795448744634744)
user></langsyntaxhighlight>
 
=={{header|Common Lisp}}==
The mistake is often written as one of these:
<langsyntaxhighlight lang="lisp">(make-list n :initial-element (make-the-distinct-thing))
(make-array n :initial-element (make-the-distinct-thing))</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="lisp">(loop repeat n collect (make-the-distinct-thing))</langsyntaxhighlight>
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:
 
<langsyntaxhighlight lang="lisp">(map-into (make-list n) #'make-the-distinct-thing)
(map-into (make-array n) #'make-the-distinct-thing)</langsyntaxhighlight>
 
=={{header|D}}==
For reference types (classes):
<langsyntaxhighlight lang="d">auto fooArray = new Foo[n];
foreach (ref item; fooArray)
item = new Foo();
</syntaxhighlight>
</lang>
 
For value types:
<langsyntaxhighlight lang="d">auto barArray = new Bar[n];
barArray[] = initializerValue;</langsyntaxhighlight>
 
=={{header|Delphi}}==
 
Same object accessed multiple times (bad)
<syntaxhighlight lang="delphi">var
<lang Delphi>var
i: Integer;
lObject: TMyObject;
Line 320 ⟶ 431:
for i := 1 to 10 do
lList.Add(lObject);
// ...</langsyntaxhighlight>
 
Distinct objects (good)
<syntaxhighlight lang="delphi">var
<lang Delphi>var
i: Integer;
lList: TObjectList<TMyObject>;
Line 330 ⟶ 441:
for i := 1 to 10 do
lList.Add(TMyObject.Create);
// ...</langsyntaxhighlight>
 
=={{header|E}}==
Line 336 ⟶ 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.
 
<langsyntaxhighlight lang="e">pragma.enable("accumulator")
...
 
accum [] for _ in 1..n { _.with(makeWhatever()) }</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
;; wrong - make-vector is evaluated one time - same vector
 
Line 358 ⟶ 469:
 
L → (#(0 🔵 0 0) #(0 0 0 0) #(0 0 0 0)) ;; OK
</syntaxhighlight>
</lang>
=={{header|Elena}}==
<syntaxhighlight lang="elena">import system'routines;
import extensions;
 
class Foo;
 
// create a list of disting object
fill(n)
= RangeEnumerator.new(1,n).selectBy::(x => new Foo()).toArray();
 
// testing
public program()
{
var foos := fill(10);
}</syntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">randoms = for _ <- 1..10, do: :rand.uniform(1000)</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 368 ⟶ 494:
Randoms = [random:uniform(1000) || _ <- lists:seq(1,10)].
</pre>
 
=={{header|F_Sharp|F#}}==
The wrong way:
<syntaxhighlight lang="fsharp">>List.replicate 3 (System.Guid.NewGuid());;
 
val it : Guid list =
[485632d7-1fd6-4d9e-8910-7949d7b2b485; 485632d7-1fd6-4d9e-8910-7949d7b2b485;
485632d7-1fd6-4d9e-8910-7949d7b2b485]</syntaxhighlight>
 
The right way:
<syntaxhighlight lang="fsharp">> List.init 3 (fun _ -> System.Guid.NewGuid());;
 
val it : Guid list =
[447acb0c-092e-4f85-9c3a-d369e4539dae; 5f41c04d-9bc0-4e96-8165-76b41fe8cd93;
1086400c-72ff-4763-9bb9-27e17bd4c7d2]</syntaxhighlight>
 
=={{header|Factor}}==
clone is the important word here to have distinct objects. This creates an array of arrays.
<langsyntaxhighlight lang="factor">1000 [ { 1 } clone ] replicate</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
The value of n can be determined at runtime, and the array is automatically initialized to zeroes.
<syntaxhighlight lang="freebasic">dim as foo array(1 to n)</syntaxhighlight>
 
=={{header|Forth}}==
Line 379 ⟶ 524:
Needs the FMS-SI (single inheritance) library code located here:
http://soton.mpeforth.com/flag/fms/index.html
<langsyntaxhighlight lang="forth">include FMS-SI.f
include FMS-SILib.f
 
Line 402 ⟶ 547:
list each: drop . 1301600
list each: drop . 1301600
</syntaxhighlight>
</lang>
 
 
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">
program multiple
! Define a simple type
Line 450 ⟶ 594:
 
end program multiple
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
The wrong way:
<lang fsharp>>List.replicate 3 (System.Guid.NewGuid());;
 
val it : Guid list =
[485632d7-1fd6-4d9e-8910-7949d7b2b485; 485632d7-1fd6-4d9e-8910-7949d7b2b485;
485632d7-1fd6-4d9e-8910-7949d7b2b485]</lang>
 
The right way:
<lang fsharp>> List.init 3 (fun _ -> System.Guid.NewGuid());;
 
val it : Guid list =
[447acb0c-092e-4f85-9c3a-d369e4539dae; 5f41c04d-9bc0-4e96-8165-76b41fe8cd93;
1086400c-72ff-4763-9bb9-27e17bd4c7d2]</lang>
=={{header|Go}}==
Useful:
<langsyntaxhighlight lang="go">func nxm(n, m int) [][]int {
d2 := make([][]int, n)
for i := range d2 {
Line 474 ⟶ 604:
}
return d2
}</langsyntaxhighlight>
Probably not what the programmer wanted:
<langsyntaxhighlight lang="go">func nxm(n, m int) [][]int {
d1 := make([]int, m)
d2 := make([][]int, n)
Line 483 ⟶ 613:
}
return d2
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
 
Correct Solution:
<langsyntaxhighlight lang="groovy">def createFoos1 = { n -> (0..<n).collect { new Foo() } }</langsyntaxhighlight>
 
Incorrect Solution:
<langsyntaxhighlight lang="groovy">// Following fails, creates n references to same object
def createFoos2 = {n -> [new Foo()] * n }</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">[createFoos1, createFoos2].each { createFoos ->
print "Objects distinct for n = "
(2..<20).each { n ->
Line 507 ⟶ 637:
}
println()
}</langsyntaxhighlight>
 
Output:
Line 524 ⟶ 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.
<syntaxhighlight lang ="haskell">replicateM n makeTheDistinctThing</langsyntaxhighlight>
in an appropriate do block. If it is distinguished by, say, a numeric label, one could write
<syntaxhighlight lang ="haskell">mapM makeTheDistinctThing [1..n]</langsyntaxhighlight>
 
An incorrect version:
<langsyntaxhighlight lang="haskell">do x <- makeTheDistinctThing
return (replicate n x)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 536 ⟶ 666:
An incorrect approach uses, e.g., the list constructor procedure with an initial value:
 
<syntaxhighlight lang="icon">
<lang Icon>
items_wrong := list (10, [])
# prints '0' for size of each item
Line 544 ⟶ 674:
# now prints '1' for size of each item
every item := !items_wrong do write (*item)
</syntaxhighlight>
</lang>
 
A correct approach initialises each element separately:
 
<syntaxhighlight lang="icon">
<lang Icon>
items := list(10)
every i := 1 to 10 do items[i] := []
</syntaxhighlight>
</lang>
 
=={{header|J}}==
<syntaxhighlight lang J="j">i.</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> i. 4
0 1 2 3</langsyntaxhighlight>
 
J almost always uses pass-by-value, so this topic is not very relevant to J.
Line 568 ⟶ 698:
{{works with|Java|1.5+}}
simple array:
<langsyntaxhighlight lang="java">Foo[] foos = new Foo[n]; // all elements initialized to null
for (int i = 0; i < foos.length; i++)
foos[i] = new Foo();
Line 574 ⟶ 704:
// incorrect version:
Foo[] foos_WRONG = new Foo[n];
Arrays.fill(foos, new Foo()); // new Foo() only evaluated once</langsyntaxhighlight>
 
simple list:
<langsyntaxhighlight lang="java5">List<Foo> foos = new ArrayList<Foo>();
for (int i = 0; i < n; i++)
foos.add(new Foo());
 
// incorrect:
List<Foo> foos_WRONG = Collections.nCopies(n, new Foo()); // new Foo() only evaluated once</langsyntaxhighlight>
 
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>.
<langsyntaxhighlight lang="java5">public static <E> List<E> getNNewObjects(int n, Class<? extends E> c){
List<E> ans = new LinkedList<E>();
try {
Line 603 ⟶ 733:
throws ClassNotFoundException{
return getNNewObjects(n, Class.forName(className));
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 609 ⟶ 739:
===ES5===
 
<langsyntaxhighlight lang="javascript">var a = new Array(n);
for (var i = 0; i < n; i++)
a[i] = new Foo();</langsyntaxhighlight>
 
 
===ES6===
 
<langsyntaxhighlight JavaScriptlang="javascript">(n => {
 
let nObjects = n => Array.from({
Line 629 ⟶ 759:
return nObjects(6);
 
})(6);</langsyntaxhighlight>
 
 
{{Out}}
<langsyntaxhighlight JavaScriptlang="javascript">[{"index":0}, {"index":1}, {"index":2}, {"index":3},
{"index":4}, {"index":5}, {"index":6}]</langsyntaxhighlight>
 
=={{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":<langsyntaxhighlight lang="jq">
def Array(atype; n):
if atype == "number" then [ range(0;n) ]
Line 656 ⟶ 786:
# Example:
 
Array("object"; 4)</langsyntaxhighlight>
 
=={{header|Julia}}==
A potential mistake would be writing:
<syntaxhighlight lang="julia">
foo() = rand() # repeated calls change the result with each call
repeat([foo()], outer=5) # but this only calls foo() once, clones that first value
</syntaxhighlight>
If the effect of calling foo() with every iteration is desired, better to use:
<syntaxhighlight lang="julia">
[foo() for i in 1:5] # Code this to call the function within each iteration
</syntaxhighlight>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.2
 
class Foo {
val id: Int
 
init {
id = ++numCreated // creates a distict id for each object
}
 
companion object {
private var numCreated = 0
}
}
 
fun main(args: Array<String>) {
val n = 3 // say
 
/* correct approach - creates references to distinct objects */
val fooList = List(n) { Foo() }
for (foo in fooList) println(foo.id)
 
/* incorrect approach - creates references to same object */
val f = Foo()
val fooList2 = List(n) { f }
for (foo in fooList2) println(foo.id)
}</syntaxhighlight>
 
{{out}}
<pre>
1
2
3
4
4
4
</pre>
 
=={{header|Latitude}}==
 
We construct an array of the appropriate length and then replace each element with a new object.
 
<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.
 
<syntaxhighlight lang="latitude">;; Will print 10 distinct, arbitrary numbers.
arr visit {
Kernel id printObject.
}.</syntaxhighlight>
 
=={{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:
<langsyntaxhighlight lang="logtalk">
| ?- create_protocol(statep, [], [public(state/1)]),
findall(
Line 669 ⟶ 861:
).
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:
<langsyntaxhighlight lang="logtalk">
| ?- create_object(state, [instantiates(state)], [public(state/1)], [state(0)]),
findall(
Line 680 ⟶ 872:
).
Ids = [o1, o2, o3, o4, o5, o6, o7, o8, o9, o10].
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- This concept is relevant to tables in Lua
local table1 = {1,2,3}
 
Line 699 ⟶ 891:
-- Now we can create a table of independent copies of table1
local copyTab = {}
for i = 1, 10 do copyTab[i] = copy(table1) end</langsyntaxhighlight>
 
=={{header|MathematicaM2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
Form 60, 40
Foo=Lambda Id=1 (m)->{
class Alfa {
x, id
Class:
Module Alfa(.x, .id) {}
}
=Alfa(m, id)
id++
}
Dim A(10)<<Foo(20)
\\ for each arrayitem call Foo(20)
TestThis()
\\ call once foo(20) and result copy to each array item
Dim A(10)=Foo(20)
TestThis()
Bar=Lambda Foo (m)->{
->Foo(m)
}
\\ Not only the same id, but the same group
\\ each item is pointer to group
Dim A(10)=Bar(20)
TestThis()
Sub TestThis()
Local i
For i=0 to 9 {
For A(i){
.x++
Print .id , .x
}
}
Print
End Sub
}
Checkit
</syntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The mistake is often written as:
<langsyntaxhighlight Mathematicalang="mathematica">{x, x, x, x} /. x -> Random[]</langsyntaxhighlight>
 
Here Random[] can be any expression that returns a new value which is incorrect since Random[] is only evaluated once. e.g.
Line 710 ⟶ 947:
A correct version is:
 
<langsyntaxhighlight Mathematicalang="mathematica">{x, x, x, x} /. x :> Random[]</langsyntaxhighlight>
which evaluates Random[] each time e.g.
Line 716 ⟶ 953:
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">a: [1, 2]$
 
b: makelist(copy(a), 3);
Line 724 ⟶ 961:
 
b;
[[1,1000],[1,2],[1,2]]</langsyntaxhighlight>
 
=={{header|Modula-3}}==
{{incorrect|Modula-3|It does not initialize the sequence.}}
Similar to the [[Ada]] version above:
<syntaxhighlight lang ="modula3">VAR a: ARRAY[1..N] OF T</langsyntaxhighlight>
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 open array (an array who's size is not known until runtime) of distinct elements of type T.
 
Modula-3 doesoffers notreference defineand whatpointer valuestypes, so the elementsmistaken way of Ainitializing have,is butquite iteasy doesto guaranteedo thatfor they will be of typethe Tcareless.
 
The example program below demonstrates each of these methods, including the mistaken way, so is a bit long.
<syntaxhighlight lang="modula3">MODULE DistinctObjects EXPORTS Main;
 
IMPORT IO, Random;
 
VAR
 
random := NEW(Random.Default).init();
 
TYPE
 
T = RECORD (* value will initialize to 2 unless otherwise specified *)
value: INTEGER := 2;
END;
 
CONST Size = 3;
 
VAR
 
(* initialize records *)
t1 := T { 3 };
t2 := T { 4 };
t3 : T; (* t3's value will be default (2) *)
 
(* initialize a reference to T with value 100 *)
tr := NEW(REF T, value := 100);
 
(* initialize an array of records *)
a := ARRAY[1..Size] OF T { t1, t2, t3 };
(* initialize an array of integers *)
b := ARRAY[1..Size] OF INTEGER { -9, 2, 6 };
(* initialize an array of references to a record -- NOT copied! *)
c := ARRAY[1..Size] OF REF T { tr, tr, tr };
 
BEGIN
 
(* display the data *)
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" , ");
IO.PutInt(c[i].value); IO.Put(" ; ");
END;
IO.PutChar('\n');
 
(* re-initialize a's data to random integers *)
FOR i := 1 TO Size DO a[i].value := random.integer(-10, 10); END;
(* modify "one" element of c *)
c[1].value := 0;
(* display the data *)
FOR i := 1 TO Size DO
IO.PutInt(a[i].value); IO.Put(" , ");
IO.PutInt(b[i]); IO.Put(" , ");
IO.PutInt(c[i].value); IO.Put(" ; ");
END;
IO.PutChar('\n');
 
END DistinctObjects.</syntaxhighlight>
{{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.
<pre>
3 , -9 , 100 ; 4 , 2 , 100 ; 2 , 6 , 100 ;
-1 , -9 , 0 ; -9 , 2 , 0 ; 8 , 6 , 0 ;
</pre>
 
=={{header|NGS}}==
 
Incorrect, same object n times:
<langsyntaxhighlight NGSlang="ngs">{ [foo()] * n }</langsyntaxhighlight>
 
Correct:
<syntaxhighlight lang NGS="ngs">{ foo * n }</langsyntaxhighlight>
 
=={{header|Nim}}==
In Nim, copy semantic is the rule. So it is very easy to create multiple distinct objects.
The simplest form of initialization works, but is a bit cumbersome to write:
<lang nim>proc foo(): string =
echo "Foo()"
"mystring"
 
We give some examples with sequences of sequences and sequences of references:
let n = 100
var ws = newSeq[string](n)
for i in 0 .. <n: ws[i] = foo()</lang>
If actual values instead of references are stored in the sequence, then objects can be initialized like this. Objects are distinct, but the initializer <code>foo()</code> is called only once, then copies of the resulting object are made:
<lang nim>proc newSeqWith[T](len: int, init: T): seq[T] =
result = newSeq[T] len
for i in 0 .. <len:
result[i] = init
 
<syntaxhighlight lang="nim">import sequtils, strutils
var xs = newSeqWith(n, foo())</lang>
 
To get the initial behaviour, where <code>foo()</code> is called to create each object, a template can be used:
# Creating a sequence containing sequences of integers.
<lang nim>template newSeqWith2(len: int, init: expr): expr =
var result {.gensym.}s1 = newSeq[type(init)seq[int]](len5)
for iitem in 0 .s1.mitems: <len:item = @[1]
echo "s1 = ", s1 # @[@[1], @[1], @[1], @[1], @[1]]
result[i] = init
s1[0].add 2
result
echo "s1 = ", s1 # @[@[1, 2], @[1], @[1], @[1], @[1]]
 
# Using newSeqWith.
var s2 = newSeqWith(5, @[1])
echo "s2 = ", s2 # @[@[1], @[1], @[1], @[1], @[1]]
s2[0].add 2
echo "s2 = ", s2 # @[@[1, 2], @[1], @[1], @[1], @[1]]
 
# Creating a sequence containing pointers.
proc newInt(n: int): ref int =
new(result)
result[] = n
var s3 = newSeqWith(5, newInt(1))
echo "s3 contains references to ", s3.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1
s3[0][] = 2
echo "s3 contains references to ", s3.mapIt(it[]).join(", ") # 2, 1, 1, 1, 1
 
# How to create non distinct elements.
var ys = newSeqWith2(n, foo())</lang>
let p = newInt(1)
var s4 = newSeqWith(5, p)
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 1, 1, 1, 1, 1
s4[0][] = 2
echo "s4 contains references to ", s4.mapIt(it[]).join(", ") # 2, 2, 2, 2, 2</syntaxhighlight>
 
=={{header|OCaml}}==
Line 771 ⟶ 1,082:
 
Incorrect:
<langsyntaxhighlight lang="ocaml">Array.make n (new foo);;
(* here (new foo) can be any expression that returns a new object,
record, array, or string *)</langsyntaxhighlight>
which is incorrect since <code>new foo</code> is only evaluated once. A correct version is:
<langsyntaxhighlight lang="ocaml">Array.init n (fun _ -> new foo);;</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 781 ⟶ 1,092:
The right way : the block sent as parameter is performed n times :
 
<langsyntaxhighlight Oforthlang="oforth">ListBuffer init(10, #[ Float rand ]) println</langsyntaxhighlight>
 
{{out}}
Line 792 ⟶ 1,103:
The "wrong" way : the same value is stored n times into the list buffer
 
<langsyntaxhighlight Oforthlang="oforth">ListBuffer initValue(10, Float rand) println</langsyntaxhighlight>
 
{{out}}
Line 802 ⟶ 1,113:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">-- get an array of directory objects
<lang ooRexx>
-- get an array of directory objects
array = fillArrayWith(3, .directory)
say "each object will have a different identityHash"
say
loop d over array
say d d~identityHash
end
 
Line 821 ⟶ 1,131:
end
 
return array</syntaxhighlight>
{{out}}
</lang>
<pre>each object will have a different identityHash
 
a Directory -140687820712417
a Directory -140687820713425
a Directory -140687820714369</pre>
 
=={{header|Oz}}==
With lists, it is difficult to do wrong.
<langsyntaxhighlight lang="oz">declare
Xs = {MakeList 5} %% a list of 5 unbound variables
in
{ForAll Xs OS.rand} %% fill it with random numbers (CORRECT)
{Show Xs}</langsyntaxhighlight>
 
With arrays on the other hand, it is easy to get wrong:
<langsyntaxhighlight lang="oz">declare
Arr = {Array.new 0 10 {OS.rand}} %% WRONG: contains ten times the same number
in
Line 840 ⟶ 1,154:
for I in {Array.low Arr}..{Array.high Arr} do
Arr.I := {OS.rand}
end</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 847 ⟶ 1,161:
=={{header|Perl}}==
incorrect:
<langsyntaxhighlight lang="perl">(Foo->new) x $n
# here Foo->new can be any expression that returns a reference representing
# a new object</langsyntaxhighlight>
which is incorrect since <code>Foo->new</code> is only evaluated once.
 
A correct version is:
<langsyntaxhighlight lang="perl">map { Foo->new } 1 .. $n;</langsyntaxhighlight>
which evaluates <tt>Foo->new</tt> <var>$n</var> times and collects each result in a list.
 
=={{header|Perl 6Phix}}==
Phix uses shared reference counts with copy-on-write semantics. Creating n references to the same mutable object is in fact the norm,
but does not cause any of the issues implicitly feared in the task description. In fact, apart from dictionaries and classes as noted below, it is not possible to create shared references such that when one is updated they all are, instead store an index to another table that stores the object, rather than the object itself. Also, apart from low-level trickery and interfacing to shared libraries, there are no pointers to normal hll objects. Sequences need not be homogeneous, they can contain any type-mix of elements.
 
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).
Unlike in Perl 5, the list repetition operator evaluates the left argument thunk each time, so
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<lang perl6>my @a = Foo.new xx $n;</lang>
<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: #000000;">s</span><span style="color: #0000FF;">[$]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">5</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">s</span>
produces <code>$n</code> distinct objects.
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'y'</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{"x","x","x","x","x","x"}
{"x","x","x","x","x",5}
{"xy","x","x","x","x",5}
{"xy",{"xy","x","x","x","x",5},"x","x","x",5}
</pre>
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
<!--<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>
<!--</syntaxhighlight>-->
and expect my_func() to be invoked 5 times, but for that you need a loop
<!--<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: #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: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</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>
In the same manner as above if you want five distinct dictionaries or classes, you must invoke new_dict()/new() five times.
 
=={{header|PicoLisp}}==
Create 5 distinct (empty) objects:
<langsyntaxhighlight PicoLisplang="picolisp">: (make (do 5 (link (new))))
-> ($384717187 $384717189 $384717191 $384717193 $384717195)</langsyntaxhighlight>
Create 5 anonymous symbols with the values 1 .. 5:
<langsyntaxhighlight PicoLisplang="picolisp">: (mapcar box (range 1 5))
-> ($384721107 $384721109 $384721111 $384721113 $384721115)
: (val (car @))
-> 1
: (val (cadr @@))
-> 2</langsyntaxhighlight>
 
=={{header|PowerShell}}==
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)))} |
Select-Object -Unique |
ForEach-Object {$_.ToString()}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 890 ⟶ 1,231:
</pre>
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)))} |
Select-Object -Unique |
ForEach-Object {$_.ToString()}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 902 ⟶ 1,243:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">n=Random(50)+25
Dim A.i(n)
; Creates a Array of n [25-75] elements depending on the outcome of Random().
Line 926 ⟶ 1,267:
Next
; Verify by sending each value of A() via *PointersToA()
; to the debugger's output.</langsyntaxhighlight>
 
=={{header|Python}}==
The mistake is often written as:
<langsyntaxhighlight lang="python">[Foo()] * n # here Foo() can be any expression that returns a new object</langsyntaxhighlight>
which is incorrect since <tt>Foo()</tt> is only evaluated once. A common correct version is:
<langsyntaxhighlight lang="python">[Foo() for i in range(n)]</langsyntaxhighlight>
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}}==
The mistake is often written as:
<langsyntaxhighlight lang="r">rep(foo(), n) # foo() is any code returning a value</langsyntaxhighlight>
A common correct version is:
<syntaxhighlight lang ="r">replicate(n, foo())</langsyntaxhighlight>
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}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 952 ⟶ 1,293:
;; a list of 10 distinct vectors
(build-list 10 (λ (n) (make-vector 10 0)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Unlike in Perl 5, the list repetition operator evaluates the left argument thunk each time, so
 
<syntaxhighlight lang="raku" line>my @a = Foo.new xx $n;</syntaxhighlight>
 
produces <code>$n</code> distinct objects.
 
 
=={{header|REXX}}==
This entry is modeled after the '''Erlang''' entry.
<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.*/
if n=='' | n=="," then n= 1000 /*Not specified? Then use the default.*/
if lim=='' | lim=="," then lim= 100000 /* " " " " " " */
lim= min(lim, 1e5) /*limit the random range if necessary. */
randoms= /*will contain random list of integers.*/
$= .
do j=1 for n /*gen a unique random integer for list.*/
 
do until wordpos($, randoms)==0 /*ensure " " " " " */
$= random(0, lim) /*Not unique? Then obtain another int.*/
end /*until*/ /*100K is the maximum range for RANDOM.*/
 
randoms= $ randoms /*add an unique random integer to list.*/
end /*j*/
 
say words(randoms) ' unique numbers generated.' /*stick a fork in it, we're all done. */</syntaxhighlight>
<br><br>
 
=={{header|RPL}}==
{{works with|HP|49}}
To create a list of n references to the same object:
<span style="color:blue">FOO</span> n DUPN →LIST
To create a list of n distinct objects:
« <span style="color:blue">FOO</span> » 'X' 1 n 1 SEQ
The FOO function can access the rank at which the object will be stored by reading the X variable.
 
=={{header|Ruby}}==
The mistake is often written as one of these:
<langsyntaxhighlight lang="ruby">[Foo.new] * n # here Foo.new can be any expression that returns a new object
Array.new(n, Foo.new)</langsyntaxhighlight>
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:
<langsyntaxhighlight lang="ruby">Array.new(n) { Foo.new }</langsyntaxhighlight>
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}}==
<syntaxhighlight lang="rust">use std::rc::Rc;
use std::cell::RefCell;
 
fn main() {
let size = 3;
// Clone the given element to fill out the vector.
let mut v: Vec<String> = vec![String::new(); size];
v[0].push('a');
println!("{:?}", v);
// Run a given closure to create each element.
let mut v: Vec<String> = (0..size).map(|i| i.to_string()).collect();
v[0].push('a');
println!("{:?}", v);
// For multiple mutable views of the same thing, use something like Rc and RefCell.
let v: Vec<Rc<RefCell<String>>> = vec![Rc::new(RefCell::new(String::new())); size];
v[0].borrow_mut().push('a');
println!("{:?}", v);
}</syntaxhighlight>
{{out}}
<pre>["a", "", ""]
["0a", "1", "2"]
[RefCell { value: "a" }, RefCell { value: "a" }, RefCell { value: "a" }]</pre>
 
=={{header|Scala}}==
Line 966 ⟶ 1,373:
if created with the same constructor arguments.
 
<langsyntaxhighlight lang="scala">for (i <- (0 until n)) yield new Foo()</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{libheader|Scheme/SRFIs}}
 
There is a standard function make-list which makes a list of size n, but repeats its given value.
 
<pre>
sash[r7rs]> (define-record-type <a> (make-a x) a? (x get-x))
#<unspecified>
sash[r7rs]> (define l1 (make-list 5 (make-a 3)))
#<unspecified>
sash[r7rs]> (eq? (list-ref l1 0) (list-ref l1 1))
#t
</pre>
 
In SRFI 1, a function list-tabulate is provided which instead calls a function to create a fresh value each time.
 
<pre>
sash[r7rs]> (define l2 (list-tabulate 5 (lambda (i) (make-a i))))
#<unspecified>
sash[r7rs]> (eq? (list-ref l2 0) (list-ref l2 1))
#f
sash[r7rs]> (map get-x l2)
(0 1 2 3 4)
</pre>
 
=={{header|Seed7}}==
Line 972 ⟶ 1,404:
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.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const func array file: openFiles (in array string: fileNames) is func
Line 991 ⟶ 1,423:
begin
files := openFiles([] ("abc.txt", "def.txt", "ghi.txt", "jkl.txt"));
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">[Foo.new] * n; # incorrect (only one distinct object is created)</langsyntaxhighlight>
<langsyntaxhighlight lang="ruby">n.of {Foo.new}; # correct</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
 
<langsyntaxhighlight lang="smalltalk">|c|
"Create an ordered collection that will grow while we add elements"
c := OrderedCollection new.
Line 1,011 ⟶ 1,443:
1 to: 9 do: [ :i | (c at: i) at: 4 put: i ].
"show it"
c do: [ :e | e printNl ].</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">class Foo { }
 
var foos = [Foo]()
Line 1,022 ⟶ 1,454:
 
// incorrect version:
var foos_WRONG = [Foo](count: n, repeatedValue: Foo()) // Foo() only evaluated once</langsyntaxhighlight>
 
=={{header|Tcl}}==
Line 1,028 ⟶ 1,460:
 
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight Tcllang="tcl">package require TclOO
 
# The class that we want to make unique instances of
Line 1,040 ⟶ 1,472:
for {set i 0} {$i<$n} {incr i} {
lappend theList [$theClass new]
}</langsyntaxhighlight>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">class Foo {
static init() { __count = 0 } // set object counter to zero
 
construct new() {
__count = __count + 1 // increment object counter
_number = __count // allocates a unique number to each object created
}
 
number { _number }
}
 
Foo.init() // set object counter to zero
var n = 10 // say
// Create a List of 'n' distinct Foo objects
var foos = List.filled(n, null)
for (i in 0...foos.count) foos[i] = Foo.new()
// Show they're distinct by printing out their object numbers
foos.each { |f| System.write("%(f.number) ") }
System.print("\n")
 
// Now create a second List where each of the 'n' elements is the same Foo object
var foos2 = List.filled(n, Foo.new())
// Show they're the same by printing out their object numbers
foos2.each { |f| System.write("%(f.number) ") }
System.print()</syntaxhighlight>
 
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10
 
11 11 11 11 11 11 11 11 11 11
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code Reserve=3, IntIn=10;
char A; int N, I;
[N:= IntIn(8); \get number of items from command line
Line 1,049 ⟶ 1,515:
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"
]</langsyntaxhighlight>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">sub test()
print "Random number: " + str$(ran(100))
end sub
 
sub repL$(e$, n)
local i, r$
for i = 1 to n
r$ = r$ + "," + e$
next
return r$
end sub
 
dim func$(1)
 
n = token(repL$("test", 5), func$(), ",")
 
for i = 1 to n
execute(func$(i))
next i</syntaxhighlight>
 
 
=={{header|Z80 Assembly}}==
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.
 
<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 b,a ;use this as a loop counter.
xor a ;set A to zero
 
loop: ;creates a list of ascending values starting at zero. Each is stored at a different memory location
ld (hl),a ;store A in ram
inc a ;ensures each value is different.
inc hl ;next element of list
djnz loop</syntaxhighlight>
 
=={{header|zkl}}==
The pump and partial application methods are useful tools for creating initialized lists.
<langsyntaxhighlight lang="zkl">n:=3;
n.pump(List) //-->L(0,1,2)
 
Line 1,070 ⟶ 1,573:
class C{ var n; fcn init(x){n=x} }
n.pump(List,C) //--> L(C,C,C)
n.pump(List,C).apply("n") //-->L(0,1,2) ie all classes distinct</langsyntaxhighlight>
 
 
Anonymous user