Skip to content

Instantly share code, notes, and snippets.

@lispm
Last active November 22, 2016 05:05
Show Gist options
  • Save lispm/801da36437c9214e5b0dc1d39f4a31ef to your computer and use it in GitHub Desktop.
Save lispm/801da36437c9214e5b0dc1d39f4a31ef to your computer and use it in GitHub Desktop.
; this code iterates over a hashmap
; prints a pair to a string
; collects the strings into a list
; prints the list to a string, by using an format iteration command
; then concatenates the string with two other strings
(defun pr-mal-hash-map (hash-map &optional (print-readably t))
(let ((hash-map-value (types:mal-data-value hash-map)))
(concatenate 'string
"{"
(format nil
"~{~a~^ ~}"
(let (repr)
(genhash:hashmap (lambda (key value)
(push (format nil
"~a ~a"
(pr-str key print-readably)
(pr-str value print-readably))
repr))
hash-map-value)
repr))
"}")))
; this version gets rid of the ugly CONCATENATE and the FORMAT in the HASHMAP
(defun pr-mal-hash-map (hash-map &optional (print-readably t))
(let ((hash-map-value (types:mal-data-value hash-map)))
(format nil "{~{~a~ ~a^ ~}}"
(let (repr)
(genhash:hashmap (lambda (key value)
(push (pr-str value print-readably) repr)
(push (pr-str key print-readably) repr))
hash-map-value)
repr))))
; Which can be written a bit more compact as:
(defun pr-mal-hash-map (hash-map &optional (print-readably t) &aux repr)
(genhash:hashmap (lambda (key value)
(push (pr-str value print-readably) repr)
(push (pr-str key print-readably) repr))
(types:mal-data-value hash-map))
(format nil "{~{~a~ ~a^ ~}}" repr))
; above version is less than half as long as the original and simpler.
; * there is no concatenate
; * there is only one format, instead of two
; * the nesting of the forms is greatly reduced
; this code iterates over a hash map and prints the key and value to a string stream
(defun pr-mal-hash-map (hash-map &optional (print-readably t))
(let ((hash-map-value (types:mal-data-value hash-map)))
(nsubstitute #\} #\space
(with-output-to-string (s)
(write-string "{" s)
(genhash:hashmap (lambda (key value)
(write-string (pr-str key print-readably) s)
(write-string " " s)
(write-string (pr-str value print-readably) s)
(write-string " " s))
hash-map-value))
:count 1 :from-end t)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment