> I've run into this multiple times as well, and would like someone (maybe me)
> to write a package (maybe named `sugar-contract`) that provides this.
It would be neat, at least, to be able to use same double ellipsis
notation as in defproc and as we read in the documentation:
(-> hash? any/c any/c ... ... hash?)
(Note: This would allow zero key/value pairs. But actually I think
it's desirable for (safe-hash-aet h) simply to return h.)
----
p.s.
I don't think it's _terrible_ to raise an error manually for something
like this. You don't get the nice blame, is the drawback. For example:
#lang racket/base
(require racket/contract
racket/match)
; (-> hash? any/c any/c ... ... hash?)
(define (safe-hash-set h . _kvs)
(let loop ([h h] [kvs _kvs])
(match kvs
[(list) h]
[(list* k v kvs) (loop (if (immutable? h)
(hash-set h k v)
(begin (hash-set! h k v) h))
kvs)]
[(list v) (error
'safe-hash-set
"expected sequence of key value ... ... but got:~n~v"
_kvs)])))
(define imm-hash (hash 'a 1))
(define mut-hash (make-hash '((a . 1))))
(module+ test
(require rackunit)
(check-equal? (safe-hash-set imm-hash 'x 2)
(hash 'a 1 'x 2))
(check-equal? (safe-hash-set imm-hash 'x 2 'y 7)
(hash 'a 1 'x 2 'y 7))
(check-equal? (safe-hash-set mut-hash 'x 2)
(make-hash '((a . 1) (x . 2))))
(check-equal? (safe-hash-set mut-hash 'x 2 'y 7)
(make-hash '((y . 7) (a . 1) (x . 2))))
(check-exn exn:fail?
(λ ()
(safe-hash-set (hash) 'x 2 'y))
"safe-hash-set: expected sequence of key value ...
... but got:\n'(x 2 y)"))
--
You received this message because you are subscribed to the Google Groups
"Racket Users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.