[CM] iterating over a hash table

Bill Schottstaedt bil at ccrma.Stanford.EDU
Wed Dec 16 04:43:06 PST 2009


> Speed-wise, how does referencing a hash table compare with using (assoc x y) 
> as I am above. Is it also just hashed values? 

For a small case, there's not much difference, but eventually the
hash table wins because it can find the desired element without
searching through a long list.

If you're concerned about speed, it might be faster to use a
vector instead:

(define (entropy-1 string)
  (let* ((sum 0.0)
	 (len (length string))
	 (top (+ 1 (apply max string)))
	 (table (make-vector top 0)))
    (do ((i 0 (+ i 1))
	 (element string (cdr element)))
	((= i len))
      (set! (table (car element)) (+ 1 (table (car element)))))
    (do ((i 0 (+ i 1)))
	((= i top))
      (let ((val (/ (table i) len)))
	(if (not (zero? val))
	    (set! sum (+ sum (* val (log val 2.0)))))))
    (- sum)))


> I guess I would prefer hash-table-for-each 

I'm leaning that way too.  I wanted for-each to work with all
"applicable" types, but currently it doesn't accept hash-tables.




More information about the Cmdist mailing list