Executable library: Difference between revisions
m
→{{header|Wren}}: Minor tidy
(added Pascal example) |
m (→{{header|Wren}}: Minor tidy) |
||
(5 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
9!:29]1
9!:27'main 0'
Line 1,376 ⟶ 1,377:
I: Longint;
begin
if (aValue <> 0) and (aValue <= 200000) then begin
Buffer[0] := aValue;
if Odd(aValue) then▼
Inc(I);
Hailstone.Data := @Buffer;▼
Hailstone.Count := I;
▲ Hailstone.Data := @Buffer;
end;
end;
Line 1,402 ⟶ 1,407:
Hailstone;
var
I, Value: Cardinal;
MaxLen: Longint;
begin
WriteLn('Length of Hailstone(27) is ',
PrintArray('it starts with ',
PrintArray('and ends with ',
Value := 0;
MaxLen := 0;
for I := 1 to 100000 do begin
if
MaxLen :=
Value := I;
end;
end;
WriteLn('Maximum length ', MaxLen, ' was found for Hailstone(', Value, ')');
end.
Line 1,481 ⟶ 1,486:
end.
</syntaxhighlight>
Both executables must be placed in the same folder.
{{out}}
<pre>
The most common Hailstone sequence length in the specified range is 72, it occurs 1467 times.
</pre>
Line 2,132 ⟶ 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.
var n = 0
var max = 0
Line 2,151 ⟶ 2,157:
}
}
say "Longest sequence is for #{n}: #{max}"
}</syntaxhighlight>
Line 2,230 ⟶ 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="
var Hailstone = Fn.new { |n|
Line 2,266 ⟶ 2,272:
// Check if it's being used as a library or not.
import "os" for Process
if (Process.allArguments[1] == "
libMain_.call()
}</syntaxhighlight>
Line 2,273 ⟶ 2,279:
If we run this directly, we get the expected output:
<pre>
$ wren
For the Hailstone sequence starting with n = 27:
Line 2,286 ⟶ 2,292:
If we now create a second module which imports the above and calls its Hailstone function:
<syntaxhighlight lang="
import "./
var freq = {}
Line 2,310 ⟶ 2,316:
We can now run this to check that the executable code in hailstone.wren has been suppressed, giving us:
<pre>
$ wren
The Hailstone length returned most is 72, which occurs 1467 times.
|