Introspection

From Rosetta Code
Revision as of 04:54, 27 August 2008 by rosettacode>Paddy3118 (→‎{{header|Python}}: Sum of global integer vars)
Task
Introspection
You are encouraged to solve this task according to the task description, using any language you may know.

This task asks to

  • 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.
  • check whether the variable "bloop" exists and whether the math-function "abs()" is available and if yes compute abs(bloop).

Extra credit:

  • Report the number of integer variables in global scope, and their sum.


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: <ada>with Ada.Integer_Text_IO, Ada.Text_IO;

procedure Introspection is
   use Ada.Integer_Text_IO, Ada.Text_IO;
begin
   Put ("Integer range: ");
   Put (Integer'First);
   Put (" .. ");
   Put (Integer'Last);
   New_Line;

   Put ("Float digits: ");
   Put (Float'Digits);
   New_Line;
end Introspection;</ada>

C

Determining the make and version of the compiler, C standard, and environment features is one of the primary uses of the C preprocessor. This has allowed C to become the lingua franca of the open source movement.

Works with: C version 94 and later

<c>#if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L

#pragma error("C compiler must adhere to at least C99 for the following code.")
#else
/* rest of file */
#endif</c>

However, there is no facility in C for checking whether individual variables and functions have been declared. In open source, the GNU autotools are often used for this purpose, doing this kind of check in a shell script and defining symbols such as __HAVE_ABS__ which can be checked by the preprocessor.

D

The DMD compiler has macros defined for the version, more easily accessible through std.compiler:

<d>import std.compiler;

 static if (version_major < 2 || version_minor > 7) {
   // this prevents further compilation
   static assert (false, "I can't cope with this compiler version");
 }</d>

To check if something compiles or not:

<d>version(D_Version2) {

 static if( __traits(compiles,abs(bloop)) ) {

  typeof(abs(bloop)) computeAbsBloop()  {
     return abs(bloop);
  }

 }
} else static assert(0, "Requires D version 2");</d>

Note that this checks that bloop is of a type which abs() accepts. It is generic code; if the type of abs() changes, so will the return type of the function. The test can also be written so that it will work on D version 1:

<d>static if ( is(typeof(abs(bloop))) ) {

  typeof(abs(bloop)) computeAbsBloop()  {
     return abs(bloop);
  }
}</d>

E

def version := interp.getProps()["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.)

escape fail {
    def &x := meta.getState().fetch("&bloop", fn { fail("no bloop") })
    if (!x.__respondsTo("abs", 0)) { fail("no abs") }
    x.abs()
}

Forth

Standard Forth doesn't necessarily provide for version numbers, but you can query information about the environment at interpretation time:

s" MAX-U" environment? [IF]
   0xffffffff <> [IF] .( Requires 32 bits! ) bye [THEN]
[THEN]
[defined] bloop [if]
[defined] abs [if]
  bloop @ abs
[then] [then]

Io

if(System version < 20080000, exit)
if(hasSlot("bloop") and bloop hasSlot("abs"), bloop abs)

Io can also inspect the source code of methods written in Io:

getSlot("arbitraryMethod") code

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:

   6 (2!:55@:]^:<) 0 ". 1 { 9!:14

Compute abs(bloop) if abs is a function and bloop is data:

   ".(#~3 0*./ .=4!:0@;:)'abs bloop'

Extra credit: report the number of integer variables in global scope, and their sum:

   ((],&(+/);@#~)((=<.)@[^:](''-:$)*.0=0{.@#,)&>)".&.>4!:1]0

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).

So this expression takes pains to emulate solutions in other languages (i.e. only reports globals that are single numbers, and whose value = floor(value), so that even if the number is represented as a float in the machine, you still get the right answer).

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 System class: <java>public class VersCheck { public static void main(String[] args) { String vers = System.getProperty("java.version"); vers = vers.substring(0,vers.indexOf('.')) + "." + //some String fiddling to get the version number into a usable form vers.substring(vers.indexOf('.')+1,vers.lastIndexOf('.')); if(Double.parseDouble(vers) >= 1.5){ System.out.println("YAY!"); }else{ System.err.println("Must use Java >=1.5"); } } }</java>

MAXScript

fn computeAbsBloop bloop =
(
    versionNumber = maxVersion()

    if versionNumber[1] < 9000 then
    (
        print "Max version 9 required"
        return false
    )

    if bloop == undefined then
    (
        print "Bloop is undefined"
        return false
    )

    try
    (
        abs bloop
    )
    catch
    (
        print "No function abs"
        false
    )
)

computeAbsBloop -17

OCaml

<ocaml># Sys.ocaml_version;; - : string = "3.10.2"</ocaml>

<ocaml># Scanf.sscanf (Sys.ocaml_version) "%d.%d.%d"

              (fun major minor micro -> major, minor, micro) ;;

- : int * int * int = (3, 10, 2)</ocaml>

Checking if an identifier (a value or a function) is bound doesn't make any sens in OCaml, which is strongly staticaly typed.

For optionnal values we would rather use a structure to contain them, for example an association lists for a small amount of items, or an hash table for a huge amount of data. Both can contain expressions or functions.

Perl

Works with: Perl version 5.x

<perl>require v5.6.1; # run time version check

require 5.6.1;     # ditto
require 5.006_001; # ditto; preferred for backwards compatibility</perl>

Checking whether a variable exists is kind of daft. Good style dictates that I declare the variables I'm going to use, and then I already know $bloop exists. Checking for the value of a variable however is something very common. <perl>defined $bloop;

# returns true if bloop has been filled with something useful</perl>

What if 'bloop' is a computed value? Good style forbids that I dereference willy-nilly variables with unknown names, that's what hashes are good for. <perl>$computed = 'bloop';

exists $introspect{$computed};
# returns true if the key bloop exists in hash %introspect</perl>

But neither you can do this, for example: <perl>#$bloop = -123; # uncomment this line to see the difference

if (defined($::{'bloop'})) {print abs(${'bloop'})} else {print "bloop isn't defined"};</perl>

The trick in this example is to use bloop variable by reference ${'bloop'} (otherwise it will be created unconditionally by the compiler). Perl store nametables inside hashes: '::' - for main package and 'xxx::' for package 'xxx'. In Perl, you cannot check for the existence of built-in functions, of which abs() is one. However in practice that's not a problem because most functions live in classes, and those are easily inspectable at runtime. <perl>use UNIVERSAL qw(can);

use Math::Cephes qw();
print Math::Cephes->fabs($bloop) if can 'Math::Cephes', 'fabs';</perl>

Pop11

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).

;;; Exit if version below 15.00
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.

;;; We do main task in a procedure
define check_and_call(x, y);
   lvars wx=consword(x), wy=consword(y);
   if identprops(wx) = 0 and isprocedure(valof(wx))
      and identprops(wy) = 0 then
          return(valof(wx)(valof(wy)));
   else
        return("failed");
   endif;
enddefine;
;;; Prints failed because bloop is undefined
check_and_call('abs' , 'bloop') =>
;;; Define bloop
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.

Python

<python># Checking for system version

import sys
major, minor, bugfix = sys.version_info[:3]
if major < 2:
    sys.exit('Python 2 is required')


def defined(name): # LBYL (Look Before You Leap)
    return name in globals() or name in locals() or name in vars(__builtins__)
def defined2(name): # EAFP (Easier to Ask Forgiveness than Permission)
    try:
         eval(name)
         return True
    except NameError:
         return False
if defined('bloop') and defined('abs') and callable(abs):
    print abs(bloop)
if defined2('bloop') and defined2('abs') and callable(abs):
    print abs(bloop) </python>

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: <python>try:

   print abs(bloop)

except (NameError, TypeError):

   print "Something's missing"</python>

Here is one way to print the sum of all the global integer variables: <python>def sum_of_global_int_vars():

   variables = vars(__builtins__).copy()
   variables.update(globals())
   print sum(v for v in variables.itervalues() if type(v) == int)

sum_of_global_int_vars()</python>

Raven

VERSION 0 prefer 20071104 <
if  'version >= 20071104 required' print bye
'bloop' GLOBAL keys in && 'abs' CORE keys in
if  bloop abs print

Ruby

exit if RUBY_VERSION < '1.8.6'

 puts bloop.abs if defined?(bloop) and bloop.respond_to?(:abs)

Tcl

package require Tcl 8.2 ; # throws an error if older
if {[info exists bloop] && [llength [info functions abs]]} {
  puts [expr abs($bloop)]
}

Toka

Works with: Toka version 1.1+

Starting with Release 1.1, Toka allows for checking the version number:

VERSION 101 > [ bye ] ifFalse

Release 1.0 can be detected by doing:

` VERSION FALSE = [ bye ] ifTrue

Basic introspection is possible via `

` bloop FALSE <> ` abs FALSE <> and [ ` bloop invoke @ ` abs invoke ] ifTrue