Adding hash table functions to ASL

This commit is contained in:
Jay McCarthy 2010-07-15 15:45:23 -06:00
parent caca804615
commit d17deb5fef
3 changed files with 54 additions and 1 deletions

View File

@ -106,4 +106,22 @@
(set-box! (box any -> void)
"to update a box")
(box? (any -> boolean)
"to determine if a value is a box"))))
"to determine if a value is a box"))
("Hash Tables"
((advanced-make-hash make-hash) ((listof (list X Y)) -> (hash X Y))
"to construct a hash table from a list of associations")
(hash-set! ((hash X Y) X Y -> void)
"to update a hash table with a new association")
((advanced-hash-ref hash-ref) ((hash X Y) X -> Y)
"to extract the value associated with a key from a hash table")
(hash-has-key? ((hash X Y) X -> boolean)
"to determine if a key is associated with a value in a hash table")
(hash-remove! ((hash X Y) X -> void)
"to remove an association from a hash table")
(hash-map ((hash X Y) (X Y -> A) -> (listof A))
"to construct a new list by applying a function to each association of a hash table")
(hash-for-each ((hash X Y) (X Y -> any) -> void)
"to apply a function to each association of a hash table for effect only")
(hash? (any -> boolean)
"to determine if value is a hash table"))))

View File

@ -345,6 +345,14 @@ namespace.
(check-last/cycle 'append x)
(apply append x)))
(define-teach advanced hash-ref
(lambda (h k)
(hash-ref h k)))
(define-teach advanced make-hash
(lambda (a)
(make-hash (map (lambda (l) (cons (first l) (second l))) a))))
(provide
false?
beginner-not
@ -375,6 +383,8 @@ namespace.
advanced-cons
advanced-list*
advanced-append
advanced-hash-ref
advanced-make-hash
cyclic-list?)
;; -----------------------------------------------------------------------------

View File

@ -208,6 +208,31 @@
(htdp-test #t 'equal~? (equal~? (shared ([x (cons 10 x)]) x) (shared ([x (cons 10.02 x)]) x) 0.1))
(htdp-test #f 'equal~? (equal~? (shared ([x (cons 10 x)]) x) (shared ([x (cons 10.2 x)]) x) 0.1))
(htdp-test 42 'hash-for-each
(local [(define x 0)
(define (f k v) (set! x 42))]
(begin (hash-for-each (make-hash (list (list 1 2))) f)
x)))
(htdp-test #t 'hash-has-key? (hash-has-key? (make-hash (list (list 1 2))) 1))
(htdp-test #f 'hash-has-key? (hash-has-key? (make-hash (list (list 1 2))) 2))
(htdp-test (list #f #f) 'hash-map
(hash-map (make-hash (list (list 1 #t) (list 2 #t)))
(lambda (k v) (not v))))
(htdp-test 1 'hash-ref (hash-ref (make-hash (list (list 'a 1))) 'a))
(htdp-test (list #t #f) 'hash-remove!
(local [(define ht (make-hash (list (list 'a 1))))]
(list (hash-has-key? ht 'a)
(begin (hash-remove! ht 'a)
(hash-has-key? ht 'a)))))
(htdp-test 2 'hash-set!
(local [(define ht (make-hash (list (list 'a 1))))]
(begin (hash-set! ht 'a 2)
(hash-ref ht 'a))))
(htdp-test #t 'hash?
(hash? (make-hash (list (list 'a 1)))))
(htdp-test #f 'hash?
(hash? 1))
;; Simulate set! in the repl
(module my-advanced-module (lib "htdp-advanced.rkt" "lang")
(define x 10)