3.11 Map
azelf内置Map,取代racket的hash。 所谓HashMap,相当于JavasScript中的Object、TypeScript中的Recrod。
3.11.1 Map定义
syntax
(Map pattern ...)
3.11.2 Map构造函数
> (hashmap 1 2 3 4) (Map '(1 . 2) '(3 . 4))
> (hashmap (array 1) 1 (array 2) 2) (Map '(#<Array: 1> . 1) '(#<Array: 2> . 2))
> (list->map '((1 2) (3 4))) (Map '(1 2) '(3 4))
procedure
(map-singleton key value) → (Map/c k v)
key : k value : v
> (map-singleton 1 2) (Map '(1 . 2))
3.11.3 Map更新
procedure
(map-insert key value hash) → (Map/c k v)
key : k value : v hash : (Map/c k v)
> (map-insert 2 10 (map-singleton 1 1)) (Map '(1 . 1) '(2 . 10))
> (map-insert 1 10 (map-singleton 1 1)) (Map '(1 . 10))
procedure
(map-remove key hash) → (Map/c k v)
key : k hash : (Map/c k v)
> (map-remove 2 (map-singleton 1 1)) (Map '(1 . 1))
> (map-remove 1 (map-singleton 1 1)) (Map)
procedure
(map-adjust f k hash) → (Map/c k v)
f : (-> v v) k : Ord? hash : (Map/c k v)
> (define (++ s) (string-append "new" s)) > (map-adjust ++ 5 (hashmap 5 "a" 3 "b")) (Map '(3 . "b") '(5 . "newa"))
> (map-adjust ++ 7 (hashmap 5 "a" 3 "b")) (Map '(3 . "b") '(5 . "a"))
> (map-adjust ++ 7 map-empty) (Map)
> (define (madd1 x) (if (= x "a") (Just "new a") nothing)) > (map-update madd1 5 (hashmap 5 "a" 3 "b")) (Map '(3 . "b") '(5 . "new a"))
> (map-update madd1 7 (hashmap 5 "a" 3 "b")) (Map '(3 . "b") '(5 . "a"))
> (map-update madd1 3 (hashmap 5 "a" 3 "b")) (Map '(5 . "a"))
> (define h (hashmap 1 2 3 4)) > (define (remove-key v) nothing) > (define (update-key v) (Just 10)) > (map-alter remove-key 3 h) (Map '(1 . 2))
> (map-alter update-key 1 h) (Map '(1 . 10) '(3 . 4))
3.11.4 Map取值
> (map-key? 1 map-empty) #f
> (map-key? 2 (map-singleton 2 1)) #t
procedure
hash : (Map/c k v) (map-values hash) → (Array/c v) hash : (Map/c k v)
procedure
(map-size hash) → exact-nonnegative-integer?
hash : Map?
3.11.5 Map转换
procedure
(map-filter f hash) → (Map/c k v)
f : (-> v boolean?) hash : (Map/c k v) (map-filter-key f hash) → (Map/c k v) f : (-> k boolean?) hash : (Map/c k v)
> (map-filter-key odd? (hashmap 1 3 2 2 4 5 7 6)) (Map '(1 . 3) '(7 . 6))
> (map-filter-key even? (hashmap 1 3 2 2 4 5 7 6)) (Map '(2 . 2) '(4 . 5))
3.11.6 Map解构
procedure
(map-fold f acc h) → a
f : (-> a k v a) acc : a h : (Map/c k v) (map-fold/key f acc h) → a f : (-> a k a) acc : a h : (Map/c k v) (map-fold/value f acc h) → a f : (-> a v a) acc : a h : (Map/c k v)
> (map-fold list '() (hashmap "a" "b" "c" "d")) '((() "c" "d") "a" "b")
> (map-fold/value list '() (hashmap "a" "b" "c" "d")) '((() "d") "b")
3.11.7 Map语法糖
azelf提供了类似于JavaScript的object定义语法:
{ 1 2 } { 1 (array 1 2) } (map-size {})