Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that every value in a hash-table satisfies a predicate in Common Lisp

I have an hash table (setf ht (make-hash-table)) which contains some entries, for example (setf (gethash 'first ht) 'first-value), (setf (gethash 'second ht) 'second-value), ...

Furthermore I have a predicate test of arity one that evaluate to T or NIL. I want to check if all first entries of the hash table ht satisfy the test predicate. If, for example, the hash table consists of only the two entries given above, I want to know the evaluation of (and (test 'first) (test 'second)). Is there a simple way to do it?

like image 897
Matteo Avatar asked Oct 25 '25 03:10

Matteo


1 Answers

You'd like to know how you do what every does with sequences, with hash tables.

You can use the loop macro to iterate over every value and use :always to check each element for your test. As with every :always will terminate the loop immediately when the test is NIL.

(defun hash-every (test hash)
 (loop :for value :being :the :hash-values :in hash 
       :always (funcall test value)))

(hash-every #'numberp ht) ; ==> NIL
(hash-every #'symbolp ht) ; ==> T

You'd probably want to look the the Common Lisp Cookbok's hash table page for more hints.

like image 167
Sylwester Avatar answered Oct 27 '25 00:10

Sylwester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!