using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics.Contracts; namespace AutoDiff { /// /// Represents a custom unary function term. The user provides custom delegates /// to evaluate and compute the derivative (differentiate) the function. /// public class UnaryFunc : Term { private readonly Func eval; private readonly Func diff; private readonly Term argument; /// /// Initializes a new instance of the class. /// /// The evaluation method for the custom function. /// The differentiation method for the custom function. /// The argument term for the unary function public UnaryFunc(Func eval, Func diff, Term argument) { Contract.Requires(eval != null); Contract.Requires(diff != null); Contract.Requires(argument != null); Contract.Ensures(Eval == eval); Contract.Ensures(Diff == diff); Contract.Ensures(Argument == argument); this.eval = eval; this.diff = diff; this.argument = argument; } /// /// Constructs a factory delegate that creates similar unary functions for different terms. /// /// The evaluation method for the custom function. /// The differentiation method for the custom function. /// The described factory delegate public static Func Factory(Func eval, Func diff) { Contract.Requires(eval != null); Contract.Requires(diff != null); Contract.Ensures(Contract.Result>() != null); Func result = term => new UnaryFunc(eval, diff, term); return result; } /// /// Gets the evaluation delegate. /// public Func Eval { get { return eval; } } /// /// Gets the differentiation delegate. /// public Func Diff { get { return diff; } } /// /// Gets the function's argument term /// public Term Argument { get { return argument; } } /// /// Accepts a term visitor /// /// The term visitor to accept public override void Accept(ITermVisitor visitor) { visitor.Visit(this); } /// /// Accepts a term visitor with a generic result /// /// The type of the result from the visitor's function /// The visitor to accept /// /// The result from the visitor's visit function. /// public override TResult Accept(ITermVisitor visitor) { return visitor.Visit(this); } } }