[contest] Is a Cow an animal ++

Norbert Nemec Norbert at Nemec-online.de
Thu Sep 30 03:02:55 PDT 2010


Idea: rather than trying to change state, one could attempt a different 
approach:

When "food" is "eaten", this action could define a new compile time 
object "eater(food)" as some value. When eating something twice, this 
would attempt to define the same object as two different values, causing 
a compiler error.

Of course, this still means that the process of eating must happen at 
compile time. Obviously the following can never be caught at compile time:

if(runtime_userinput) {
	rabbit1.eat(carrot);
}
if(another_runtime_userinput) {
	rabbit2.eat(carrot);
}

Which confirms my original position: the final three tests in the 
contest are flawed by concept. If the actions of eating and slaughtering 
are supposed to happen at run-time, no compiler in the world can 
reliably detect them happening twice. Of course, if the whole action 
happens at compile-time, it is a simple matter of finding a nice syntax 
to express a regular program as compile-time code (e.g. within a CTFE 
routine)





On 09/27/2010 02:26 PM, bearophile wrote:
> This is a harder variant of an old and very simple OOP problem:
> http://merd.sourceforge.net/pixel/language-study/various/is-a-cow-an-animal/
>
> The problem presents a hierarchy of types, some rules, and 11 tests, each one of them represents a bug because it contains a violation of the rules. You have to write the program in a way that the type system refuses as many of those 11 tests as possible at compile-time. There are many acceptable ways to write the program, for example you may use functional programming, so you are able to return different types, that enforce different rules, so it's not a contest, it's more like a demonstration.
>
> A basic Python implementation catches none of the 11 tests at compile time :-) A basic D implementation that I have written catches five of the 11 bugs at compile time:
> http://ideone.com/87q67
> I will try to write a more statically typed D version.
>
> The site shows four C++ versions, the fourth is able to catch 8 of the 11 bugs at compile-time. A type system that supports typestates is probably able to catch all 11 bugs (because for example the Cow type has two states, alive and eaten, and you can't perform some operations on a eaten cow, like eating it again), but probably it's very hard to do this with D.
>
> The fourth C++ version contains a line that I am am not even sure how to translate to D (maybe there is a workaround with template constraints):
> (void) static_cast<My_kind *>((Kind *) 0);
>
> Bye,
> bearophile



More information about the Digitalmars-d mailing list