You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In this code snippet, the scope of the iteration variable i is global, and the anonymous function captures the variable by reference instead of by value during each iteration, which is consistent with Python but different from functional languages such as OCaml and Scala. To some extent, this behavior goes against intuition.
[<function <lambda> at 0x102d69b20>, <function <lambda> at 0x102d69bc0>, <function <lambda> at 0x102d69ee0>, <function <lambda> at 0x102d69f80>, <function <lambda> at 0x102d6a020>]
<function <lambda> at 0x102d69b20>
4
<function <lambda> at 0x102d69bc0>
4
<function <lambda> at 0x102d69ee0>
4
<function <lambda> at 0x102d69f80>
4
<function <lambda> at 0x102d6a020>
4
i = 4
Scala 3
importscala.collection.mutable.ArrayBuffervarfunctions=ArrayBuffer[()=>Int]()
for i <-1 to 10do
functions.append(()=>i)
println(functions)
println(functions(0)())
println(functions(1)())
println(functions(2)())
<function <lambda> at 0x000001E1B8A3C720> 0
<function <lambda> at 0x000001E1B8B68540> 1
<function <lambda> at 0x000001E1B8B68680> 2
<function <lambda> at 0x000001E1B8B8B060> 3
<function <lambda> at 0x000001E1B8B8B100> 4
De-optimized, pure procedure for! is defined here.
This is what we wanted, but de-optimized version is much slower.
# iteration with 0..<1000000
❯ hyperfine "cargo r test.er"# optimized (normal) versionBenchmark 1: cargo r test.er Time (mean ± σ): 1.981 s ± 0.016 s [User: 1.493 s, System: 0.158 s] Range (min … max): 1.964 s … 2.014 s 10 runs
❯ hyperfine "cargo r test.er"# de-optimized versionBenchmark 1: cargo r test.er Time (mean ± σ): 3.168 s ± 0.120 s [User: 2.562 s, System: 0.255 s] Range (min … max): 3.088 s … 3.475 s 10 runs
I will try to see if we can get the desired behavior without performance penalty.
In this code snippet, the scope of the iteration variable i is global, and the anonymous function captures the variable by reference instead of by value during each iteration, which is consistent with Python but different from functional languages such as OCaml and Scala. To some extent, this behavior goes against intuition.
Output:
Scala 3
Output of Scala
The text was updated successfully, but these errors were encountered: