Statalist


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

st: Distinguishing subclasses in Mata


From   "Joseph Coveney" <[email protected]>
To   <[email protected]>
Subject   st: Distinguishing subclasses in Mata
Date   Thu, 3 Sep 2009 01:32:02 +0900

What's the recommended way for a function to distinguish subclasses in Mata?
Mata doesn't yet appear to have a specialization of the -eltype()- function that
would return class type, or subclass and (parent) class type.  

I've stumbled through a workaround (shown below) that has each subclass set a
public member variable to identify itself, but there ought to be a better way .
. .

Joseph Coveney

(The example is adapted from the zoological scenario by Derek Wallace in
http://darksinister.com/fusion/software/research/ppt/MultipleMethodDispatch.ppt
)

version 11.0
mata
mata set matastrict on

class Food {
	public:
		string scalar food_type
	private:
		void new()
	protected:
		virtual void WhoAmI()
}
void function Food::new() {
	WhoAmI()
}
void Food::WhoAmI() {
	food_type = "General"
}

class FishFood extends Food {
	private:
		virtual void WhoAmI()
}
void function FishFood::WhoAmI() {
	food_type = "Fish"
}

class DoughnutsFood extends Food {
	private:
		virtual void WhoAmI()
}
void function DoughnutsFood::WhoAmI() {
	food_type = "Doughnuts"
}

class Animal {
	protected:
		void feed()
}
void function Animal::feed(class Food scalar food) {
	// Interface--do nothing
}

class PolarBear extends Animal {
	public:
		void feed()
}
void function PolarBear::feed(class Food scalar food) {
	// Eating Food
	::printf("mmm...\n")
}

class Penguin extends Animal {
	public:
		void feed()
}
void Penguin::feed(class Food scalar food) {
	// Eating Food
	if (food.food_type == "General") {
		::printf("gulp\n")
	}
	// Eating Fish
	else if (food.food_type == "Fish") {
		::printf("yum\n")
	}
	// Eating Doughnuts
	else if (food.food_type == "Doughnuts") {
		::printf("ick\n")
	}
	else {
		::printf("food?\n")
	}
}

void function Testem() {

	class Food scalar food
	class FishFood scalar fish
	class DoughnutsFood scalar doughnut

	class PolarBear scalar bear
	class Penguin scalar penguin

	bear.feed(food)
	bear.feed(fish)
	bear.feed(doughnut)

	penguin.feed(food)
	penguin.feed(fish)
	penguin.feed(doughnut)

}
Testem()

end
exit


*
*   For searches and help try:
*   http://www.stata.com/help.cgi?search
*   http://www.stata.com/support/statalist/faq
*   http://www.ats.ucla.edu/stat/stata/



© Copyright 1996–2024 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index