Multiple distinct objects: Difference between revisions

(Add Logtalk implementation)
(→‎{{header|Groovy}}: new solution)
Line 369:
return d2
}</lang>
 
=={{header|Groovy}}==
 
Correct Solution:
<lang groovy>def createFoos1 = { n -> (0..<n).collect { new Foo() } }</lang>
 
Incorrect Solution:
<lang groovy>// Following fails, creates n references to same object
def createFoos2 = {n -> [new Foo() ]* n }</lang>
 
Test:
<lang groovy>[createFoos1, createFoos2].each { createFoos ->
print "Objects distinct for n = "
(2..<20).each { n ->
def foos = createFoos(n)
foos.eachWithIndex { here, i ->
foos.eachWithIndex { there, j ->
assert (here == there) == (i == j)
}
}
print "${n} "
}
println()
}</lang>
 
Output:
<pre>Objects distinct for n = 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Objects distinct for n = Caught: Assertion failed:
 
assert (here == there) == (i == j)
| | | | | | |
| | | | 0 | 1
| | | false false
| | Foo@19c8ef56
| true
Foo@19c8ef56</pre>
 
=={{header|Haskell}}==
Anonymous user