fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. typedef enum { CONSTANT, VARIABLE, OPERATOR } ExpressionType;
  5.  
  6. typedef struct {
  7. ExpressionType expressionType;
  8. void* expression;
  9. } Expression;
  10.  
  11. typedef struct {} Variable;
  12.  
  13. typedef struct {
  14. float value;
  15. } Constant;
  16.  
  17. typedef enum { PLUS, MINUS, MULTIPLY, DIVIDE } OperatorType;
  18.  
  19. typedef struct {
  20. OperatorType operatorType;
  21. Expression a;
  22. Expression b;
  23. } Operator;
  24.  
  25. typedef struct {
  26. Variable* variable;
  27. float value;
  28. } Binding;
  29.  
  30. typedef struct {
  31. Binding* bindings;
  32. size_t size;
  33. } Context;
  34.  
  35. float value(Variable* variable, Context context) {
  36. for (size_t i = 0; i < context.size; i++) {
  37. if (context.bindings[i].variable == variable) {
  38. return context.bindings[i].value;
  39. }
  40. }
  41.  
  42. return NAN;
  43. }
  44.  
  45. float result(Expression expression, Context context);
  46.  
  47. float resultOfOperator(Operator* op, Context context) {
  48. float aResult = result(op->a, context);
  49. float bResult = result(op->b, context);
  50.  
  51. switch (op->operatorType) {
  52. case PLUS:
  53. return aResult + bResult;
  54.  
  55. case MINUS:
  56. return aResult - bResult;
  57.  
  58. case MULTIPLY:
  59. return aResult * bResult;
  60.  
  61. case DIVIDE:
  62. return aResult / bResult;
  63. }
  64.  
  65. return NAN;
  66. }
  67.  
  68. float result(Expression expression, Context context) {
  69. switch (expression.expressionType) {
  70. case CONSTANT:
  71. return *(float*)expression.expression;
  72.  
  73. case VARIABLE:
  74. return value((Variable*)expression.expression, context);
  75.  
  76. case OPERATOR:
  77. return resultOfOperator((Operator*)expression.expression, context);
  78. }
  79.  
  80. return NAN;
  81. }
  82.  
  83. int main(void) {
  84. Variable a;
  85. Variable b;
  86. Variable c;
  87. Variable d;
  88.  
  89. Constant five = { 5.0 };
  90. Operator divide = { DIVIDE, { VARIABLE, &a }, { VARIABLE, &b } };
  91. Operator multiply = { MULTIPLY, { OPERATOR, &divide }, { VARIABLE, &c } };
  92. Operator minus = { MINUS, { OPERATOR, &multiply }, { VARIABLE, &d } };
  93. Operator plus = { PLUS, { OPERATOR, &minus }, { CONSTANT, &five } };
  94.  
  95. Expression expression = { OPERATOR, &plus };
  96.  
  97. Binding bindings[] = { { &a, 1.0 }, { &b, 2.0 }, { &c, 3.0 }, { &d, 4.0 } };
  98. Context context = { bindings, sizeof bindings };
  99. printf("%f", result(expression, context));
  100.  
  101. return 0;
  102. }
  103.  
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
2.500000