Back to index

texmacs  1.0.7.15
math_tree.hpp
Go to the documentation of this file.
00001 
00002 /******************************************************************************
00003 * MODULE     : math_tree.hpp
00004 * DESCRIPTION: trees as mathematical expressions
00005 * COPYRIGHT  : (C) 2006  Joris van der Hoeven
00006 *******************************************************************************
00007 * This software falls under the GNU general public license version 3 or later.
00008 * It comes WITHOUT ANY WARRANTY WHATSOEVER. For details, see the file LICENSE
00009 * in the root directory or <http://www.gnu.org/licenses/gpl-3.0.html>.
00010 ******************************************************************************/
00011 
00012 #ifndef MATH_TREE_H
00013 #define MATH_TREE_H
00014 #include "tree.hpp"
00015 
00016 tree neg (tree t1);
00017 tree add (tree t1, tree t2);
00018 tree sub (tree t1, tree t2);
00019 tree mul (tree t1, tree t2);
00020 tree div (tree t1, tree t2);
00021 
00022 tree sqrt (tree t);
00023 tree exp (tree t);
00024 tree log (tree t);
00025 tree pow (tree t1, tree t2);
00026 tree sin (tree t);
00027 tree cos (tree t);
00028 tree tan (tree t);
00029 
00030 string as_math_string (tree t);
00031 
00032 template<typename T> void
00033 parse (tree t, T& result) {
00034   FAILED ("unsupported type");
00035 }
00036 
00037 inline void
00038 parse (tree t, double& result) {
00039   ASSERT (is_double (t), "not a double");
00040   result= as_double (t);
00041 }
00042 
00043 template<typename T> T
00044 parse_as (tree t) {
00045   switch (L(t)) {
00046   case PLUS:
00047     return parse_as<T> (t[0]) + parse_as<T> (t[1]);
00048   case MINUS:
00049     if (N(t) == 1) return -parse_as<T> (t[0]);
00050     else return parse_as<T> (t[0]) - parse_as<T> (t[1]);
00051   case TIMES:
00052     return parse_as<T> (t[0]) * parse_as<T> (t[1]);
00053   case OVER:
00054     return parse_as<T> (t[0]) / parse_as<T> (t[1]);
00055   case MATH_SQRT:
00056     return sqrt (parse_as<T> (t[0]));
00057   case EXP:
00058     return exp (parse_as<T> (t[0]));
00059   case LOG:
00060     return log (parse_as<T> (t[0]));
00061   case POW:
00062     return pow (parse_as<T> (t[0]), parse_as<T> (t[1]));
00063   case COS:
00064     return cos (parse_as<T> (t[0]));
00065   case SIN:
00066     return sin (parse_as<T> (t[0]));
00067   case TAN:
00068     return tan (parse_as<T> (t[0]));
00069   default:
00070     {
00071       T result;
00072       parse (t, result);
00073       return result;
00074     }
00075   }
00076 }
00077 
00078 #endif // defined MATH_TREE_H