/* polymorphic linked lists with a mixture of generics and inheritance */ using System; // want: linked list with both natural and ad-hoc polymorphic functions public interface addable { T add(T other); } public class integer : addable { internal int x; // internal means public within same assembly public integer(int y) {x=y;} // constructor public integer add(integer other) { return new integer(other.x+x); } public override string ToString() { return ""+x; } } public class rational : addable { internal int n, d; // numerator and denominator public rational(int a, int b) { n=a; d=b; } public rational add(rational R) { int sd = R.d * d; int sn = n*R.d + R.n*d; return new rational(sn,sd); } public override string ToString() { return n+"/"+d; } } // polymorphic linked list class public class cell where T : addable { internal T car; internal cell cdr; public cell(T a, cell b) {car=a; cdr=b;} // constructor // naturally polymorphic function: public int length() { int ax = 0; for(cell i=this; i!=null; i=i.cdr) ax++; return ax; } // ad-hoc polymorphic function public T sum() { T ax = car; for(cell i=cdr; i!=null; i=i.cdr) ax = ax.add(i.car); return ax; } }// cell // compile to .dll with csc /t:library polylists.cs