Undefined values

From Rosetta Code

Jump to: navigation, search
Task
Undefined values
You are encouraged to solve this task according to the task description, using any language you may know.
For languages which have an explicit notion of an undefined value, identify and exercise those language's mechanisms for identifying and manipulating a variable's value's status as being undefined

Contents

[edit] Ada

Works with: GNAT

Ada language provides attribute 'Valid used to check if a scalar value is valid. An invalid value may appear as a result of unchecked type conversion, input, access through a dangling pointer etc. The language also provides the configuration pragma Normalize_Scalars which instructs the compiler to initialize uninitialized scalars with values, which when possible, would have the attribute 'Valid false. This pragma is required to be applied to the whole partition, which would require recompilation of the run-time library. For this reason, the presented example uses another pragma Initialize_Scalars. This one has the effect similar to Normalize_Scalars, but is GNAT-specific:

 
pragma Initialize_Scalars;
with Ada.Text_IO; use Ada.Text_IO;
 
procedure Invalid_Value is
type Color is (Red, Green, Blue);
X : Float;
Y : Color;
begin
if not X'Valid then
Put_Line ("X is not valid");
end if;
X := 1.0;
if X'Valid then
Put_Line ("X is" & Float'Image (X));
end if;
if not Y'Valid then
Put_Line ("Y is not valid");
end if;
Y := Green;
if Y'Valid then
Put_Line ("Y is " & Color'Image (Y));
end if;
end Invalid_Value;
 

Sample output:

X is not valid
X is 1.00000E+00
Y is not valid
Y is GREEN

Note that some types are always initialized valid. E.g. pointers, which are formally non-scalar, are initialized null. Another example are scalar types of which representation does not leave free bit patterns for invalid value. For instance a 32-bit integer will likely valid under any circumstances.

[edit] ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8-8d

Note: Some implementations (eg ALGOL 68C) also have a procedure named undefined that is called to indicated that the behaviour at a particular point in a program is unexpected, undefined, or non-standard.

MODE R = REF BOOL;
R r := NIL;
 
MODE U = UNION(BOOL, VOID);
U u := EMPTY;
 
IF r IS R(NIL) THEN
print(("r IS NIL", new line))
ELSE
print(("r ISNT NIL", new line))
FI;
 
CASE u IN
(VOID):print(("u is EMPTY", new line))
OUT print(("u isnt EMPTY", new line))
ESAC

Output:

r IS NIL
u is EMPTY

[edit] C#

In C# it's important to see the difference between reference and value types. For reference types (class instances) there is null as a general undefined reference.

string foo = null;

Dereferencing a null reference will throw a NullReferenceException.

This can't be used normally for value types (int, double, DateTime, etc.) since they are no references, so the following is a compiler error:

int i = null;

With .NET 2.0 there is an additional Nullable<T> structure which enables those semantics for value types as well:

int? answer = null;
if (answer == null) {
answer = 42;
}

There is a bit syntactic sugar involved here. The ? after the type name signals the compiler that it's a nullable type. This only works for value types since reference types are nullable due to their very nature.

But since value types still can't actually have a null value this gets converted into the following code by the compiler:

Nullable<int> answer = new Nullable<int>();
if (!answer.HasValue) {
answer = new Nullable<int>(42);
}

So it's a little compiler magic but in the end works just as one would expect.

[edit] Delphi

Delphi and its dialects don't have an undefined notion for all variables, but implement the notion of the keyword nil that is untyped, yet compatible with all pointer types and object references as well as interfaces. No compatibility is given for non-referenced data types like integers, enums and records - as well as string types (Some exceptions exist due to some compiler magic for those types).

For Referenced data types like pointers, classes and interfaces a reference can be explicitely set to undefined by assigning the NIL value for it. No memory management like garbage collection (except for interfaces) is done.

var
P: PInteger;
begin
New(P); //Allocate some memory
try
If Assigned(P) Then //...
begin
P^ := 42;
end;
finally
Dispose(P); //Release memory allocated by New
end;
end;

If P was a Class only the Assigned function would be available; in addition Dispose would have to be replaced by FreeAndNil or calling the .Free method of the instance. For Interfaces no such last call would be necessary as simple removal of the reference would be sufficient to trigger the Garbage Collector.

[edit] Haskell

The nullary function undefined returns the undefined value. But Haskell has no way whatsoever to identify or manipulate an undefined value at runtime. In fact, trying to evaluate anything that's undefined terminates the program immediately.

main = print $ 2 + undefined   -- An error.

This isn't quite as dangerous as it sounds because of Haskell's laziness. For example, this program:

main = print $ length [undefined, undefined, 1 `div` 0]

prints 3, since length doesn't need to evaluate any of the elements of its input.

In practice, one uses undefined less often than error, which behaves exactly the same except that it lets you choose the error message. So if you say

resurrect 0 = error "I'm out of orange smoke!"

then if you make the mistake of writing your program such that it at some point requires the value of resurrect 0, you'll get the error message "I'm out of orange smoke!".

[edit] Icon and Unicon

Icon/Unicon don't really have a notion of an undefined variable. There is a null value/data type that can be tested. However, it is possible in Unicon to interrogate the environment and obtain the string names of variables in the current (or calling procedures) and determine if a variable is defined.

[edit] Icon

The functions localnames, paramnames, staticnames, and globalnames don't exist in Icon.

[edit] Unicon

global G1
 
procedure main(arglist)
local ML1
static MS1
undeftest()
end
 
procedure undeftest(P1)
static S1
local L1,L2
every #write all local, parameter, static, and global variable names
write((localnames|paramnames|staticnames|globalnames)(&current,0)) # ... visible in the current co-expression at this calling level (0)
return
end

The output looks like:

L1
L2
P1
S1
main
undeftest
write
localnames
paramnames
staticnames
globalnames

Note that ML1,arglist, and MS1 are not listed. Also note, that procedures names are just global variables of type procedure.

[edit] J

J does not have a concept of an "undefined value" as such, but J does allow treatment of undefined names. The verb nc finds the (syntactic) class of a name. This result is negative 1 for names which have not been defined.

 
foo=: 3
nc;:'foo bar'
0 _1

From this we can infer that foo has a definition (and its definition is a noun), and bar does not have a definition.

This task also asked that we identify and exercise .. mechanisms for ... manipulating a variable's value's status as being undefined. So: a name can be made to be undefined using the verb erase. The undefined status can be removed by assigning a value to the name.

 
erase;:'foo bar'
1 1
nc;:'foo bar'
_1 _1
bar=:99
nc;:'foo bar'
_1 0

[edit] Java

In Java there are two kinds of types: primitive types and reference types. The former are predefined in the language (eg. boolean, int, long, double, &c), while the latter are pointers to objects (class instances or arrays).

Java has a special null type, the type of the expression null, that can be cast to any reference type; in practice the null type can be ignored and null can be treated as a special literal that can be of any reference type. When a reference variable has the special value null it refers to no object, meaning that it is undefined.

String string = null;        // the variable string is undefined
System.out.println(string); //prints "null" to std out
System.out.println(string.length()); // dereferencing null throws java.lang.NullPointerException

Variables of primitive types cannot be assigned the special value null, but there are wrapper classes corresponding to the primitive types (eg. Boolean, Integer, Long, Double, &c), that can be used instead of the corresponding primitive; since they can have the special value null it can be used to identify the variable as undefined.

int i = null;      // compilation error: incompatible types, required: int, found: <nulltype>
if (i == null) { // compilation error: incomparable types: int and <nulltype>
i = 1;
}

But this piece of code can be made valid by replacing int with Integer, and thanks to the automatic conversion between primitive types and their wrapper classes (called autoboxing) the only change required is in the declaration of the variable:

Integer i = null;  // variable i is undefined
if (i == null) {
i = 1;
}

[edit] JavaScript

var a;
 
typeof(a) == "undefined";
typeof(b) == "undefined";
 
var obj = {}; // Empty object.
obj.c == null;
 
obj.c = 42;
 
obj.c == 42;
delete obj.c;
obj.c == null;

[edit] Logo

Works with: UCB Logo

UCB Logo has separate namespaces for procedures and variables ("names"). There is no distinction between a proc/name with no value and an undefined proc/name.

; procedures
to square :x
output :x * :x
end
 
show defined? "x  ; true
show procedure? "x  ; true (also works for built-in primitives)
erase "x
show defined? "x  ; false
show square 3  ; I don't know how to square
 
; names
 
make "n 23
 
show name? "n  ; true
ern "n
show name? "n  ; false
show :n  ; n has no value

[edit] MUMPS

MUMPS does have variables with undefined values, but referencing them usually causes an error. To test for whether a value is undefined use the $Data function. If you are trying to read a value that may be undefined, use $Get as a wrapper. Note that an alternate form of $Get can return a specified value, which must be defined.

 IF $DATA(SOMEVAR)=0 DO UNDEF ; A result of 0 means the value is undefined
SET LOCAL=$GET(^PATIENT(RECORDNUM,0)) ;If there isn't a defined item at that location, a null string is returned

[edit] OCaml

(* There is no undefined value in OCaml,
but if you really need this you can use the built-in "option" type.
It is defined like this: type 'a option = None | Some of 'a *)

 
let inc = function
Some n -> Some (n+1)
| None -> failwith "Undefined argument";;
 
inc (Some 0);;
(* - : value = Some 1 *)
 
inc None;;
(* Exception: Failure "Undefined argument". *)

[edit] Oz

A program that uses an undefined variable does not compile. However, variables can be "unbound" or "free". If a program tries to read such a variable, the current thread will be suspended until the variable's value becomes determined.

declare X in
 
thread
if {IsFree X} then {System.showInfo "X is unbound."} end
{Wait X}
{System.showInfo "Now X is determined."}
end
 
{System.showInfo "Sleeping..."}
{Delay 1000}
{System.showInfo "Setting X."}
X = 42

Explicitly checking the status of a variable with IsFree is discouraged because it can introduce race conditions.

[edit] Perl

#!/usr/bin/perl -w
use strict;
 
# Declare the variable. It is initialized to the value "undef"
our $var;
 
# Check to see whether it is defined
print "var contains an undefined value at first check\n" unless defined $var;
 
# Give it a value
$var = "Chocolate";
 
# Check to see whether it is defined after we gave it the
# value "Chocolate"
print "var contains an undefined value at second check\n" unless defined $var;
 
# Give the variable the value "undef".
$var = undef;
# or, equivalently:
undef($var);
 
# Check to see whether it is defined after we've explicitly
# given it an undefined value.
print "var contains an undefined value at third check\n" unless defined $var;
 
# Give the variable a value of 42
$var = 42;
 
# Check to see whether the it is defined after we've given it
# the value 42.
print "var contains an undefined value at fourth check\n" unless defined $var;
 
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
print "Done\n";

Results in:

var contains an undefined value at first check
var contains an undefined value at third check
Done

[edit] PHP

<?php
// Check to see whether it is defined
if (!isset($var))
echo "var is undefined at first check\n";
 
// Give it a value
$var = "Chocolate";
 
// Check to see whether it is defined after we gave it the
// value "Chocolate"
if (!isset($var))
echo "var is undefined at second check\n";
 
// Give the variable an undefined value.
unset($var);
 
// Check to see whether it is defined after we've explicitly
// given it an undefined value.
if (!isset($var))
echo "var is undefined at third check\n";
 
// Give the variable a value of 42
$var = 42;
 
// Check to see whether the it is defined after we've given it
// the value 42.
if (!isset($var))
echo "var is undefined at fourth check\n";
 
// Because most of the output is conditional, this serves as
// a clear indicator that the program has run to completion.
echo "Done\n";
?>

Results in:

var is undefined at first check
var is undefined at third check
Done

[edit] PicoLisp

An internal symbol is initialized to NIL. Depending on the context, this is interpreted as "undefined". When called as a function, an error is issued:

: (myfoo 3 4)
!? (myfoo 3 4)
myfoo -- Undefined
?

The function 'default' can be used to initialize a variable if and only if its current value is NIL:

: MyVar
-> NIL
 
: (default MyVar 7)
-> 7
 
: MyVar
-> 7
 
: (default MyVar 8)
-> 7
 
: MyVar
-> 7

[edit] PureBasic

Variables are defined through a formal declaration or simply upon first use. Each variable is initialized to a value. PureBasic does not allow changing of a variable's status at runtime. It can be tested at compile-time and acted upon, however, it cannot be undefined once it is defined.

If OpenConsole()
 
CompilerIf Defined(var, #PB_Variable)
PrintN("var is defined at first check")
CompilerElse
PrintN("var is undefined at first check")
Define var
CompilerEndIf
 
CompilerIf Defined(var, #PB_Variable)
PrintN("var is defined at second check")
CompilerElse
PrintN("var is undefined at second check")
Define var
CompilerEndIf
 
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
 
EndIf

Sample output:

var is undefined at first check
var is defined at second check

[edit] Python

In Python names, (variables), can be dynamically created and deleted at run time.

# Check to see whether a name is defined
try: name
except NameError: print "name is undefined at first check"
 
# Create a name, giving it a string value
name = "Chocolate"
 
# Check to see whether the name is defined now.
try: name
except NameError: print "name is undefined at second check"
 
# Remove the definition of the name.
del name
 
# Check to see whether it is defined after the explicit removal.
try: name
except NameError: print "name is undefined at third check"
 
# Recreate the name, giving it a value of 42
name = 42
 
# Check to see whether the name is defined now.
try: name
except NameError: print "name is undefined at fourth check"
 
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
print "Done"

Results in:

name is undefined at first check
name is undefined at third check
Done

[edit] R

There are four cases to consider. To test whether a varaible has previously been defined, use exists.

 
exists("x")
 

If you want to declare a variable with undefined contents, use NULL.

 
x <- NULL
 

If you want to declare a variable with missing values, use NA.

 
y <- c(1, 4, 9, NA, 25)
z <- c("foo", NA, "baz")
 

(Note that there are different types of NA, namely NA_integer_, NA_real_, NA_character_, NA_complex_ and plain (logical) NA. In practice, you should hardly ever need to explicitly set which type of NA you are using, as it will be done automatically.)

Finally, you test for arguments that haven't been passed into a function with missing.

 
print_is_missing <- function(x)
{
print(missing(x))
}
 
print_is_missing() # TRUE
print_is_missing(123) # FALSE
 

[edit] Ruby

# Check to see whether it is defined
puts "var is undefined at first check" unless defined? var
 
# Give it a value
var = "Chocolate"
 
# Check to see whether it is defined after we gave it the
# value "Chocolate"
puts "var is undefined at second check" unless defined? var
 
# I don't know any way of undefining a variable in Ruby
 
# Because most of the output is conditional, this serves as
# a clear indicator that the program has run to completion.
puts "Done"

Results in:

var is undefined at first check
Done

[edit] Tcl

Tcl does not have undefined values, but variables may be undefined by being not set.

# Variables are undefined by default and do not need explicit declaration
 
# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at first check"}
 
# Give it a value
set var "Screwy Squirrel"
 
# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at second check"}
 
# Remove its value
unset var
 
# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at third check"}
 
# Give it a value again
set var 12345
 
# Check to see whether it is defined
if {![info exists var]} {puts "var is undefind at fourth check"}
 
puts "Done"

Yields this output:

var is undefind at first check
var is undefind at third check
Done
Personal tools
Support