making dictionary - add parentheses to function name

656 views Asked by At

I have a scheme project with which I want to make a dictionary without using 'dict' function. IO example:

 (define d (make-dictionary)) ;; creates an empty dictionary
 (define d1 (d (cons "a" 1))) ;;d1 is d+("a" 1), d not changing
 (d1 "a") ;; = 1
 (define d2 (d1 (cons "b" 15))) ;;d2 is d1+("b" 15), d1 not changing
 (d2 "b") ;; = 15
 (d2 "a") ;; = 1

I simply do not understand how I can get make-dictionary with parenthesis as an argument, it always returns a procedure rather than types the answer.

(define (make-dictionary)
'())

(define ( ( (make-dictionary) pairs) )  ;;trying to get it with parenthesis
   append make-dictionary (cons pairs '()))

I know I've asking a lot of questions the past couple of days, but I am new to scheme and I am doing my best to learn it, but I'm running out of time.. HELP?

2

There are 2 answers

0
Óscar López On

I guess you're trying to implement an association list. Sadly, what you're proposing to do with parentheses doesn't make sense, at all. A more sensible approach would be to have separate procedures for adding and retrieving key/value pairs:

(define (make-dictionary)
  '())

(define (add-dictionary dict pair)
  (cons pair dict))

(define (get-dictionary dict key)
  (let ((pair (assoc key dict))) ; use the built-in `assoc` procedure!
    (if pair (cdr pair) #f)))

Now, we'd use it like this:

(define d (make-dictionary))
(define d1 (add-dictionary d (cons "a" 1)))
(get-dictionary d1 "a") ;; = 1
(define d2 (add-dictionary d1 (cons "b" 15)))
(get-dictionary d2 "a") ;; = 1
(get-dictionary d2 "b") ;; = 15
(get-dictionary d2 "c") ;; = #f
0
Simar Chawla On

From what I understand, you're having difficulty making a dictionary where the value is a list. I think a more simpler way to approach it would be to make an association list and use a lookup function.

So an Al would look like

(define my-al (list (list key (list value1a value1b))
                    (list key (list value2a value 2b))))

lookup-al: Key AL -> value

(define (lookup-al k alst)
   (cond [(empty? alst) false]
         [(equal? k (first (first alst))) (second (first alst))]
         [else (lookup-al k (rest alst))]))