The problem of animals and foods


no comments

The problem of animals and foods

this is a short post that is dealing with a classic riddle.

I was thinking on this riddle when I was trying to figure out a Scala feature. we are having (at Sela Group) a small Scala study group led by Israel Tabadi and while we were going over Scala’s abstract type (which is by the way a cool implementation) I was thinking about the .NET equivalent solution.

I will use the problem of "animals and foods" (taken from here) as an anchor’s point.

The problem: assuming an Animal with a method, Eat, which eats some food. and the riddle is, how can you restrict a Cow (which derived from an Animal), to eat nothing but Grass (at compile time). A Cow can’t eat an arbitrary food like Fish.

the idea is to restrict a Cow to a specialize type of food which is Grass.

the Scala version is available here.

now take your time and think of how can you solve it using .NET and Generics?

Scala, Generics, Abstract, Type, animals and foods, .NET

the solution is to assign the Cow’s type to Grass (as simple as it is, sometimes it can slip away).

the solution is present on the following snippet:

Code Snippet
  1. public abstract class Food { }
  2. public class Grass : Food { }
  3. public class Club : Grass { }
  4. public class DogFood : Food { }
  6. public abstract class Animal<T>
  7.     where T : Food
  8. {
  9.     public void eat(T food)
  10.     {
  11.         Console.WriteLine("{0} eat {1}", this.GetType().Name, food.GetType().Name);
  12.     }
  13. }
  15. public class Cow: Animal<Grass>
  16. {
  17. }
  19. public class Dog : Animal<DogFood>
  20. {
  21. }

the following snippet is the main method part:

Code Snippet
  1. var dogFood = new DogFood();
  2. var grass = new Grass();
  3. var club = new Club();
  5. var dog = new Dog();
  6. var cow = new Cow();
  9. // // not compiled

and the result is:

Scala, Generics, Abstract, Type, animals and foods, .NET

Shout it

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>