I made a mistake in designing the program. I need to sort part of the entries in a hash table by their value. I will tell the story with a demo code.
;; A loacal hash table......
(let ((table (make-hash-table))
(list-of-interest nil))
(puthash 0 "Foo" table)
(puthash 1 "Bar" table)
;;..........
(puthash 9999 "Bra" table)
;; And I have a list with key I am interested to sort
(dotimes (var 50)
(add-to-list list-of-interest (random 9999)))
;; Sorting should depends on comparing the associated string
;; For exmple,
;; If the list is (0 1 9999)
;; I hope to get (1 9999 0) as "Bar" < "Bra" < "Foo"
;; However, I forgot that the table is a local variable
;; I can't pass the table to the predicate function by any means
;; So the predicate function can never resolve the string from the key
(sort list-of-interest 'predicate)
;; When I was thinking to rewrite the code
;; I find that a lambda function can 'grab' the local variable
(sort list-of-interest (lambda (a b)
(string-lessp (gethash a table) (gethash b table))))
;; return value
table)
I raised two questions in my mind:
- The most important question: Is the lambda function fine?
- I believed lambda is a function like others without name only. Why can it 'grab' the local variable?