[plt-scheme] hash-has-key?

From: Jay McCarthy (jay.mccarthy at gmail.com)
Date: Fri Mar 27 19:38:00 EDT 2009

You can also capture the exception that hash-ref will raise:

#lang scheme
(define (hash-has-key? hash key)
  (with-handlers ([exn:fail? (lambda (x) #f)])
    (hash-ref hash key)

(define ht (make-immutable-hash (list (cons 'a 1))))
(hash-has-key? ht 'a)
(hash-has-key? ht 'b)

(That should be roughly equivalent to Carl's suggestion of let/ec)


On Fri, Mar 27, 2009 at 5:14 PM, Henk Boom <henk at henk.ca> wrote:
> Hi, I was looking for a way to test whether or not a hash table has a
> mapping for a given key. I was surprised not to find anything in the
> docs, but thought of two ways to implement this:
> (define (hash-has-key? hash key)
>  (let/cc return
>    (hash-ref hash key (lambda () (return #f)))
>    #t))
> (define hash-has-key?
>  (let ((distinct-value (gensym)))
>    (lambda (hash key)
>      (not (eq? distinct-value (hash-ref hash key distinct-value))))))
> Both of these seem like roundabout approaches, is there a built-in way
> to do this? If not, is one of these better than the other?
>    Henk
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

Jay McCarthy <jay at cs.byu.edu>
Assistant Professor / Brigham Young University

"The glory of God is Intelligence" - D&C 93

Posted on the users mailing list.