summaryrefslogtreecommitdiff
path: root/impl/Expression.hpp
blob: 3c84d300a15b92806418975df5c67086268e55d1 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#ifndef EXPRESSION_HPP
#define EXPRESSION_HPP

#include <iostream>
#include "VariableAssignment.hpp"
#include "Operator.hpp"

template<typename T>
struct Variable;
template<typename T>
struct MaxStrategy;

int ExpressionCount;

template<typename T>
struct Expression {
  Expression(Operator<T>* op, const std::vector< Expression<T>* >& args)
    : _operator(op), _arguments(args) { }
  virtual ~Expression() {
    if (!dynamic_cast<Variable<T>*>(_operator)) {
      delete _operator;
    }
  }
  virtual T operator() (const VariableAssignment<T>& assignment) const {
    return (*_operator)(_arguments, assignment);
  }

  template<typename Z>
  friend std::ostream& operator<<(std::ostream&, const Expression<Z>&);

  protected:
  Operator<T>* _operator;
  std::vector< Expression<T>* > _arguments;
};

template<typename T>
struct MaxExpression : public Expression<T> {
  MaxExpression(const std::vector< Expression<T>* >& args)
    : Expression<T>(new Maximum<T>, args) { }
  unsigned int id() const {
    return _id;
  }
  unsigned int id(unsigned int id) {
    return (_id = id);
  }
  Expression<T>* argument(unsigned int i) const {
    if (i >= Expression<T>::_arguments.size()) {
      throw "Error";
    }
    return Expression<T>::_arguments[i];
  }
  virtual T operator() (const VariableAssignment<T>& assignment) const {
    throw "error";
  }
  std::pair<T, unsigned int> bestStrategy(const VariableAssignment<T>& rho, const MaxStrategy<T>& strat) const {
    std::pair<T, unsigned int> best = std::pair<T, unsigned int>(-infinity<T>(), 0);
    for (unsigned int i = 0, size = Expression<T>::_arguments.size(); i < size; ++i) {
      T value = strat(*Expression<T>::_arguments[i], rho);
      if (best.first < value)
        best = std::pair<T, unsigned int>(value, i);
    }
    std::cerr << "Best strategy: (" << best.first << ", " << best.second << ")" << std::endl;
    return best;
  }
  private:
  unsigned int _id;
};

template<typename T>
std::ostream& operator<<(std::ostream& cout, const Expression<T>& expr) {
  if (expr._arguments.size() == 0) {
    cout << expr._operator->op_name;
  } else {
    cout << expr._operator->op_name << "(";
    for (typename std::vector<Expression<T>*>::const_iterator it = expr._arguments.begin();
         it != expr._arguments.end();
         ++it) {
      cout << (it == expr._arguments.begin() ? "" : ", ");
      cout << **it;
    }
    cout << ")";
  }
  return cout;
}

#include "Variable.hpp"
#include "MaxStrategy.hpp"

#endif