Undefined values: Difference between revisions

From Rosetta Code
Content added Content deleted
m (+output, comment)
Line 19: Line 19:


== Icon and Unicon ==
== Icon and Unicon ==
Icon/Unicon don't really have a notion of an undefined variable. There is a [[Undefined_values/Check_if_a_variable_is_defined|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).
Icon/Unicon don't really have a notion of an undefined variable. There is a [[Undefined_values/Check_if_a_variable_is_defined|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.
==={{header|Icon}}===
==={{header|Icon}}===
The functions localnames, paramnames, staticnames, and globalnames don't exist in Icon.
The functions localnames, paramnames, staticnames, and globalnames don't exist in Icon.

Revision as of 11:28, 5 May 2010

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

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.

<lang haskell>main = print $ 2 + undefined -- An error.</lang>

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

<lang haskell>main = print $ length [undefined, undefined, 1 `div` 0]</lang>

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

<lang haskell>resurrect 0 = error "I'm out of orange smoke!"</lang>

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!".

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.

Icon

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

Unicon

<lang 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</lang>

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.

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.

<lang J>

 foo=: 3
 nc;:'foo bar'

0 _1</lang>

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.

<lang J>

  erase;:'foo bar'

1 1

  nc;:'foo bar'

_1 _1

  bar=:99
  nc;:'foo bar'

_1 0</lang>

JavaScript

<lang 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;</lang>

OCaml

<lang 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". *)</lang>

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.

<lang oz>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</lang>

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

Perl

<lang perl>#!/usr/bin/perl -w use strict;

  1. Declare the variable

our $var;

  1. Check to see whether it is defined

print "var contains an undefined value at first check\n" unless defined $var;

  1. Give it a value

$var = "Chocolate";

  1. Check to see whether it is defined after we gave it the
  2. value "Chocolate"

print "var contains an undefined value at second check\n" unless defined $var;

  1. Give the variable an undefined value.

$var = undef;

  1. or, equivalently:

undef $var;

  1. Check to see whether it is defined after we've explicitly
  2. given it an undefined value.

print "var contains an undefined value at third check\n" unless defined $var;

  1. Give the variable a value of 42

$var = 42;

  1. Check to see whether the it is defined after we've given it
  2. the value 42.

print "var contains an undefined value at fourth check\n" unless defined $var;

  1. Because most of the output is conditional, this serves as
  2. a clear indicator that the program has run to completion.

print "Done\n";</lang>

Results in:

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

PHP

<lang 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"; ?></lang>

Results in:

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

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: <lang PicoLisp>: (myfoo 3 4) !? (myfoo 3 4) myfoo -- Undefined ?</lang> The function 'default' can be used to initialize a variable if and only if its current value is NIL: <lang PicoLisp>: MyVar -> NIL

(default MyVar 7)

-> 7

MyVar

-> 7

(default MyVar 8)

-> 7

MyVar

-> 7</lang>

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. <lang PureBasic>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</lang> Sample output:

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

Python

<lang python># Check to see whether it is defined try: var except NameError: print "var is undefined at first check"

  1. Give it a value

var = "Chocolate"

  1. Check to see whether it is defined after we gave it the
  2. value "Chocolate"

try: var except NameError: print "var is undefined at second check"

  1. Give the variable an undefined value.

del var

  1. Check to see whether it is defined after we've explicitly
  2. given it an undefined value.

try: var except NameError: print "var is undefined at third check"

  1. Give the variable a value of 42

var = 42

  1. Check to see whether the it is defined after we've given it
  2. the value 42.

try: var except NameError: print "var is undefined at fourth check"

  1. Because most of the output is conditional, this serves as
  2. a clear indicator that the program has run to completion.

print "Done"</lang>

Results in:

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

Ruby

<lang ruby># Check to see whether it is defined puts "var is undefined at first check" unless defined? var

  1. Give it a value

var = "Chocolate"

  1. Check to see whether it is defined after we gave it the
  2. value "Chocolate"

puts "var is undefined at second check" unless defined? var

  1. I don't know any way of undefining a variable in Ruby
  1. Because most of the output is conditional, this serves as
  2. a clear indicator that the program has run to completion.

puts "Done"</lang>

Results in:

var is undefined at first check
Done

Tcl

Tcl does not have undefined values, but variables may be undefined by being not set. <lang tcl># Variables are undefined by default and do not need explicit declaration

  1. Check to see whether it is defined

if {![info exists var]} {puts "var is undefind at first check"}

  1. Give it a value

set var "Screwy Squirrel"

  1. Check to see whether it is defined

if {![info exists var]} {puts "var is undefind at second check"}

  1. Remove its value

unset var

  1. Check to see whether it is defined

if {![info exists var]} {puts "var is undefind at third check"}

  1. Give it a value again

set var 12345

  1. Check to see whether it is defined

if {![info exists var]} {puts "var is undefind at fourth check"}

puts "Done"</lang> Yields this output:

var is undefind at first check
var is undefind at third check
Done