Multiple distinct objects: Difference between revisions

Replaced existing text which contained errors by an example.
(Added 11l)
(Replaced existing text which contained errors by an example.)
Line 962:
 
=={{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
 
<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:
<lang nim>template newSeqWith2(len: int, init: expr): expr =
var result {.gensym.} = newSeq[type(init)](len)
for i in 0 .. <len:
result[i] = init
result
 
# Creating a sequence containing sequences of integers.
var ys = newSeqWith2(n, foo())</lang>
var wss1 = newSeq[stringseq[int]](n5)
for item in s1.mitems: item = @[1]
echo "s1 = ", s1 # @[@[1], @[1], @[1], @[1], @[1]]
s1[0].add 2
echo "s1 = ", s1 # @[@[1, 2], @[1], @[1], @[1], @[1]]
 
# Using newSeqWith.
var xss2 = newSeqWith(n5, foo()@[1])</lang>
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[] = newSeq[T] lenn
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.
let np = 100newInt(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</lang>
 
=={{header|OCaml}}==
Anonymous user