Multiple distinct objects: Difference between revisions

m
Formatting fix, added headers
(new task (inspired by the *name* of "Create a Sequence of unique elements"))
 
m (Formatting fix, added headers)
Line 8:
This task mostly makes sense for languages operating in the pass-references-by-value style (most object-oriented or 'dynamic' languages).
 
=={{header|C}}==
 
<code c>foo *foos = malloc(n * sizeof(*foos));
for (int i = 0; i < n; i++)
init_foo(&foos[i]);</code>
 
(Or if no particular initialization is needed, skip that part, or use <codett>calloc</codett>.)
 
==Common Lisp==
 
=={{header|Common Lisp}}==
The mistake is often written as one of these:
<code lisp>(make-list n :initial-element (make-the-distinct-thing))
(make-array n :initial-element (make-the-distinct-thing))</code>
which are incorrect since <code>(make-the-distinct-thing)</code> is only evaluated once. A common correct version is:
<code lisp>(loop repeat n collect (make-the-distinct-thing))</code>
which evaluates <codett>(make-the-distinct-thing)</codett> <var>n</var> times and collects each result in a list.
 
=={{header|Haskell}}==
 
If the creator of the distinct thing is in some monad, then one can write
<code haskell>replicateM n makeTheDistinctThing</code>
in an appropriate do block. If it is distinguished by, say, a numeric label, one could write
<code haskell>map makeTheDistinctThing [1..n]</code>
Anonymous user