Executable library: Difference between revisions

Added Wren
(Lua)
(Added Wren)
Line 2,092:
 
puts "most common length is $mostCommonLength, with frequency $freq"</lang>
 
=={{header|Wren}}==
 
In Wren there is no essential difference between the ''main module'' (the module at which the script starts executing) and any ''library module'' which it imports. The latter can also contain executable code and, if it does, it will execute when the library module is imported.
 
To treat a library module as ''dual purpose'' we therefore need a way to stop its executable code from running when it is being used as a pure library but to let it run otherwise.
 
The strategy here is check whether the main module is the same as the library module and to treat is as executable if it is but as a library otherwise.
 
<lang ecmascript>/* hailstone.wren */
 
var Hailstone = Fn.new { |n|
if (n < 1) Fiber.abort("Parameter must be a positive integer.")
var h = [n]
while (n != 1) {
n = (n%2 == 0) ? (n/2).floor : 3*n + 1
h.add(n)
}
return h
}
 
var libMain_ = Fn.new {
var h = Hailstone.call(27)
System.print("For the Hailstone sequence starting with n = 27:")
System.print(" Number of elements = %(h.count)")
System.print(" First four elements = %(h[0..3])")
System.print(" Final four elements = %(h[-4..-1])")
 
System.print("\nThe Hailstone sequence for n < 100,000 with the longest length is:")
var longest = 0
var longlen = 0
for (n in 1..99999) {
var h = Hailstone.call(n)
var c = h.count
if (c > longlen) {
longest = n
longlen = c
}
}
System.print(" Longest = %(longest)")
System.print(" Length = %(longlen)")
}
 
// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "hailstone.wren") { // if true, not a library
libMain_.call()
}</lang>
 
{{out}}
If we run this directly, we get the expected output:
<pre>
$ wren hailstone.wren
 
For the Hailstone sequence starting with n = 27:
Number of elements = 112
First four elements = [27, 82, 41, 124]
Final four elements = [8, 4, 2, 1]
 
The Hailstone sequence for n < 100,000 with the longest length is:
Longest = 77031
Length = 351
</pre>
 
If we now create a second module which imports the above and calls its Hailstone function:
<lang ecmascript>/* hailstone2.wren */
 
import "/hailstone" for Hailstone
 
var freq = {}
for (i in 1...100000) {
var len = Hailstone.call(i).count
var f = freq[len]
freq[len] = f ? f + 1 : 1
}
var mk = 0
var mv = 0
for (k in freq.keys) {
var v = freq[k]
if (v > mv) {
mk = k
mv = v
}
}
System.print("The Hailstone length returned most is %(mk), which occurs %(mv) times.")</lang>
 
{{out}}
We can now run this to check that the executable code in hailstone.wren has been suppressed, giving us:
<pre>
$ wren hailstone2.wren
 
The Hailstone length returned most is 72, which occurs 1467 times.
</pre>
 
=={{header|zkl}}==
9,490

edits