Null object: Difference between revisions

From Rosetta Code
Content added Content deleted
Line 10: Line 10:
end if;</Ada>
end if;</Ada>
=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
In ALGOL 68 the NIL yield a name that does not refer to any value. NIL can never be
In ALGOL 68 the NIL yields a name that does not refer to any value. NIL can never be
coerced and can only appear where the context is [[ALGOL 68#strong|strong]].
coerced and can only appear where the context is [[ALGOL 68#strong|strong]].
REF STRING no result = NIL;
REF STRING no result = NIL;

Revision as of 22:53, 20 October 2008

Task
Null object
You are encouraged to solve this task according to the task description, using any language you may know.

Null (or nil) is the computer science concept of an undefined or unbound object. Some languages have an explicit way to access the null object, and some don't.

Show how to access null in your language by checking to see if an object is equivalent to the null object.

Ada

<Ada>with Ada.Text_Io;

if Object = null then

  Ada.Text_Io.Put_line("object is null");

end if;</Ada>

ALGOL 68

In ALGOL 68 the NIL yields a name that does not refer to any value. NIL can never be coerced and can only appear where the context is strong.

REF STRING no result = NIL;
STRING result := "";

IF no result :=: NIL THEN print(("no result :=: NIL", new line)) FI;
IF result :/=: NIL THEN print(("result :/=: NIL", new line)) FI;

IF no result IS NIL THEN print(("no result IS NIL", new line)) FI;
IF result ISNT NIL THEN print(("result ISNT NIL", new line)) FI;

COMMENT using the UNESCO/IFIP/WG2.1 ALGOL 68 character set
  result := °;
  IF REF STRING(result) :≠: ° THEN print(("result ≠ °", new line)) FI;
END COMMENT

Note the following gotcha:

REF STRING var := NIL;
IF var ISNT NIL THEN print(("The address of var ISNT NIL",new line)) FI;
IF REF STRING(var) IS NIL THEN print(("The REF STRING var IS NIL",new line)) FI

Output:

no result :=: NIL
result :/=: NIL
no result IS NIL
result ISNT NIL
The address of var ISNT NIL
The REF STRING var IS NIL

C

C's access to null is by way of a macro which simply evaluates to 0. <c>#include <stdio.h>

  1. include <stdlib.h>

if (object == NULL) {

  printf("object is null");

}</c>

C++

C++'s access to null is (as in C) by way of a macro which simply evaluates to 0. <cpp>#include <iostream>

  1. include <cstdlib>

if (object == NULL) {

  std::cout << "object is null";

}</cpp>

D

Use operator == to compare two objects by value. <d>import std.stdio; if (object is null) {

   writefln("object is null");

}</d>

Haskell

Haskell does not have a universal null value. There is a 'value of every type', the undefined value (sometimes written ⊥, 'bottom'), but it is essentially a sort of exception — any attempt to use it is an error.

undefined      -- undefined value provided by the standard library
error "oops"   -- another undefined value
head []        -- undefined, you can't take the head of an empty list

When one would use "null" as a marker for "there is no normal value here" (e.g. a field which is either an integer or null), one uses the Maybe type instead. The definition of Maybe is:

data Maybe a = Nothing | Just a

That is, a Maybe Integer is either Nothing or Just <some integer>.

There are many ways to work with Maybe, but here's a basic case expression:

case thing of
 Nothing -> "It's Nothing. Or null, whatever."
 Just v  -> "It's not Nothing; it is " ++ show v ++ "."

Io

 if(object == nil, "object is nil" println)

Java

In Java, "null" is a value of every reference type. <java>// here "object" is a reference if (object == null) {

  System.out.println("object is null");

}</java>

to test :thing
if empty? :thing [print [list or word is empty]]
end
print empty? []  ; true
print empty? "|| ; true

MAXScript

if obj == undefined then print "Obj is undefined"

OCaml

Maybe the closest type of OCaml would be the type option, which is defined like this in the standard library:

type 'a option = None | Some of 'a
 match v with
 | None -> "unbound value"
 | Some _ -> "bounded value"

Perl

In Perl, all variables are undefined by default. The defined function returns true iff its argument is defined. Hence, this statement on its own will print "Undefined." <perl>print +(defined $x ? 'Defined' : 'Undefined'), ".\n";</perl>

PHP

There is a special value NULL. You can test for it using is_null() or !isset() <php>$x = NULL; if (is_null($x))

 echo "\$x is null\n";</php>

Python

None is the sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a procedure[1]. <python>no_result = None if no_result is None:

 print "no_result is None"</python>

None also has available the is not operator: <python>result = "NotNone" if result is not None:

 print "result is not None"</python>

None is often used when defining default arguments of a procedure, for example: <python>def add_details(name, email=None, domain="gmail.com"): pass</python> In this case the missing email address could be calculated from the users name, and the default domain.

None is python object of type NoneType, hence it has various other attributes. <python>from types import NoneType print "Is no_result and instance of NoneType?",isinstance(no_result, NoneType)</python> Note: In previous versions of python None could be assigned to. Currently NoneType cannot be subclassed, nor instantiated.

Hence the following code would generate a TypeError (if uncommented) <python># class NewNone(NoneType): pass</python> NoneType cannot be used to create a new instance of None, hence the following code would generate a TypeError (if uncommented): <python># new_none=NoneType()</python> However None can be used as a key to a dictionary. This is because None has the attribute __hash__: <python>print "None in a dictionary with its hashing value:", {None:None.__hash__()}</python> None can be explicitly coerced to BoolType using the bool() procedure, in which case None is False. <python>print "Coercing None to bool gives:",bool(None)</python> However this coercion is normally done transparently for the programmer in an if (or while) statement: <python>if no_result:

 print "If no_result is None, then this should never happen"

else:

 print 'no_result "might" be None'</python>

Note that in the context of an if (or while) None is always coerced to False, caution should be taken as this property is not unique amongst python objects and many other objects also coerce to False. <python>false_list = [ None, False, 0, "", (), [], {} ] for false in false_list:

 print `false`,"==",bool(false),";",

print</python> By default if a procedure does not explicitly return a value, then None is returned. <python>def skip(): pass print "The returned value of skip is:",skip()</python> Output:

no_result is None
result is not None
Is no_result an instance of NoneType? True
None in a dictionary with its hashing value: {None: 82890272}
Coercing None to bool gives: False
no_result "might" be None
None == False ; False == False ; 0 == False ; '' == False ; () == False ; [] == False ; {} == False ;
The returned value of skip is: None

Ruby

if object == nil

  puts "object is null"

end

Scheme

<scheme>(null? object)</scheme> Note: "null?" here tests whether a value is the empty list.