Skip to content

Instantly share code, notes, and snippets.

@jweinst1
Created December 7, 2016 00:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jweinst1/fb8e03e618de63825d3a9e40a47cfdb0 to your computer and use it in GitHub Desktop.
Save jweinst1/fb8e03e618de63825d3a9e40a47cfdb0 to your computer and use it in GitHub Desktop.
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)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment