all tasks

This commit is contained in:
Ingy döt Net 2013-04-11 01:07:29 -07:00
parent b83f433714
commit 68f8f3e56b
14735 changed files with 178959 additions and 0 deletions

View file

@ -0,0 +1 @@
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

View file

@ -0,0 +1,2 @@
---
note: Programming language concepts

View file

@ -0,0 +1,16 @@
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

View file

@ -0,0 +1,7 @@
var foo; // untyped
var bar:*; // explicitly untyped
trace(foo + ", " + bar); // outputs "undefined, undefined"
if (foo == undefined)
trace("foo is undefined"); // outputs "foo is undefined"

View file

@ -0,0 +1,23 @@
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;

View file

@ -0,0 +1,8 @@
ok% = TRUE
ON ERROR LOCAL IF ERR<>26 REPORT : END ELSE ok% = FALSE
IF ok% THEN
PRINT variable$
ELSE
PRINT "Not defined"
ENDIF
RESTORE ERROR

View file

@ -0,0 +1,11 @@
PROCtest
END
DEF PROCtest
LOCAL array()
IF !^array() < 2 PRINT "Array is undefined"
DIM array(1,2)
IF !^array() > 1 PRINT "Array is defined"
!^array() = 0 : REM Set array to undefined state
ENDPROC

View file

@ -0,0 +1,16 @@
#include <stdio.h>
#include <stdlib.h>
int main()
{
int junk, *junkp;
/* Print an unitialized variable! */
printf("junk: %d\n", junk);
/* Follow a pointer to unitialized memory! */
junkp = malloc(sizeof *junkp);
if (junkp)
printf("*junkp: %d\n", *junkp);
return 0;
}

View file

@ -0,0 +1,10 @@
;; assumption: none of these variables initially exist
(defvar *x*) ;; variable exists now, but has no value
(defvar *y* 42) ;; variable exists now, and has a value
(special-variable-p '*x*) -> T ;; Symbol *x* names a special variable
(boundp '*x*) -> NIL ;; *x* has no binding
(boundp '*y*) -> T
(special-variable-p '*z*) -> NIL ;; *z* does not name a special variable

View file

@ -0,0 +1,3 @@
(makunbound '*y*) ;; *y* no longer has a value; it is erroneous to evaluate *y*
(setf *y* 43) ;; *y* is bound again.

View file

@ -0,0 +1,7 @@
(defvar *dyn*) ;; special, no binding
(let (*dyn* ;; locally scoped override, value is nil
lex) ;; lexical, value is nil
(list (boundp '*dyn*) *dyn* (boundp 'lex) lex)) -> (T NIL NIL NIL)
(boundp '*global*) -> NIL

View file

@ -0,0 +1,19 @@
void main() {
// Initialized:
int a = 5;
double b = 5.0;
char c = 'f';
int[] d = [1, 2, 3];
// Default initialized:
int aa; // set to 0
double bb; // set to double.init, that is a NaN
char cc; // set to 0xFF
int[] dd; // set to null
int[3] ee; // set to [0, 0, 0]
// Undefined (contain garbage):
int aaa = void;
double[] bbb = void;
int[3] eee = void;
}

View file

@ -0,0 +1,13 @@
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;

View file

@ -0,0 +1,3 @@
if (foo == bar || (def baz := lookup(foo)) != null) {
...
}

View file

@ -0,0 +1,7 @@
IsBound(a);
# true
Unbind(a);
IsBound(a);
# false

View file

@ -0,0 +1,97 @@
package main
import "fmt"
var (
s []int
p *int
f func()
i interface{}
m map[int]int
c chan int
)
func main() {
fmt.Println("Exercise nil objects:")
status()
// initialize objects
s = make([]int, 1)
p = &s[0] // yes, reference element of slice just created
f = func() { fmt.Println("function call") }
i = user(0) // see user defined type just below
m = make(map[int]int)
c = make(chan int, 1)
fmt.Println("\nExercise objects after initialization:")
status()
}
type user int
func (user) m() {
fmt.Println("method call")
}
func status() {
trySlice()
tryPointer()
tryFunction()
tryInterface()
tryMap()
tryChannel()
}
func reportPanic() {
if x := recover(); x != nil {
fmt.Println("panic:", x)
}
}
func trySlice() {
defer reportPanic()
fmt.Println("s[0] =", s[0])
}
func tryPointer() {
defer reportPanic()
fmt.Println("*p =", *p)
}
func tryFunction() {
defer reportPanic()
f()
}
func tryInterface() {
defer reportPanic()
// normally the nil identifier accesses a nil value for one of
// six predefined types. In a type switch however, nil can be used
// as a type. In this case, it matches the nil interface.
switch i.(type) {
case nil:
fmt.Println("i is nil interface")
case interface {
m()
}:
fmt.Println("i has method m")
}
// assert type with method and then call method
i.(interface {
m()
}).m()
}
func tryMap() {
defer reportPanic()
m[0] = 0
fmt.Println("m[0] =", m[0])
}
func tryChannel() {
defer reportPanic()
close(c)
fmt.Println("channel closed")
}

View file

@ -0,0 +1,3 @@
main = print $ "Incoming error--" ++ undefined
-- When run in GHC:
-- "Incoming error--*** Exception: Prelude.undefined

View file

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

View file

@ -0,0 +1 @@
resurrect 0 = error "I'm out of orange smoke!"

View file

@ -0,0 +1,2 @@
undefined :: a
undefined = error "Prelude.undefined"

View file

@ -0,0 +1,16 @@
import Control.Exception (catch, evaluate, ErrorCall)
import System.IO.Unsafe (unsafePerformIO)
import Prelude hiding (catch)
import Control.DeepSeq (NFData, deepseq)
scoopError :: (NFData a) => a -> Either String a
scoopError x = unsafePerformIO $ catch right left
where right = deepseq x $ return $ Right x
left e = return $ Left $ show (e :: ErrorCall)
safeHead :: (NFData a) => [a] -> Either String a
safeHead = scoopError . head
main = do
print $ safeHead ([] :: String)
print $ safeHead ["str"]

View file

@ -0,0 +1,15 @@
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

View file

@ -0,0 +1,3 @@
foo=: 3
nc;:'foo bar'
0 _1

View file

@ -0,0 +1,7 @@
erase;:'foo bar'
1 1
nc;:'foo bar'
_1 _1
bar=:99
nc;:'foo bar'
_1 0

View file

@ -0,0 +1,3 @@
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

View file

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

View file

@ -0,0 +1,4 @@
Integer i = null; // variable i is undefined
if (i == null) {
i = 1;
}

View file

@ -0,0 +1,13 @@
var a;
typeof(a) === "undefined";
typeof(b) === "undefined";
var obj = {}; // Empty object.
typeof(obj.c) === "undefined";
obj.c = 42;
obj.c === 42;
delete obj.c;
typeof(obj.c) === "undefined";

View file

@ -0,0 +1,3 @@
var a;
a === void 0; // true
b === void 0; // throws a ReferenceError

View file

@ -0,0 +1,18 @@
HAI 1.3
I HAS A foo BTW, INISHULIZD TO NOOB
DIFFRINT foo AN FAIL, O RLY?
YA RLY, VISIBLE "FAIL != NOOB"
OIC
I HAS A bar ITZ 42
bar, O RLY?
YA RLY, VISIBLE "bar IZ DEFIND"
OIC
bar R NOOB BTW, UNDEF bar
bar, O RLY?
YA RLY, VISIBLE "SHUD NEVAR C DIS"
OIC
KTHXBYE

View file

@ -0,0 +1,19 @@
; 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

View file

@ -0,0 +1,9 @@
print( a )
local b
print( b )
if b == nil then
b = 5
end
print( b )

View file

@ -0,0 +1 @@
global var;

View file

@ -0,0 +1 @@
isempty(var)

View file

@ -0,0 +1 @@
var = [1, 2, NaN, 0/0, inf-inf, 5]

View file

@ -0,0 +1 @@
isnan(var)

View file

@ -0,0 +1,2 @@
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

View file

@ -0,0 +1,14 @@
a
-> a
a + a
-> 2 a
ValueQ[a]
-> False
a = 5
-> 5
ValueQ[a]
-> True

View file

@ -0,0 +1,2 @@
ConditionalExpression[a, False]
->Undefined

View file

@ -0,0 +1,2 @@
Sin[Undefined]
-> Undefined

View file

@ -0,0 +1,8 @@
a = Undefined
-> Undefined
a
-> Undefined
ValueQ[a]
-> True

View file

@ -0,0 +1,13 @@
(* 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". *)

View file

@ -0,0 +1,12 @@
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

View file

@ -0,0 +1 @@
v == 'v

View file

@ -0,0 +1 @@
is_entry("v") == NULL;

View file

@ -0,0 +1,33 @@
<?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";
?>

View file

@ -0,0 +1 @@
my $x; $x = 42; $x = Nil; say $x.WHAT; # prints Any()

View file

@ -0,0 +1 @@
say Method ~~ Routine; # Bool::True

View file

@ -0,0 +1,3 @@
my $x; say $x.WHAT; # Any()
my Int $y; say $y.WHAT; # Int()
my Str $z; say $z.WHAT; # Str()

View file

@ -0,0 +1,35 @@
#!/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";

View file

@ -0,0 +1,4 @@
: (myfoo 3 4)
!? (myfoo 3 4)
myfoo -- Undefined
?

View file

@ -0,0 +1,14 @@
: MyVar
-> NIL
: (default MyVar 7)
-> 7
: MyVar
-> 7
: (default MyVar 8)
-> 7
: MyVar
-> 7

View file

@ -0,0 +1,11 @@
> zero_type(UNDEFINED);
Result: 1
> mapping bar = ([ "foo":"hello" ]);
> zero_type(bar->foo);
Result: 0
> zero_type(bar->baz);
Result: 1
> bar->baz=UNDEFINED;
Result: 0
> zero_type(bar->baz);
Result: 0

View file

@ -0,0 +1,21 @@
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

View file

@ -0,0 +1,28 @@
# 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"

View file

@ -0,0 +1 @@
exists("x")

View file

@ -0,0 +1 @@
x <- NULL

View file

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

View file

@ -0,0 +1,7 @@
print_is_missing <- function(x)
{
print(missing(x))
}
print_is_missing() # TRUE
print_is_missing(123) # FALSE

View file

@ -0,0 +1,23 @@
/*REXX program to test if a variable is defined. */
tlaloc = "rain god of the Aztecs."
/*check if the rain god is defined.*/
y='tlaloc'
if symbol(y)=="VAR" then say y 'is defined.'
else say y "ain't defined."
/*check if the fire god is defined.*/
y='xiuhtecuhtli'
if symbol(y)=="VAR" then say y 'is defined.'
else say y "ain't defined."
drop tlaloc /*un-define the TLALOC variable. */
/*check if the rain god is defined.*/
y='tlaloc'
if symbol(y)=="VAR" then say y 'is defined.'
else say y "ain't defined."

View file

@ -0,0 +1,15 @@
# 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"

View file

@ -0,0 +1,2 @@
Smalltalk includesKey: #FooBar
myNamespace includesKey: #Baz

View file

@ -0,0 +1,24 @@
# 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"

View file

@ -0,0 +1,3 @@
VAR1="VAR1"
echo ${VAR1:-"Not set."}
echo ${VAR2:-"Not set."}