Multiple distinct objects: Difference between revisions

Add Nimrod
(Add Nimrod)
Line 551:
 
Modula-3 does not define what values the elements of A have, but it does guarantee that they will be of type T.
 
=={{header|Nimrod}}==
The simplest form of initialization works, but is a bit cumbersome to write:
<lang nimrod>proc foo(): string =
echo "Foo()"
"mystring"
 
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 nimrod>proc newSeqWith[T](len: int, init: T): seq[T] =
result = newSeq[T] len
for i in 0 .. <len:
result[i] = init
 
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:
<lang nimrod>template newSeqWith2(len: int, init: expr): expr =
var result {.gensym.} = newSeq[type(init)](len)
for i in 0 .. <len:
result[i] = init
result
 
var ys = newSeqWith2(n, foo())</lang>
 
=={{header|OCaml}}==
Anonymous user