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

From: Dave Herman (dherman at ccs.neu.edu)
Date: Sun Feb 26 00:31:17 EST 2006

It's easier than you're making it out to be. Don't bother with 
continuations. Just use an exception handler.

(define (bound? t s)
   (with-handlers ([exn? (lambda (exn) #f)])
     (hash-table-get t s)
     #t))

Dave

Gregory Woodhouse wrote:
> 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)
>    (call/cc
>     (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)
>       (call/cc
>        (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
> 
> 
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme



Posted on the users mailing list.