/*********************************************** * CS2510 Fall 2011 * Lecture #15.2 * Parameterized Lists ***********************************************/ /** Goal: Create generic lists and a more generic map function */ import tester.*; // Information about our Puppy class Puppy { String name; String furcolor; String superpower; Puppy(String name, String furcolor, String superpower) { this.name = name; this.furcolor = furcolor; this.superpower = superpower; } } //Information about our Unicorn class Unicorn { String name; String furcolor; String superpower; Unicorn(String name, String furcolor, String superpower) { this.name = name; this.furcolor = furcolor; this.superpower = superpower; } } // A generic list interface IList extends Traverse{ // Applies the mapper function to all elements in the list to create a new type of list public IList transformAll(IMap mapper); } class MtList implements IList { // Are we at an empty element public boolean emptyP() { return true; } // Get the current element public T getFirst() { throw new RuntimeException("Got no elements."); } // Get the next position in the list public Traverse getRest() { throw new RuntimeException("Nowhere to go but home."); } // Returns a newly typed empty public IList transformAll(IMap mapper) { return new MtList(); } } class ConsList implements IList { T first; IList rest; ConsList(T first, IList rest) { this.first = first; this.rest = rest; } // Are we at an empty element public boolean emptyP() { return false; } // Get the current element public T getFirst() { return first; } // Get the next position in the list public Traverse getRest() { return rest; } // Applies the mapper to the current element and recurses public IList transformAll(IMap mapper) { return new ConsList(mapper.apply(first),rest.transformAll(mapper)); } } // Represents something that can be traversed interface Traverse { // Are we at an empty element public boolean emptyP(); // Get the current element public X getFirst(); // Get the next position in the list public Traverse getRest(); } interface IMap { // The function to apply for our map public Y apply(X x); } class PtoUMap implements IMap{ // Turn our puppy into a unicorn public Unicorn apply(Puppy p) { return new Unicorn(p.name,"Silver",p.superpower); } } class GenericListExamples { Puppy sophie = new Puppy("Sophie", "purple", "invisibility"); Puppy hercules = new Puppy("Hercules", "golden", "supercanine smell"); IList classdogs = new ConsList(sophie,new ConsList(hercules,new MtList())); IMap ptou = new PtoUMap(); IList classunicorns = classdogs.transformAll(ptou); }