Jump to content

Executable library: Difference between revisions

m
m (→‎{{header|Pascal}}: more correct code in the library)
m (→‎{{header|Wren}}: Minor tidy)
 
(3 intermediate revisions by 3 users not shown)
Line 756:
This is the executable library:
 
<syntaxhighlight lang="j">hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0#!/usr/bin/ijconsole
hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0
9!:29]1
9!:27'main 0'
Line 1,378 ⟶ 1,379:
Hailstone.Count := 0;
Hailstone.Data := nil;
if (aValue <> 0) and (aValue <= 200000) then begin
Buffer[0] := aValue;
I := 1;
Line 2,137 ⟶ 2,138:
while (n > 1) {
take(n)
n = (n.is_even ? (n/2) : (take(3*n + 1)/2))
}
take(1)
}
}
 
 
if (__FILE__ == __MAIN__) { # true when not imported
var seq = hailstone(27)
say "hailstone(27) - #{seq.len} elements: #{seq.ftfirst(0, 34)} [...] #{seq.ftlast(-4)}"
 
 
var n = 0
var max = 0
Line 2,156 ⟶ 2,157:
}
}
 
 
say "Longest sequence is for #{n}: #{max}"
}</syntaxhighlight>
Line 2,235 ⟶ 2,236:
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.
 
<syntaxhighlight lang="ecmascriptwren">/* hailstoneExecutable_library.wren */
 
var Hailstone = Fn.new { |n|
Line 2,271 ⟶ 2,272:
// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "hailstoneExecutable_library.wren") { // if true, not a library
libMain_.call()
}</syntaxhighlight>
Line 2,278 ⟶ 2,279:
If we run this directly, we get the expected output:
<pre>
$ wren hailstoneExecutable_library.wren
 
For the Hailstone sequence starting with n = 27:
Line 2,291 ⟶ 2,292:
 
If we now create a second module which imports the above and calls its Hailstone function:
<syntaxhighlight lang="ecmascriptwren">/* hailstone2Executable_library_2.wren */
 
import "./hailstoneExecutable_library" for Hailstone
 
var freq = {}
Line 2,315 ⟶ 2,316:
We can now run this to check that the executable code in hailstone.wren has been suppressed, giving us:
<pre>
$ wren hailstone2Executable_library_2.wren
 
The Hailstone length returned most is 72, which occurs 1467 times.
9,485

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.