View Javadoc
1   package calculator.functions;
2   
3   import calculator.Expression;
4   import calculator.IllegalConstruction;
5   import calculator.Notation;
6   import calculator.atoms.Complex;
7   import calculator.atoms.IntegerAtom;
8   import calculator.atoms.Rationnal;
9   import calculator.atoms.Real;
10  import visitor.Printer;
11  import visitor.Visitor;
12  
13  /**
14   * UnaryFunction is an abstract class that represents unary arithmetic
15   * operations,
16   * which are a special kind of Expressions, just like binary operations are.
17   */
18  public abstract class UnaryFunction implements Expression {
19  	/**
20  	 * The expression passed as an argument to the arithmetic operation
21  	 */
22  	public Expression arg;
23  
24  	/**
25  	 * The character/string used to represent the arithmetic operation (e.g. "cos")
26  	 */
27  	protected String symbol;
28  
29  	/**
30  	 * To construct a unary operation with an expression as argument
31  	 *
32  	 * @param arg The expression passed as argument to the arithmetic operation
33  	 * @throws IllegalConstruction Exception thrown if a null argument is passed
34  	 */
35  	protected /* constructor */ UnaryFunction(Expression arg)
36  			throws IllegalConstruction {
37  		if (arg == null) {
38  			throw new IllegalConstruction();
39  		} else {
40  			this.arg = arg;
41  		}
42  	}
43  
44  	/**
45  	 * getter method to return the argument of an arithmetic operation.
46  	 *
47  	 * @return The argument of the arithmetic operation.
48  	 */
49  	public Expression getArg() {
50  		return arg;
51  	}
52  
53  	/**
54  	 * getter method to return the symbol of the arithmetic operation.
55  	 *
56  	 * @return The symbol of the arithmetic operation.
57  	 */
58  	public String getSymbol() {
59  		return symbol;
60  	}
61  
62  	public abstract Real op(Real r);
63  
64  	public abstract Complex op(Complex c);
65  
66  	public abstract IntegerAtom op(IntegerAtom i);
67  
68  	public abstract Rationnal op(Rationnal q);
69  
70  	/**
71  	 * Accept method to implement the visitor design pattern to traverse arithmetic
72  	 * expressions.
73  	 *
74  	 * @param v The visitor object
75  	 */
76  	public void accept(Visitor v) {
77  		v.visit(this);
78  	}
79  
80  	@Override
81  	public final String toString() {
82  		Printer p = new Printer();
83  		this.accept(p);
84  		return p.getResult();
85  	}
86  
87  	public final String toString(Notation n) {
88  		Printer p = new Printer(n);
89  		this.accept(p);
90  		return p.getResult();
91  	}
92  
93  	@Override
94  	public boolean equals(Object o) {
95  		if (o == null)
96  			return false;
97  		if (this == o)
98  			return true;
99  		if (getClass() != o.getClass())
100 			return false;
101 		UnaryFunction other = (UnaryFunction) o;
102 		return this.arg.equals(other.getArg());
103 	}
104 
105 	@Override
106 	public int hashCode() {
107 		return arg.hashCode();
108 	}
109 }