Skip to content

Commit cdf6f58

Browse files
authored
[ 210_11] 给hash-table补上hash-table-fold函数
1 parent e6232c5 commit cdf6f58

File tree

4 files changed

+21
-4
lines changed

4 files changed

+21
-4
lines changed

devel/210_11.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# 210_11
2+
3+
## 2026/01/30 为hash-table补上hash-table-fold函数

goldfish/liii/hash-table.scm

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,10 @@
2525
hash-table-set! hash-table-delete! hash-table-intern! hash-table-update!
2626
hash-table-update!/default hash-table-pop! hash-table-clear!
2727
hash-table-size hash-table-keys hash-table-values hash-table-entries
28-
hash-table-find hash-table-count
28+
hash-table-find hash-table-count hash-table-fold
2929
hash-table-for-each hash-table-map->list
3030
hash-table->alist
3131
)
3232
(begin
3333
) ; end of begin
3434
) ; end of library
35-

goldfish/srfi/srfi-125.scm

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@
2121
hash-table-ref/default hash-table-set! hash-table-delete! hash-table-intern!
2222
hash-table-update! hash-table-update!/default hash-table-pop! hash-table-clear!
2323
hash-table-size hash-table-keys hash-table-values hash-table-entries hash-table-find
24-
hash-table-count hash-table-for-each hash-table-map->list hash-table->alist)
24+
hash-table-count hash-table-fold hash-table-for-each hash-table-map->list
25+
hash-table->alist)
2526
(begin
2627

2728
(define (assert-hash-table-type ht f)
@@ -128,6 +129,15 @@
128129
(typed-lambda ((pred? procedure?) (ht hash-table?))
129130
(count (lambda (x) (pred? (car x) (cdr x))) (map values ht))))
130131

132+
(define (hash-table-fold proc seed ht)
133+
(assert-hash-table-type ht hash-table-fold)
134+
(let ((result seed))
135+
(hash-table-for-each
136+
(lambda (k v)
137+
(set! result (proc k v result)))
138+
ht)
139+
result))
140+
131141
(define hash-table-for-each
132142
(typed-lambda ((proc procedure?) (ht hash-table?))
133143
(for-each (lambda (x) (proc (car x) (cdr x))) ht)))

tests/goldfish/liii/hash-table-test.scm

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,12 @@
256256
(hash-table 'a 1 'b 2 'c 3))
257257
(check cnt => 6))
258258

259+
(let ((ht (hash-table 'a 1 'b 2 'c 3)))
260+
(check (hash-table-fold (lambda (k v acc) (+ acc v)) 0 ht) => 6)
261+
)
262+
263+
(check (hash-table-fold (lambda (k v acc) (+ acc v)) 10 (hash-table)) => 10)
264+
259265
(let* ((ht (hash-table 'a 1 'b 2 'c 3))
260266
(ks (hash-table-map->list (lambda (k v) k) ht))
261267
(vs (hash-table-map->list (lambda (k v) v) ht)))
@@ -275,4 +281,3 @@
275281
=> (list 'k1 'v1))
276282

277283
(check-report)
278-

0 commit comments

Comments
 (0)