5 points · by vmathew · 16y ago · 10 comments
Ocaml basically does that, though it feels sort of second-nature rather than a restriction, because syntactically, the only way to get a reference is to take a reference of something. Eiffel "attached types" are similar (guaranteed to always be "attached" to a non-Void value), but have a somewhat more complex scheme of possibilities: http://docs.eiffel.com/sites/docs.eiffel.com/files/void-safe...
A big potential problem, I think, would be whether people use null-setting patterns often enough that they would work around the proposed change, by using these default-constructed objects as glorified null values, maybe by having them set an "I'm a dummy object" flag internally or something.
Foo * pFoo = NULL;
if(x) {
// stuff
pFoo = Foo::p1;
} else {
// stuff
pFoo = Foo::p2;
}
if(pFoo) {
pFoo->bar();
}
I can't declare pFoo inside if(x) due to scoping, so I have to declare it before initializing it meaningfully. It has to be either a pointer to the object (references don't work without initialization) or an object copy, which would not modify the original object... Foo foo; // initialized to default
if (x) {
// stuff
foo = Foo.p1;
} else {
// stuff
foo = Foo.p2;
}
// No need to check if this is a valid reference, it always will be.
foo.bar(); struct node {
char * key;
char * value;
struct node * left; // NULL if we have no left child
struct node * right; // NULL if we have no right child
}
Sure, you could add a separate "int flags" field to record which children a node has, but that would just make the code slower and cause it to use more RAM.By means of example:
irb(main):003:0> nil.class
=> NilClass
irb(main):004:0> nil.nil?
=> true
irb(main):005:0> nil.methods
=> ["inspect", "method", "tap", "&", "clone", "public_methods", "__send__", ...]
irb(main):006:0> nil.is_a? String
=> false class Node {
static const Node EMPTY_NODE = Node();
String key;
String value;
Node left = EMPTY_NODE;
Node right = EMPTY_NODE;
Node(String key, String value) {
this.key = key;
this.value = value;
}
static void traverseInorder(Node n, Visitor v) {
if (n.left != EMPTY_NODE) {
traverseInorder(left, v);
}
v.visit (n);
if (n.right != EMPTY_NODE) {
traverseInorder(right, v);
}
}
}