Introspection: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 12:
=={{header|Ada}}==
Ada doesn't allow you to ask about compiler versions, but you can query specific parameters of the target, such as the range of the standard integer type, or the precision of the standard floating point type:
<
procedure Introspection is
use Ada.Integer_Text_IO, Ada.Text_IO;
Line 25:
Put (Float'Digits);
New_Line;
end Introspection;</
All Ada compilers recognize obsolete parts of a programs and either automatically recompile them or fail to link the program.
=={{header|Aikido}}==
The version of the Aikido interpreter is in the global scope variable <em>version</em>. AIkido doesn't have <code>abs</code> but it does have <code>fabs</code>. Getting the variables in main involves getting their names and then evaluating them as an expression in order to retrieve their type.
<
import math
Line 83:
</syntaxhighlight>
Here is the result:
fabs(bloop) is 1.4
Line 101:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<
print (("Integer range: ", -max int, " .. ", max int, new line));
print (("Integer digits: ", int width, new line));
print (("Float range: ", -max real, " .. ", max real, new line));
print (("Float digits: ", real width, new line))
END</
{{out}}
<pre>
Line 121:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - MODEs BYTE, SEMA, FORMAT etc are not available in ELLA Algol68RS}}
<
MODE SSMODES = UNION(SHORT SHORT BITS, SHORT SHORT BYTES, #SHORT SHORT CHAR,#
SHORT SHORT INT, SHORT SHORT REAL, SHORT SHORT COMPL);
Line 170:
sep := ", "
OD
END</
{{out}}
<pre>
Line 184:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.3.3 algol68g-2.3.3].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
'''File: Typeof_operator.a68'''<
OP TYPEOF = (INT skip)STRING: "INT";
Line 191:
OP TYPEOF = (COMPL skip)STRING: "COMPL";
printf(($g" "$,TYPEOF 1, TYPEOF "x", TYPEOF pi, TYPEOF (0 I 1 ), $l$))</
{{out}}
<pre>
Line 203:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards)}}
'''File: Introspection_array_bounds.a68'''<
[]INT x = (5,4,3,2,1);
print(("x =", x, new line));
print(("LWB x =", LWB x, ", UPB x = ",UPB x, new line))</
{{out}}
<pre>
Line 217:
=={{header|Arturo}}==
<
bloop: 3 - 5
Line 230:
sum map select keys symbols 'sym -> integer? var sym
'sym -> var sym
]</
{{out}}
Line 238:
=={{header|AutoHotkey}}==
<
{
MsgBox % "you are using" . A_AhkVersion . "`nplease upgrade to" . "1.0.48.03"
Line 247:
if IsFunc("abs")
MsgBox % abs(bloop)
return</
=={{header|AWK}}==
{{works with|gawk|4.1.0}} PROCINFO is a gawk-extension
<syntaxhighlight lang="awk">
# syntax: GAWK -f INTROSPECTION.AWK
BEGIN {
Line 266:
}
function abs(x) { if (x >= 0) { return x } else { return -x } }
</syntaxhighlight>
{{out}}
<pre>
Line 275:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
ON ERROR LOCAL PRINT "Variable 'bloop' doesn't exist" : END
Line 297:
INPUT #F%,V$
CLOSE #F%
= RIGHT$(V$,5)</
=={{header|C}}==
Line 305:
{{works with|C|94 and later}}
<
#pragma error("C compiler must adhere to at least C99 for the following code.")
#else
/* rest of file */
#endif</
However, there is no facility in C for checking whether individual variables
Line 319:
=={{header|C sharp|C#}}==
There has to be some caveats made with C#. There are no truly "global" variables - just publicly exported ones from individual classes/types. I chose to make a couple of public static variables in my program's class. Also, the "version" of the compiler is difficult to impossible to get at. There are no predefined compiler constants that can be compared against as in C/C++ but then again, it's hardly the thing that counts in C#. What really counts is the version of .NET and the framework you're working with since that determines what C++ features you can use and the various calls that can be made. Consequently, I check the .NET version to make sure it's past 4.0 and exit if not.
<
using System.Reflection;
Line 400:
}
}
</syntaxhighlight>
{{out}}
Line 409:
Identifying the version of the C++ standard used by the compiler in C++ is syntactically very similar to the way of checking the C standard version (also seen on this page).
<
#pragma error("The following code requires at least C++11.")
#else
// ...
#endif</
As in C, the introspective capabilities of C++ are very limited.
Line 419:
=={{header|Clojure}}==
Partial answer...
<
; check Java version
(let [version (Double/parseDouble (re-find #"\d*\.\d*" (System/getProperty "java.version")))]
Line 431:
(println "Version ok")
(throw (Error. "Bad version"))))
</syntaxhighlight>
=={{header|Common Lisp}}==
<
(major (parse-integer ver :start 0 :end (position #\. ver))))
#+lispworks (assert (>= 5 major) () "Requires Lispworks version 5 or above")
#+clisp (assert (>= 2 major) () "Requires CLISP 2.n")
)</
<
(if (and (fboundp 'abs)
(boundp 'bloop))
(format t "~d~%" (abs bloop)))</
The ''list-all-packages'' and ''do-symbols'' forms enable a lisp program to examine all symbols and these can be tested to identify integer variables.
<
(ints '()))
(loop for pkg in (list-all-packages)
Line 453:
(incf sum (symbol-value s)))))
(format t "there are ~d integer variables adding up to ~d~%"
(length ints) sum))</
=={{header|D}}==
With extra credit.
<
immutable x = 3, y = 100, z = 3_000;
short w = 1; // Not an int, must be ignored.
Line 488:
tot += mixin("." ~ name);
writeln("Total of the module-level ints (could overflow): ", tot);
}</
{{out}}
<pre>The expression is compilable.
Line 495:
=={{header|E}}==
Version:
<
(There is no built-in version comparison, and the author of this example assumes that implementing a version comparison algorithm isn't the point of this task.)
Existence:
<
def &x := meta.getState().fetch("&bloop", fn { fail("no bloop") })
if (!x.__respondsTo("abs", 0)) { fail("no abs") }
x.abs()
}</
This will return either bloop.abs(), "no bloop", or "no abs".
Sum of integers:
<syntaxhighlight lang="e">{
var sum := 0
for &x in interp.getTopScope() { sum += try { x :int } catch _ { 0 } }
sum
}</
<code>try</code> rather than an ordinary type check is used because in general a slot might be broken; this way we skip over all read failures as well as non-integers. The block around the code ensures that the sum variable itself will not be involved in the computation.
=={{header|EchoLisp}}==
<
(version)
→ EchoLisp - 2.50.3
Line 546:
</syntaxhighlight>
=={{header|Erlang}}==
Erlang does not have global variables so I look for a function bloop/0 that returns an integer.
Moreover, I sum the available modules, instead of the unavailable global integers.
<syntaxhighlight lang="erlang">
-module( introspection ).
Line 572:
exit_if_too_old( Release ) when Release < "R13A" -> erlang:exit( too_old_release );
exit_if_too_old( _Release ) -> ok.
</syntaxhighlight>
{{out}}
<pre>
Line 582:
=={{header|Factor}}==
Check for build number and execute a quotation if it's too old. (There are no such things as versions for Factor yet.)
<
[ build > ] 2dip if ; inline
Line 590:
[ [ ] ] dip if-older ; inline
900 [ "Your version of Factor is too old." print 1 exit ] when-older</
It is possible to test if a function or a variable exists (<code>search</code>), but that shouldn't be used outside of parsing.
<
get [
"abs" search [ execute( n -- n' ) ] when*
] [ 0 ] if*
] [ 0 ] if*</
On the other hand, it is possible to search the global namespace for integer variables:
<
0 0
Line 606:
nip dup integer? [ + [ 1 + ] dip ] [ drop ] if
] assoc-each
"There are %d integer variables, the sum is %d\n" printf</
=={{header|Forth}}==
Standard Forth doesn't necessarily provide for version numbers, but you can query information about the environment at interpretation time:
<
0xffffffff <> [IF] .( Requires 32 bits! ) bye [THEN]
[THEN]
Line 618:
[defined] abs [if]
bloop @ abs
[then] [then]</
[[4tH]] is able to fulfill all requirements. Note that since only one variable has been declared, the sum of all integer (user)variables is consequently the value of that variable.
{{Works with|4tH|3.62.2}}
<
-32 value bloop
Line 631:
0 last cell+ first over over - .( User variables: ) .
?do i @ + loop .( Sum: ) . cr</
{{out}}
<pre>
Line 640:
=={{header|FreeBASIC}}==
Version 1:
<
#If __FB_VERSION__ < "1.06.0"
Line 656:
Print "bloop does not exist"
#EndIf
Sleep</
{{out}}
<pre>introspection.bas(4) error: Compiler version is too old - needs to be 1.06.0 or later</pre>
Version 2:
<
#If __FB_VERSION__ < "1.05.0" '' version 1.05.0 is now OK
Line 676:
Print "bloop does not exist"
#EndIf
Sleep</
{{out}}
<pre>Abs(bloop) = 15</pre>
Version 3 (version code omitted for brevity):
<
Dim bloop As Integer = -15
#IfDef bloop
Line 691:
Print "bloop does not exist"
#EndIf
Sleep</
{{out}}
<pre>Abs is not available</pre>
Version 4 (version code omitted for brevity):
<
'Dim bloop As Integer = -15 '' bloop declaration commented out
#IfDef bloop
Line 706:
Print "bloop does not exist"
#EndIf
Sleep</
{{out}}
<pre>bloop does not exist</pre>
=={{header|GAP}}==
<
CheckEval := function(fun, val)
local f, x;
Line 740:
od;
return s;
end;</
=={{header|Go}}==
Task variance: "exit if it is too old" is not done here. Go version strings do not present an easily interpreted chronology. This version of the program simply prints the version string.
<
import (
Line 802:
fmt.Println(" abs(bloop): ", math.Abs(bloop))
}
}</
{{out}}
<pre>
Line 817:
=={{header|Haskell}}==
<
import Control.Monad
import System.Info
Line 824:
main = when (compilerName == "ghc" && compilerVersion < minGHCVersion) $
fail "Compiler too old."</
No means exists of checking whether a variable exists at runtime. The set of variables that exist in any given scope is fixed at compile-time.
Line 830:
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main(A)
Line 847:
return (major < maj) | ((major = maj) & (minor < min))
}
end</
Sample run:
<pre>->introspect
Line 856:
=={{header|Inform 7}}==
Inform 7 doesn't have built-in functionality for checking the runtime version number, but the version number is available and can be read by including a snippet of Inform 6 code. The address and format of the version number vary according to the virtual machine being targeted.
<
When play begins:
Line 880:
To decide which version is current runtime version: (- ($32-->0) -).
To decide which version is required runtime version: decide on 1.1.</
It's not possible to check for the existence of functions (invoking a nonexistent phrase causes a compile-time error) or list global variables.
=={{header|Io}}==
<
if(hasSlot("bloop") and bloop hasSlot("abs"), bloop abs)</
Io can also inspect the source code of methods written in Io:
<
=={{header|IS-BASIC}}==
<
110 WHEN EXCEPTION USE ERROR
120 PRINT ABS(BLOOP)
Line 900:
150 PRINT EXSTRING$(EXTYPE)
160 CONTINUE
170 END HANDLER</
=={{header|J}}==
Exit if we're running an old version of J (earlier than version 6, which is current as of this writing), giving version number as the exit status:
<
Compute <tt>abs(bloop)</tt> if <tt>abs</tt> is a function and <tt>bloop</tt> is data:
<
'''Extra credit''': report the number of integer variables in global scope, and their sum:
<
This last expression is longer than the others, because it has a couple of extra guard checks; in J, the programmer doesn't need to care if the data is a single number or an array, or what hardware representation is used for numbers (32-bit int, IEEE float, etc).
Line 916:
=={{header|Java}}==
You can't see if a variable or function is available in Java (it will be a compile time error if you try to use them when you they aren't available), but you can check the version number using the <tt>System</tt> class:
<
public static void main(String[] args) {
String vers = System.getProperty("java.version");
Line 927:
}
}
}</
=={{header|JavaScript}}==
Line 935:
Testing whether the variable “bloop” exists:
<
The <code>typeof</code> operator explicitly does not throw an error when given an undeclared variable.
Line 941:
Test whether <code>Math.abs()</code> is available:
<
<code>abs</code> is a method of the Math object, methods are properties, and the <code>in</code> operator tests whether an object has the named property.
Line 964:
=={{header|Jsish}}==
<
if (Info.version() < Util.verConvert('2.8.6')) {
puts("need at least version 2.8.6 of jsish for this application");
Line 983:
}
}
printf("%d numerics with sum of: %d\n", nums, sums);</
{{out}}
Line 990:
=={{header|Julia}}==
<
VERSION < v"0.4" && exit(1)
Line 1,000:
vars = filter(x -> eval(x) isa Integer, names(Main))
println("Integer variables: ", join(vars, ", "), ".")
println("Sum of integers in the global scope: ", sum(eval.(vars)), ".")</
{{out}}
Line 1,009:
=={{header|Kotlin}}==
We will use Java reflection for this task as Kotlin's own reflection facilities do not appear to be able to deal generically with top-level entities at the present time (i.e. ::class isn't yet supported):
<
import java.lang.reflect.Method
Line 1,048:
}
println("\nThere are $count global integer variables and their sum is $sum")
}</
{{out}}
Line 1,060:
=={{header|Lasso}}==
<
decimal(lasso_version(-lassoversion)) < 9.2 ? abort
var_defined('bloob') and $bloob -> isa(::integer) and lasso_tagexists('math_abs') ? math_abs($bloob)</
-> 26
Lassos equivalence of global variables are thread variables. They have scope that lasts for the entire call in contrast to local variables that are confined to the page or method they are created within.
<
bloob = -26,
positive = 450
Line 1,083:
}
#total</
-> 424
=={{header|Lingo}}==
*verify the version/revision of your currently running (compiler/interpreter/byte-compiler/runtime environment/whatever your language uses) and exit if it is too old.
<
-- "11.5.9"
_player.itemDelimiter="."
if integer(_player.productVersion.item[1])<11 then _player.quit()</
*check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).
<
bloopExists = not voidP(value("bloop"))
-- or for global scope:
-- bloopExists = not voidP(_global.bloop)
absExists = value("abs(1)")=1
if bloopExists and absExists then put abs(bloop) -- or abs(_global.bloop)</
*Report the number of integer variables in global scope, and their sum.
<
sum = 0
repeat with v in the globals
Line 1,112:
end repeat
put cnt
put sum</
=={{header|Locomotive Basic}}==
Line 1,118:
To get the BASIC ROM version number, we need to use a Z80 machine code routine which copies the version number (major/minor/patchlevel) to RAM where BASIC can then read it. Here is the assembly:
<
push bc
Line 1,141:
pop de
pop bc
ret</
The following BASIC program POKEs that routine into memory and quits prematurely if BASIC 1.0 is detected (meaning the machine is a CPC464), as opposed to the more standard 1.1 or later:
<
20 FOR i=0 to 34:READ a:POKE s+i,a:NEXT
30 DATA &c5,&d5,&e5,&f5,&01,&00,&df,&ed,&49,&01,&86,&7f,&ed,&49
Line 1,153:
70 PRINT "BASIC ROM version is ";PEEK(&4040);".";PEEK(&4041);".";PEEK(&4042)
80 IF PEEK(&4041)=0 THEN PRINT "Uh oh, you are still using BASIC 1.0":END
90 PRINT "You are using BASIC 1.1 or later, program can continue"</
The second subtask, testing for the presence of a variable, is done here by trying to get the memory address of the variable. If that fails, it is obviously is not yet defined:
<
10 IF RND>.5 THEN bloop=-100*RND
20 ON ERROR GOTO 100
Line 1,164:
50 PRINT "ABS of bloop is",ABS(bloop)
90 END
100 IF ERL=30 THEN PRINT "Variable bloop not defined":RESUME 90</
(Like the Spectrum version, we have omitted checking for ABS because it is a builit-in function of the BASIC interpreter and therefore always present.)
Line 1,170:
'''Extra credit''': Finally, we can traverse the memory area where BASIC stores its integer, real, and string variables and add together all integers (type 1):
<
20 foo%=-4:bar%=7:baz%=9:somereal=3.141
30 varstart=&ae68 ' for CPC 664 and 6128
Line 1,187:
160 WEND
170 PRINT "There are"num"integer variables."
180 PRINT "Their sum is"sum</
{{out}}
Line 1,195:
=={{header|Logo}}==
{{works with|UCB Logo}}
<
if logoversion < 6.0 [print [too old!]]
if and [name? "a] [number? :a] [
print ifelse procedure? "abs [abs :a] [ifelse :a < 0 [minus :a] [:a]]
]</
=={{header|Logtalk}}==
<
:- object(my_application).
Line 1,237:
:- end_object.
</syntaxhighlight>
=={{header|Lua}}==
<
if bloop and math.abs then print(math.abs(bloop)) end</
=={{header|Maple}}==
The "version" kernel option returns a string similar to
<
Maple 16.00, SUN SPARC SOLARIS, Mar 3 2012, Build ID 732982</
The following does the trick for the first bit.
<
(There is also an internal "version" procedure, which returns a build ID, but this is less obvious to use, as you'd need a table mapping versions to build IDs. Besides, it prints stuff.)
It doesn't really make sense to ask whether a variable "exists"; it springs into existence by uttering it in code. So I'll interpret the problem as asking whether it is assigned some kind of numeric value to which abs() can be applied.
<
1/2
13</
Note that it is not necessary to check that the name "bloop" is assigned (though it is possible to do so), since an unassigned name is a first-class value in Maple. Another possible interpretation is that the symbolic expression
<
| bloop |</
is a perfectly good expression in Maple, so checking for the the "existence" of "bloop" isn't necessary in the first place. (One probably would not bother to check that abs() was actually there either, unless one expected that the standard library was broken.)
Here are the number and sum of the assigned integer globals in my current (fresh) session.
<
3
> eval(`+`(anames(integer)));
17
</syntaxhighlight>
If I change it, I get:
<syntaxhighlight lang="maple">
> foo := 25:
> nops([anames](integer));
Line 1,275:
> eval(`+`(anames(integer)));
42</
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
If[NameQ["bloop"] && NameQ["Abs"],
Print[Abs[bloop]]]</
{{out}}
<pre>7</pre>
<syntaxhighlight lang="text">globalintegers = Symbol /@ Select[Names["Global`*"], IntegerQ[Symbol[#]] &];
Print [ globalintegers //Length, " global integer(s) and their sum is: ", globalintegers // Total] </
{{out}}
Line 1,292:
=={{header|MATLAB}} / {{header|Octave}}==
<
v = version;
v(v=='.')=' ';
Line 1,312:
printf('abs(bloob) is %f\n',abs(bloob));
return;
end; </
Extra credit task:
<syntaxhighlight lang="matlab">
% find all integers
varlist = whos;
Line 1,330:
printf('sum of integer scalars: %i\n',intsum);
printf('sum of all integer elements: %i\n',intsumall);
</syntaxhighlight>
=={{header|Maxima}}==
<
build_info();
/* build_info("5.27.0", "2012-05-08 11:27:57", "i686-pc-mingw32", "GNU Common Lisp (GCL)", "GCL 2.6.8") */
Line 1,350:
/* Sum of integer variables */
lreduce("+", sublist(map(ev, values), integerp));</
=={{header|MAXScript}}==
<
(
versionNumber = maxVersion()
Line 1,380:
)
computeAbsBloop -17</
=={{header|NetRexx}}==
Line 1,386:
The language does however return a string identifying the version of NetRexx in effect when the current class was last processed. This information can be retrieved through the '''<tt>version</tt>''' ''special variable''.
<
options replace format comments java crossref symbols binary
Line 1,411:
end
return
</syntaxhighlight>
{{out}}
<pre>
Line 1,423:
=={{header|Nim}}==
In Nim, many checks are done at compile time. So, you have the choice to emit an error or warning at compile time or exit at runtime.
<
error "This compiler is too old" # Error at compile time.
Line 1,431:
when compiles abs(bloop):
echo abs(bloop)</
{{out}}
Line 1,438:
=={{header|OCaml}}==
<
- : string = "3.10.2"</
<
(fun major minor micro -> major, minor, micro) ;;
- : int * int * int = (3, 10, 2)</
Checking if an identifier (a value or a function) is bound doesn't make any sens in OCaml, which is strongly staticaly typed.
Line 1,453:
Oforth does not have global variables, only global constants.
<
| bl m |
System.VERSION println
Line 1,464:
System.Out "bloop value is : " << bl value << cr
System.Out "bloop abs is : " << bl value m perform << cr ;</
{{out}}
Line 1,483:
=={{header|OxygenBasic}}==
Compile time introspection
<syntaxhighlight lang="text">
$ rtlversion "0.4.0"
Line 1,500:
#endif
#endif
</syntaxhighlight>
=={{header|Oz}}==
We cannot check whether a variable is in scope (static property).
We <em>can</em> check whether a module exports a certain value. However, for system modules the compiler will refuse to compile if we try to use a non-existing value.
<
Version = {Property.get 'oz.version'}
%% Version is an atom like '1.4.0'. So we can not compare it directly.
Line 1,518:
else
{System.showInfo "Your Mozart version is too old."}
end</
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above}}
<
if(bloop!='bloop && type(abs) == "t_CLOSURE", abs(bloop))</
=={{header|Perl}}==
{{works with|Perl|5.x}}
<
require 5.6.1; # ditto
require 5.006_001; # ditto; preferred for backwards compatibility</
To check if a variable exists, do a name lookup of it in the package symbol table:
<
no strict 'refs'; # referring to variable by name goes against 'strict' pragma
if (defined($::{'bloop'})) {print abs(${'bloop'})} else {print "bloop isn't defined"};</
To check if certain built-in function is available (maybe you are using a stripped down build of perl binary, for example), one can use eval, but make sure the statement you are eval'ing doesn't have side effect:
<
print "abs() doesn't seem to be available\n" if $@;</
To check if a package or object provides certain method name, use 'can':
<
my $cpl = Math::Complex->new(1,1);
Line 1,550:
print "object \$cpl does not have 'explode' method\n"
unless $cpl->can('explode');
</syntaxhighlight>
Keep in mind that what a package has as method names are not equal to what method names can be called on this package, due to things like AUTOLOAD.
For most uses, introspection is meaningless, just call the method (and catch exceptions if it's important).
An example that solves the task:
<
our $bloop = -12;
if (defined $::bloop) {
Line 1,567:
else {
say '$bloop is not defined';
}</
Note that this program will exit with a message "Perl v5.10.0 required" if run under perl version lower than 5.10 and it actually uses a feature introduced in that version (<code>say</code>).
The program checks whether the variable is actually defined and not if it just exists.
Line 1,575:
Extra task:
<
package test;
use Regexp::Common;
Line 1,590:
my $num = @ints;
my $sum = sum @ints;
say "$num integers, sum = $sum";</
It prints:
<pre>
Line 1,597:
This example uses the <code>test</code> namespace instead of the default, because there already are some integer numbers in the <code>main</code> namespace like the PID, etc.
The program to sum those numbers would be:
<
use Regexp::Common;
use List::Util qw(sum);
Line 1,603:
my $num = @ints;
my $sum = sum @ints;
say "$num integers, sum = $sum";</
<pre>
4 integers, sum = 74717
Line 1,611:
The requires procedure behaves like a compiler directive, although it is in fact just a normal executable routine.
<!--<
<span style="color: #7060A8;">requires<span style="color: #0000FF;">(<span style="color: #008000;">"0.8.2"<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- crashes on 0.8.1 and earlier </span>
<span style="color: #7060A8;">requires<span style="color: #0000FF;">(<span style="color: #000000;">WINDOWS<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- crashes on Linux </span>
<span style="color: #7060A8;">requires<span style="color: #0000FF;">(<span style="color: #000000;">64<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- crashes on 32-bit
<!--</
If passed a string it compares it (intelligently) against the interpreter/compiler version and terminates in error with a suitable message should it be too old to cope. Otherwise the parameter must be an integer: <32 checks the platform, >=32 checks the word size. In the latter case when (interpreting and) it needs to, it hunts for a suitable alternative runtime and offers to re-run with that, maybe you need bigger ints, or maybe you only ship a 32-bit libcurl.dll.
Line 1,621:
The version() routine used by the above can also be called directly and returns a string:
<!--<
<span style="color: #0000FF;">?<span style="color: #7060A8;">version<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- eg "0.8.0"
<!--</
Normally only really useful for display, but you can of course break that down into an integer triplet with scanf(), as requires does, maybe something works on 0.7.7 and 0.7.9 but not 0.7.8.
Line 1,629:
Phix has a builtin abs() routine, which will be auto-included if referenced.
<!--<
<span style="color: #000080;font-style:italic;">--include pmaths.e -- (an auto-include, ok but not needed)
--include complex.e -- (not an auto-include, needed if used)</span>
Line 1,637:
<span style="color: #0000FF;">?<span style="color: #7060A8;">call_func<span style="color: #0000FF;">(<span style="color: #000000;">r_abs<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">-<span style="color: #000000;">42<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if
<!--</
Using complex_abs() is probably closer to the task requirement in that if complex.e is not included it will not be found/called.<br>
In this case it happens to give exactly the same result, however under the hood it is first promoting the -42 to -42+0i before returning sqrt((-42)*(-42)+(0)*(0)).
Line 1,645:
normally hidden away out of sight in builtins\VM.
<!--<
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins<span style="color: #0000FF;">/<span style="color: #000000;">VM<span style="color: #0000FF;">/<span style="color: #000000;">pStack<span style="color: #0000FF;">.<span style="color: #000000;">e</span> <span style="color: #000080;font-style:italic;">-- :%opGetST
-- copies from pglobals.e:</span>
Line 1,759:
<span style="color: #0000FF;">?<span style="color: #000000;">var_id<span style="color: #0000FF;">(<span style="color: #000000;">0<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- bloop+burp = 42</span>
<span style="color: #0000FF;">?<span style="color: #000000;">bloop<span style="color: #0000FF;">+<span style="color: #000000;">burp</span> <span style="color: #000080;font-style:italic;">-- "", doh
<!--</
{{out}}
Line 1,772:
Other routines of interest include
<!--<
<span style="color: #0000FF;">?<span style="color: #7060A8;">platform<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- WINDOWS=2, LINUX=3</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">machine_bits<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- 32 or 64</span>
Line 1,782:
<span style="color: #0000FF;">?<span style="color: #7060A8;">get_interpreter<span style="color: #0000FF;">(<span style="color: #0000FF;">)</span> <span style="color: #000080;font-style:italic;">-- eg "C:\Program Files (x86)\Phix\p.exe"
-- or perhaps "/home/pete/phix/p" on Linux
<!--</
Phix supports the absolute bare minimum use of #ifdef, for compatibility with OpenEuphoria, however it is almost always better
Line 1,789:
=={{header|Phixmonti}}==
<
The program will not be executed if the variable or function has not been defined.
=={{header|PHP}}==
<
if (version_compare(PHP_VERSION, '5.3.0', '<' ))
Line 1,809:
echo(array_sum($GLOBALS) . " is the total of variables in global scope.\n");
?></
=={{header|PicoLisp}}==
<
(bye) )
Line 1,820:
(num? bloop) # When 'bloop' is bound to a number
(getd 'abs) # and 'abs' defined as a function
(println (abs bloop)) ) # then print the absolute value</
=={{header|PL/I}}==
===Version 1===
<syntaxhighlight lang="pl/i">
S = SYSVERSION();
if substr(S, 6, 6) < '050000' then
do; put skip list ('Version of compiler is too old'); stop; end;
</syntaxhighlight>
===Version 2===
<
/*********************************************************************
* 02-11.2013 Walter Pachl
Line 1,851:
Else
Put Skip List('Version is '!!s);
End</
{{out}}
<pre>Version is PL/I for Win* 7.5</pre>
Line 1,858:
Variable pop_internal_version contains Poplog version in numeric form (as an integer) -- this one is most convenient for version checks. For printing one can use pop_version (which is a string containing more information).
<
if pop_internal_version < 150000 then
sysexit()
endif;</
Pop11 variables are named by words. Pop11 word is a unique version of string stored in dictionary. So we need first convert strings to words and then query about words. Pop11 variables can store any value including functions and in fact when one accesses a function like abs by name one merely access a variable abs which happen to hold predefined function abs. To follow spirit of the task as closely as possible we check if abs indeed holds functional value.
<
define check_and_call(x, y);
lvars wx=consword(x), wy=consword(y);
Line 1,881:
vars bloop = -5;
;;; Now prints 5
check_and_call('abs' , 'bloop') =></
Note that here bloop is defined as "permanent" variable, Pop11 also have lexical variables which are not available for introspection.
Line 1,891:
The compiler directive <code>#COMPILER</code>, introduced with PB/Win 8 and PB/CC <!--uncertain version here--> 4, will fail the compile if the compiler does not match at least one of the listed compilers, and is not at least the (optional) minimum version of that compiler.
<
#COMPILER PBWIN, PBCC 5</
=={{header|PowerShell}}==
<
if ($PSVersionTable['PSVersion'] -lt '2.0') {
exit
Line 1,908:
| Where-Object { $_.Value -is [int] } `
| Measure-Object -Sum Value `
| Select-Object Count,Sum</
=={{header|PureBasic}}==
<
CompilerError "You failed the version check!"
CompilerEndIf
Line 1,919:
Abs(bloop)
CompilerEndIf
CompilerEndIf</
=={{header|Python}}==
<
import sys
major, minor, bugfix = sys.version_info[:3]
Line 1,943:
if defined2('bloop') and defined2('abs') and callable(abs):
print abs(bloop)</
You can combine both tests, (But loose sight of which variable in missing/not callable by wrapping the whole function call in a try-except statement:
<
print abs(bloop)
except (NameError, TypeError):
print "Something's missing"</
Here is one way to print the sum of all the global integer variables:
<
variables = vars(__builtins__).copy()
variables.update(globals())
print sum(v for v in variables.itervalues() if type(v) == int)
sum_of_global_int_vars()</
=={{header|R}}==
{{works with|R|2.14.1}}
<syntaxhighlight lang="r">
if(getRversion() < "2.14.1")
{
warning("Your version of R is older than 2.14.1")
q() # exit R, with the option to cancel
}</
The constants <code>version</code> and <code>R.version</code> give further information about the version that is running. The function <code>R.Version()</code> provides the same information as a list.
We now perform three checks: we want to know if bloop is in the user workspace (global environment), if abs exists somewhere, and if abs is a function.
<
if(exists("bloop", envir=globalenv()) && exists("abs") && is.function(abs))
{
abs(bloop)
}</
Finally, we count how many integers are in the user workspace, and find their total. Note that a number followed by the letter L is considered to be an integer. See [[Integer_literals#R]] for more information.
<
qqq <- 45L
www <- -3L
Line 1,988:
the_ints <- mget(varnames[is_int], globalenv())
#Add them up
sum(unlist(the_ints))</
=={{header|Racket}}==
The usual hack:
<syntaxhighlight lang="racket">
#lang racket
(unless (string<=? "5.3" (version)) (error "ancient version"))
</syntaxhighlight>
Proper comparison:
<syntaxhighlight lang="racket">
(require version/utils)
(unless (version<=? "5.3" (version)) (error "ancient version"))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
if MY::{'$bloop'}.defined and CORE::{'&abs'}.defined { say abs $bloop }
Line 2,012:
my @ints = ($_ when Int for PROCESS::.values);
say "Number of PROCESS vars of type Int: ", +@ints;
say "PROCESS vars of type Int add up to ", [+] @ints;</
{{out}}
<pre>123
Line 2,023:
=={{header|Raven}}==
<
if 'version >= 20071104 required' print bye
'bloop' GLOBAL keys in && 'abs' CORE keys in
if bloop abs print</
=={{header|Retro}}==
This will exit if the version is less than 2019.6:
<
The existence of functions can be checked using '''d:lookup'''. In this, a helper function is provided to improve readability.
<syntaxhighlight lang="retro">
Checks for existence of "bloop" and "n:abs"
Line 2,045:
'bloop 'n:abs [ find nip ] bi@ and
[ 'bloop executeByName 'n:abs executeByName ] if
~~~</
Retro has no direct way to check for data types of functions. Assuming that a word class is defined for integer variables, we could do something like this:
<syntaxhighlight lang="retro">
#0 #0 [ dup d:class fetch &class:integer eq? [ d:xt fetch + [ n:inc ] dip ] [ drop ] choose ] d:for-each
</syntaxhighlight>
After execution the stack will have the number of variables found, and the accumulated sum of their values.
Line 2,057:
=={{header|REXX}}==
Test to see if the version is at least version 4.
<
/* theREXXinterpreterName level mm Mon yyyy */
parse version . level .
if level<4 then exit</
Test to see if the version is at least version 4, another example.
<
if level<4 then do
say
Line 2,068:
say x /*this displays everything.*/
exit /*or maybe: EXIT 13 */
end</
Test to see if the REXX variable "bloop" exists, version 1.
<
Test to see if the REXX variable "bloop" exists, version 2.
<
else say 'the "bloop" variable doesn''t exist.'</
Programming note: note the use of the double apostrophe (<big>''' ' ' '''</big>) which is within a quoted string (with apostrophes) [in the above and below REXX programming examples].
<br>Another test to see if the REXX variable "bloop" exists.
<
if symbol('bloop')=='VAR' then say 'the "bloop" variable exists.'
else say 'the "bloop" variable doesn''t exist.'</
In REXX, the ABS function is a built-in function (BIF).
<
g=abs(bloop)</
However, most REXX interpreters will allow this type of test:
<
else say 'function XYZ was found.'
exit
Line 2,092:
return 0
/*──────────────────────────────────────────────────────────────────────────────────────*/
syntax: return 1</
=={{header|Ring}}==
<
# Project: Introspection
Line 2,127:
func abs(bloop)
return fabs(bloop)
</syntaxhighlight>
Output:
<pre>
Line 2,138:
=={{header|Ruby}}==
<
puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs)</
'''Extra credit:'''
<
int_vars = []
sum = 0
Line 2,164:
a_float = 3.14
variable_counter(binding)</
{{out}}
Line 2,179:
=={{header|Scala}}==
<
val minimalVersion = 1.7
Line 2,187:
val bloop = Option(-42)
if (bloop.isDefined) bloop.get.abs
}</
=={{header|Slate}}==
No version string included inside the system presently.
<
<
lobby slotValues inject: 0 into: [| :sum :value | (value is: Integer) ifTrue: [sum + value] ifFalse: [sum]].</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
"uncomment the following to see what happens if bloop exists"
"Smalltalk at: #bloop put: -10."
Line 2,235:
] .
Transcript show: 'Num of global numeric vars: '; show: (hm printString); cr ;
show: 'Sum of global numeric vars: '; show: (sum printString) ; cr.</
=={{header|Tcl}}==
<
if {[info exists bloop] && [llength [info functions abs]]} {
puts [expr abs($bloop)]
}</
'''Extra credit:'''
<
variable sum_global_int 0
variable n_global_int 0
Line 2,257:
puts "number of global ints = $n_global_int"
puts "their sum = $sum_global_int"
}</
=={{header|TI-89 BASIC}}==
<
Prgm
Local l, i, vers
Line 2,284:
© There is no way to get a list of global variables.
EndPrgm</
=={{header|Toka}}==
Line 2,291:
Starting with Release 1.1, Toka allows for checking the version number:
<
Release 1.0 can be detected by doing:
<
Basic introspection is possible via '''`'''
<
=={{header|UNIX Shell}}==
{{works with|ksh93}}
There's no way to introspect the builtin arithmetic functions. We'll just try it and see if there's an error.
<
*93[[:alpha:]]+*) :;; #this appears to be ksh93, we're OK
*) echo "version appears to be too old"
Line 2,325:
done
print "${int_vars[*]}"
print -- $sum</
{{works with|bash}}
bash does not have a builtin math function "abs" -- we'll check for a user-defined shell function instead.
<
echo "version is too old"
exit
Line 2,354:
echo "${int_vars[*]}"
echo $sum
}</
=={{header|Ursala}}==
Line 2,379:
1 by the time it's displayed.
<
#import flo
#import lag
Line 2,391:
#cast %e
bloop = -1.</
{{out}}
<pre>1.000000e+00</pre>
Line 2,401:
To determine the version of the environment -- typically meaning which version of Microsoft Office is running -- the <code>Application</code> object has a <code>Version</code> property:
<
=={{header|Wren}}==
Line 2,411:
* Wren doesn't have reflection as such but is able to obtain and analyze the running script's source code. It is assumed for this purpose that the latter is sensibly formatted - only global declarations are not indented.
* Wren is dynamically typed and has a Num type but not an integer type. As far as the extra credit is concerned, the simplifying assumption has been made that a global variable is an integer if it's assigned an integer literal when it's declared.
<
import "io" for File
import "meta" for Meta
Line 2,456:
var vars = res[0]
var vals = res[1]
System.print("The sum of the %(vars.count) integer variables, %(vars), is %(Nums.sum(vals))"</
{{out}}
Line 2,465:
=={{header|Yabasic}}==
<
=={{header|zkl}}==
<
if (Language.version[1] < 10) System.exit("Too old");
var bloop=-123;
if ((1).resolve("abs",1) and resolve("bloop",8)) bloop.abs().println()</
{{out}}<pre>123</pre>
The concept of global vars doesn't really exist, only instance data.
<
self.vars; --> L(L("a",5),L("n",3),L("x",1),L("z","zoo"))
sum:=self.vars.reduce(fcn(p,[(nm,v)],r){
if((1).isType(v)){r.inc();p+v;} else p},0,num:=Ref(0));
println("Num int vars = ",num.value,". Sum = ",sum);</
{{out}}<pre>Num int vars = 2. Sum = 8</pre>
=={{header|ZX Spectrum Basic}}==
<
20 IF totram < 65535 THEN PRINT "Your 16k Spectrum is too old": STOP
30 REM variables must exist before they are used, otherwise we get an error
Line 2,489:
50 REM I haven't implemented this, because I have forgotten the handler address
60 LET bloob = -4: REM make sure bloob exists, by creating it.
70 PRINT ABS(bloob): REM function will be present, ZX Spectrum Basic is standardized.</
{{omit from|6502 Assembly|(1) depends on the hardware, (2) variable names don't exist at runtime, (3) everything is global scope.}}
|