Browse Source

Implement some bonus marks

T. Meissner 7 months ago
parent
commit
7affd2b284
1 changed files with 26 additions and 3 deletions
  1. 26
    3
      chapter_07/lispy.c

+ 26
- 3
chapter_07/lispy.c View File

@@ -31,12 +31,34 @@ void add_history(char* unused) {}
31 31
 #endif
32 32
 
33 33
 
34
+long min(long x, long y) {
35
+    if (x <= y) {
36
+        return x;
37
+    } else {
38
+        return y;
39
+    }
40
+}
41
+
42
+
43
+long max(long x, long y) {
44
+    if (x >= y) {
45
+        return x;
46
+    } else {
47
+        return y;
48
+    }
49
+}
50
+
51
+
34 52
 /* Use operator string to see which operation to perform */
35 53
 long eval_op(long x, char* op, long y) {
36 54
     if (strcmp(op, "+") == 0) {return x + y;}
37 55
     if (strcmp(op, "-") == 0) {return x - y;}
38 56
     if (strcmp(op, "*") == 0) {return x * y;}
39 57
     if (strcmp(op, "/") == 0) {return x / y;}
58
+    if (strcmp(op, "%") == 0) {return x % y;}
59
+    if (strcmp(op, "^") == 0) {return pow(x, y);}
60
+    if (strcmp(op, "min") == 0) {return min(x, y);}
61
+    if (strcmp(op, "max") == 0) {return max(x, y);}
40 62
     return 0;
41 63
 }
42 64
 
@@ -65,8 +87,8 @@ long eval(mpc_ast_t* t) {
65 87
 }
66 88
 
67 89
 
68
-int main(int argc, char const *argv[])
69
-{
90
+int main(int argc, char const *argv[]) {
91
+
70 92
     /* Create some parsers */
71 93
     mpc_parser_t* Number = mpc_new("number");
72 94
     mpc_parser_t* Operator = mpc_new("operator");
@@ -77,7 +99,8 @@ int main(int argc, char const *argv[])
77 99
     mpca_lang(MPCA_LANG_DEFAULT,
78 100
         "                                                       \
79 101
             number   : /-?[0-9]+/ ;                             \
80
-            operator : '+' | '-' | '*' | '/' ;                  \
102
+            operator : '+' | '-' | '*' | '/' | '%' | '^' |      \
103
+            \"min\" | \"max\" ;                                 \
81 104
             expr     : <number> | '(' <operator> <expr>+ ')' ;  \
82 105
             lispy    : /^/ <operator> <expr>+ /$/ ;             \
83 106
         ",