using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics.Contracts;
using System.Collections.ObjectModel;
namespace AutoDiff
{
///
/// Represents a custom n-ary function term. The user provides custom delegates
/// to evaluate and compute the gradient of the function.
///
public class NaryFunc : Term
{
private readonly Func eval;
private readonly Func diff;
///
/// Initializes a new instance of the class.
///
/// The evaluation method for the custom function.
/// The differentiation method for the custom function.
/// The argument terms for the n-ary function.
public NaryFunc(
Func eval,
Func diff,
IEnumerable terms)
{
this.eval = eval;
this.diff = diff;
this.Terms = Array.AsReadOnly(terms.ToArray());
}
///
/// Constructs a factory delegate that creates similary n-ary 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, NaryFunc> Factory(Func eval, Func diff)
{
Contract.Requires(eval != null);
Contract.Requires(diff != null);
Contract.Ensures(Contract.Result, NaryFunc>>() != null);
Func, NaryFunc> result = (terms) => new NaryFunc(eval, diff, terms);
return result;
}
///
/// Gets the evaluation delegate
///
public Func Eval { get { return eval; } }
///
/// Gets the differentiation delegate
///
public Func Diff { get { return diff; } }
///
/// Gets the arguments of this function
///
public ReadOnlyCollection Terms { get; private set; }
///
/// 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);
}
}
}