SimpleMath.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. namespace ExpressionLib.Contexts
  7. {
  8. public class SimpleMath : IContext<double>
  9. {
  10. public int NumParams(string oprtr)
  11. {
  12. if (oprtr == "+" || oprtr == "-" || oprtr == "*" || oprtr == "/" || oprtr == "^" || oprtr == "(max)")
  13. return 2;
  14. else if (oprtr == "(sqrt)")
  15. return 1;
  16. else
  17. return 0;
  18. }
  19. public double EvalOperator(string oprtr, List<double> values)
  20. {
  21. if (oprtr == "+")
  22. return values[0] + values[1];
  23. else if (oprtr == "-")
  24. return values[0] - values[1];
  25. else if (oprtr == "*")
  26. return values[0] * values[1];
  27. else if (oprtr == "/")
  28. return values[0] / values[1];
  29. else if (oprtr == "^")
  30. return Math.Pow(values[0], values[1]);
  31. else if (oprtr == "(sqrt)")
  32. return Math.Sqrt(values[0]);
  33. else if (oprtr == "(max)")
  34. return Math.Max(values[0], values[1]);
  35. else
  36. throw new ParsingException("Unknown operator '" + oprtr + "' detected!");
  37. }
  38. public bool IsValue(string c)
  39. {
  40. double r;
  41. return IsValue(c, out r);
  42. }
  43. public bool IsValue(string c, out double r)
  44. {
  45. return double.TryParse(c.Replace('.', ','), out r);
  46. }
  47. public bool IsOperator(string c)
  48. {
  49. return
  50. (
  51. c == "^" || c == "*" || c == "/" || c == "+" || c == "-"
  52. );
  53. }
  54. public int PriorityOf(string c)
  55. {
  56. if (c == "(sqrt)" || c == "(max)")
  57. return 4;
  58. else if (c == "^")
  59. return 3;
  60. else if (c == "*" || c == "/")
  61. return 2;
  62. else if (c == "+" || c == "-")
  63. return 1;
  64. else return 0;
  65. }
  66. public Associativity AssociativityOf(string c)
  67. {
  68. if (c == "^")
  69. return Associativity.Right;
  70. else
  71. return Associativity.Left;
  72. }
  73. }
  74. }