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

From: Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
Date: Sat Feb 25 20:06:16 EST 2006

> But you can also get away with no continuations and no handlers -- you
> only need a unique identifiable value:
>   (define hash-contains?
>     (let ([secret (list 'whatever)])
>       (lambda (t x)
>         (not (eq? secret (hash-table-get t x (lambda () secret)))))))

I wanted to polish this up a little more, and came up with:

(module hash-contains mzscheme
  (require (lib "contract.ss"))

  (provide/contract (hash-contains? (-> hash-table? any/c boolean?)))

  ;; hash-contains?: hash-table any -> boolean
  ;; Returns true if the table contains a mapping for the key.
  (define hash-contains?
    (let* ((secret (list 'whatever))
           (fail-thunk (lambda () secret)))
      (lambda (table key)
        (not (eq? secret (hash-table-get table key fail-thunk)))))))

Would it be considered a bit overkill to put contracts around it?

Posted on the users mailing list.