Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Interface for dictionaries
- *
- * 15-122 Principles of Imperative Computation
- */
- #use <string>
- #use <conio>
- /* Interface to dictionaries (leave this alone) */
- // typedef ______* dict_t;
- typedef struct dict_header* dict_t;
- // Data structure invariant to ensure safety
- bool is_dict(dict_t D);
- // Returns NULL if the input array has the same operator twice
- dict_t dict_new(string[] A, int n)
- /*@requires \length(A) == n; @*/
- /*@requires is_infix_array(A, n); @*/
- /*@ensures is_dict(\result);@*/;
- // Returns -1 if no definition is found
- int dict_lookup(dict_t D, string oper)
- /*@requires is_dict(D); @*/
- /*@ensures \result >= -1; @*/ ;
- //implementations for dictionaries
- typedef struct dict_header dict;
- struct dict_header {
- int[] precOp;
- int len;
- };
- bool is_dict(dict_t D) {
- //@assert(\length(D->precOP)==D->len);
- return D != NULL && D->len > 0;
- }
- dict_t dict_new(string[] A, int n)
- /*@ensures ((\result == NULL)
- || (is_dict(\result))
- && (\length(\result->precOp)==\result->len));@*/
- {
- int[] opPrec = parse_ints("-1 -1 -1 -1 -1", 10);
- string[] operations = parse_tokens("** * / + -");
- for(int h=0; h<5; h++) {
- for(int i=0; i<n; i++) {
- string[] opArr = parse_tokens(A[i]);
- for(int j=0; j<num_tokens(A[i]); j++) {
- if(string_equal(operations[h],opArr[j])) {
- if(opPrec[h]!=-1) return NULL;
- opPrec[h]=i;
- }
- }
- }
- }
- dict* d = alloc(dict);
- d->precOp=opPrec;
- d->len = n;
- return d;
- }
- int dict_lookup(dict_t D, string oper)
- //@requires is_dict(D);
- //@ensures is_dict(D);
- {
- string[] ops = parse_tokens("** * / + -");
- for(int i=0; i<5; i++) {
- if(string_equal(ops[i],oper)) return D->precOp[i];
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement