6

I'm playing around with guile to try and get familiar with pure functional programming concepts. Before I can do anything useful with any language, I need to understand some basic data structures and how to manipulate them effectively... in particular, enumerable data structures.

I can iterate a list like this (I'm not sure if I'm indenting this correctly or not):

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

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

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

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

The Ruby equivalent of what I'm trying to do would be:

{ "one" => 1, "two" => 2, "three" => 3 }.map do |key, value|
  puts "#{key} => #{value}"
end
Will Ness
  • 70,110
  • 9
  • 98
  • 181
d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • P.S. You should use `for-each` instead of `map` when the return value from the function is not used. – C. K. Young Nov 15 '11 at 02:30
  • Thanks, I got map from the page in the wiki on looping and just assumed it was used since the return value can be ignored :) Good to know! – d11wtq Nov 15 '11 at 02:32

1 Answers1

5

If you are using R6RS hashtables, you can use the hashtable-keys and hashtable-entries functions.

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

So for your example, using Guile's hash-for-each, you'd do:

(use-modules (ice-9 hash-table))
(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)
Daniel Dinnyes
  • 4,898
  • 3
  • 32
  • 44
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • Great, thanks, I think I'll stick with figuring out what's available natively before looking at libraries (just for the basic data structures at least). I never saw the native hashtable support before :) – d11wtq Nov 15 '11 at 02:37