[contest] Is a Cow an animal ++
bearophile
bearophileHUGS at lycos.com
Mon Sep 27 19:06:18 PDT 2010
Simen kjaeraas:
> This is a static assert of sorts. Basically, the function will only
> compile if Kind is a subtype of My_kind. In D, you would use
> is( Kind : My_kind ), where Kind and My_Kind are interfaces
OK.
> Here's mine ( 8/11 at compile-time, the remaining at runtime ):
> http://ideone.com/6WlFJ
Thank you. It's a nice implementation, and it doesn't use template magic at all, it's fully OOP :-) Your implementation shows that there are many different ways to solve this puzzle. I presume a bit shorter code is possible using templates (as in the 4th C++ version).
I have modified your code a little, I have added the missing 'override', I have added the required sequence ("there should be a way to handle a list of animals and the energy of each animal"), but there is no need for the name field because there is the classinfo.name, and I have shortened/simplified your (nice) test code a lot:
http://ideone.com/TQzyD
What's the purpose of using class names like "wCarrot" instead of "Carrot"?
I'd like to send (with full attribution) the D versions to the site/page owner (Pixel), maybe she/he's interested.
> I don't think it's possible to make it better than that in D without,
> as you say, for instance type states.
Typestate (a single word, it seems) is probably an useful thing, it's not the expression of an esoteric need. But to implement it I think you need flow analysis done by the compiler at compile-time. Among all the possible applications of flow analysis I think this can be one of the most useful :-)
Runtime tests are useful to avoid bugs, but it's nice to have a static type that's able to catch bugs at compile time.
>I guess it actually is doable at CT, by coding the whole puzzle within the confines of CTFE or TMP. I'm not going to, though.<
Better to not go there, because you are back to the Python version, but done at compile time :-)
Bye,
bearophile
More information about the Digitalmars-d
mailing list