Anonymous user
Multiple distinct objects: Difference between revisions
Replaced existing text which contained errors by an example.
Alextretyak (talk | contribs) (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.
We give some examples with sequences of sequences and sequences of references:
let n = 100▼
var ws = newSeq[string](n)▼
result = newSeq[T] len▼
<lang Nim>import sequtils, strutils
var xs = newSeqWith(n, foo())</lang>▼
result▼
# Creating a sequence containing sequences of integers.
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.
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)
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 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}}==
|