Reputation: 182
I have a list of keys and a list of values that I want to add to a hash table. The best I've got so far is:
(apply hash-set*! table (flatten (map list keys values)))
But that makes a lot of nested lists only to flatten them.
Is there a simple way to do this without making the nested lists?
Upvotes: 0
Views: 621
Reputation: 24623
Simplest 'for'
loop can be used here:
(for ([k keys]
[v vals])
(hash-set! table k v))
Upvotes: 1
Reputation: 17233
I think I would write it like this:
#lang racket
(define keys '(a b c))
(define values '(1 2 3))
(define table (hash 'p 34 'c 9))
(for/fold ([ht table])
([k (in-list keys)]
[v (in-list values)])
(hash-set ht k v))
... no extra consing required.
Upvotes: 1
Reputation: 48775
Unless your lists are tens of thousands long it really doesn't matter but in the name of laziness here is what I would have done:
(require srfi/26) ; cut
(for-each (cut hash-set! table <> <>) keys vals)
Same without SRFI-26:
(for-each (λ (k v) (hash-set! table k v)) keys vals)
Upvotes: 1