
/*
 * Classi e oggetti in Java: Liste di interi
 *
 * Ultimo aggiornamento: 28/03/12
 *
 *
 * Tipo di dato:  IntList
 *
 * Protocollo:                                                   ;; Scheme:
 *
 *   IntList.NULL                [costante lista vuota]          ;;   null
 *
 *   IntList.listNull( lst )     :  IntList  -->  boolean        ;;   null?
 *
 *   IntList.listCar( lst )      :  IntList  -->  int            ;;   car
 *
 *   IntList.listCdr( lst )      :  IntList  -->  int            ;;   cdr
 *
 *   IntList.listCons( n, lst )  :  int x IntList  -->  IntList  ;;   cons
 *
 */


public class IntList {


  public static final IntList NULL = new IntList();
  
  
  private final int head;
  private final IntList tail;
  
  
  private IntList() {
  
    head = 0;
    tail = null;
  }
  
  
  private IntList( int x, IntList lst ) {
  
    head = x;
    tail = lst;
  }
  
  
  public String toString() {
  
    IntList lst = this;
    String listRep = "(";
    
    if ( lst != NULL ) {
    
      listRep = listRep + lst.head;
      lst = lst.tail;
    }
    while ( lst != NULL ) {
    
      listRep = listRep + " " + lst.head;
      lst = lst.tail;
    }
    return ( listRep + ")" );
  }
  
  
  public static boolean listNull( IntList lst ) {
  
    return ( lst == NULL );
  }
  
  
  public static IntList listCons( int x, IntList lst ) {
  
    return  new IntList( x, lst );
  }
  
  
  public static int listCar( IntList lst ) {
  
    if ( lst != NULL ) {
    
      return  lst.head;
    
    } else {
      throw new RuntimeException( "car of empty list" );
    }
  }
  
  
  public static IntList listCdr( IntList lst ) {
  
    if ( lst != NULL ) {
    
      return  lst.tail;
    
    } else {
      throw new RuntimeException( "cdr of empty list" );
    }
  }

}  // class IntList

