Multiple distinct objects: Difference between revisions

added ocaml
(→‎{{header|Java}}: More explanaiton)
(added ocaml)
Line 106:
=={{header|Haskell}}==
 
Below, we are assuming that <tt>makeTheDistinctThing</tt> is a monadic expression (i.e. it has type <tt>m a</tt> where <tt>m</tt> is some monad, like <tt>IO</tt> or <tt>ST</tt>), 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.
If the creator of the distinct thing is in some monad, then one can write
<code haskell>
replicateM n makeTheDistinctThing
Line 112:
in an appropriate do block. If it is distinguished by, say, a numeric label, one could write
<code haskell>
mapmapM makeTheDistinctThing [1..n]
</code>
 
An incorrect version:
<code haskell>
do x <- makeTheDistinctThing
return (replicate n x)
</code>
 
=={{header|Java}}==
{{works with|Java|1.5+}}
Line 158 ⟶ 165:
return getNNewObjects(n, Class.forName(className));
}
</code>
 
=={{header|OCaml}}==
For arrays:
 
Incorrect:
<code ocaml>
Array.make n (new foo);; (* here (new foo) can be any expression that returns a new object or record *)
</code>
which is incorrect since <tt>new foo</tt> is only evaluated once. A correct version is:
<code ocaml>
Array.init n (fun _ -> new foo);;
</code>
 
Anonymous user