In a trick scheme, how can I iterate over a list of key-value pairs (i.e. a hash map)?

I play with a trick to try to get acquainted with the concepts of pure functional programming. Before I can do anything useful in any language, I need to understand some basic data structures and how to manage them effectively ... in particular, enumerated data structures.

I can list a list like this (I'm not sure if I typed this correctly):

(map (lambda (v) (display (string-append v "\n")) '(1 2 3)) => 1 2 3 

What does a hash table / hash map look like in a schema? Is there a real data structure for representing one, or does it come down to compiling a list of lists? In which case, how do you get the key and value as separate variables from the internal list?

Obviously, this is wrong, as lambda expects one value, not two:

 (map (lambda (key value) (display (string-append key " => " value)) '('("one" 1) '("two" 2) '("three" 3))) 

In Ruby, the equivalent of what I'm trying to do would be:

 { "one" => 1, "two" => 2, "three" => 3 }.map do |key, value| puts "#{key} => #{value}" end 
+4
source share
1 answer

If you use R6RS hash tables , you can use the hashtable-keys and hashtable-entries functions.

If you use Guile native hashtables , you can use hash-map->list , hash-for-each , hash-for-each-handle or hash-fold .

So, for your example, using Guile hash-for-each , you would do:

 (define my-hash (make-hash-table)) (hash-set! my-hash "one" 1) (hash-set! my-hash "two" 2) (hash-set! my-hash "three" 3) (hash-for-each (lambda (key value) (format #t "~a => ~a~%" key value)) my-hash) 
+3
source

Source: https://habr.com/ru/post/1381231/


All Articles