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

From: Ryan Culpepper (ryan_sml at yahoo.com)
Date: Sat Feb 25 18:43:31 EST 2006

--- Gregory Woodhouse <gregory.woodhouse at sbcglobal.net> 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))))

You aren't actually applying the continuation in the failure thunk
(or in the second, superfluous occurrence, either). Try this:

(define (bound? t s)
  (call/cc
    (lambda (k)
      (hash-table-get t s (lambda () (k #f))
      #t)))

You should also read about call/ec. It's more efficient than call/cc
when you can use it, such as in cases like this.

Ryan


> (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.