Associative array/Iteration: Difference between revisions
Content added Content deleted
(added novice-package version for Forth) |
|||
Line 2,079: | Line 2,079: | ||
Values: Netherlands, USA, Netherlands |
Values: Netherlands, USA, Netherlands |
||
Unique values: Netherlands, USA |
Unique values: Netherlands, USA |
||
</pre> |
|||
=={{header|Scheme}}== |
|||
{{works with|Gauche Scheme}} |
|||
<lang Scheme> |
|||
;; Create an associative array (hash-table) whose keys are strings: |
|||
(define table (hash-table 'string=? |
|||
'("hello" . 0) '("world" . 22) '("!" . 999))) |
|||
;; Iterate over the table, passing the key and the value of each entry |
|||
;; as arguments to a function: |
|||
(hash-table-for-each |
|||
table |
|||
;; Create by "partial application" a function that accepts 2 arguments, |
|||
;; the key and the value: |
|||
(pa$ format #t "Key = ~a, Value = ~a\n"))</lang> |
|||
Output: |
|||
<pre> |
|||
Key = !, Value = 999 |
|||
Key = world, Value = 22 |
|||
Key = hello, Value = 0 |
|||
</pre> |
|||
<lang Scheme> |
|||
;; Iterate over the table and create a list of the keys and the |
|||
;; altered values: |
|||
(hash-table-map |
|||
table |
|||
(lambda (key val) (list key (+ val 5000)))) |
|||
;; Create a new table that has the same keys but altered values. |
|||
(use gauche.collection) |
|||
(map-to <hash-table> |
|||
(lambda (k-v) (cons (car k-v) (+ (cdr k-v) 5000))) |
|||
table) |
|||
</lang> |
|||
To get a list of the keys or of the values of the table, |
|||
use one of the following: |
|||
<pre> |
|||
(hash-table-keys table) |
|||
(hash-table-values table) |
|||
</pre> |
</pre> |
||