jweinst1
12/7/2016 - 12:15 AM

implements a dictionary in scheme

implements a dictionary in scheme

;Implementing a Dictionary in Scheme;
;keys must be numbers;

;Constructor Method;
(define (dict k v)
  (list (cons k v))
)

;Takes a Scheme list and makes it into a dictionary;
;(lstdict (list 3 4 5 6)) => ((3 . 4) (4 . 5) (5 . 6));
(define (lstdict lst)
  (cond
    ((null? (cdr lst)) ())
    (else 
          (cons (cons (car lst) (cadr lst)) (lstdict (cdr lst))))
  )
)

;Get Method;
;Returns nothing if key not in dictionary;
(define (get d key)
  (cond
    ((null? d) #f)
    ((= key (caar d)) (cdar d))
    (else (get (cdr d) key))
  )
)

;in method;
;checks if a key exists in the dictionary;
(define (contains d key)
  (cond
    ((null? d) #f)
    ((= key (caar d)) #t)
    (else (get (cdr d) key))
  )
)
  

;Adds a Key Value Pair;
;(add ccc 8 90) => ((8 . 90) (3 . 6));
(define (add d k v)
  (cons (cons k v) d)
)