[plt-scheme] Checking to see if a key is present in a hash table

From: Gregory Woodhouse (gregory.woodhouse at sbcglobal.net)
Date: Sat Feb 25 18:28:10 EST 2006

There doesn't seem to be a simple way to do it. The problem is that  
an error is signaled if the key is not present, so if I use hash- 
table-get, I need to deal with it somehow. The following code does  
not work

  (define (bound? t s)
     (lambda (k)
       (let ((x
              (hash-table-get t s (lambda () k #f))))
         k #t))))
(define t (make-hash-table))
(hash-table-put! t 'x #f)
(bound? t 'x)
(bound? t 'y)

I get #t in both cases. That seems odd because if the failure thunk  
is ever invoked, I'd expect bound? to return #f immediately.

Now, the odd (to me, anyway) thing is that I use the following code  
to (say) take the symbol '+ as input and return a function. It works  
just fine

;;get builtin (or #<void>)
;;symbol -> procedure + void
(define get-builtin
   (let ((t (make-hash-table)))
     (hash-table-put! t '+ (lambda (x y) (+ x y)))
     (hash-table-put! t '- (lambda (x y) (- x y)))
     (hash-table-put! t '* (lambda (x y) (* x y)))
     (hash-table-put! t '/ (lambda (x y) (unless (zero? y) (/ x y))))
     (hash-table-put! t 'and (lambda (x y) (and x y)))
     (hash-table-put! t 'or (lambda (x y) (or x y)))
     (hash-table-put! t 'not (lambda (x) (not x)))
     (hash-table-put! t '< (lambda (x y) (< x y)))
     (hash-table-put! t '> (lambda (x y) (> x y)))
     (hash-table-put! t '= (lambda (x y) (= x y)))
     (lambda (op)
        (lambda (k)
          (hash-table-get t op (lambda () k (void))))))))

What's the difference?

Gregory Woodhouse
gregory.woodhouse at sbcglobal.net

"Doubt may be uncomfortable,
but certainty is absurd."  --Voltaire

Posted on the users mailing list.