29f67f70f4b4

Add `collect-hash`
[view raw] [browse files]
author Steve Losh <steve@stevelosh.com>
date Tue, 07 Feb 2017 12:26:05 +0000
parents 5f26482784a6
children 3fea2a14eb5f
branches/tags (none)
files losh.lisp package.lisp

Changes

--- a/losh.lisp	Mon Feb 06 14:36:36 2017 +0000
+++ b/losh.lisp	Tue Feb 07 12:26:05 2017 +0000
@@ -1457,6 +1457,34 @@
                              ,form)))))))
 
 
+(defmacro-clause (COLLECT-HASH key-and-value &optional
+                  INTO var
+                  TEST (test #'eql))
+  "Collect keys and values into a hash table at `var`.
+
+  `key-and-value` should be a `(key-expr . value-expr)` pair.
+
+  If `var` is omitted the hash table will be returned instead.
+
+  `test` specifies the test used for the hash table.
+
+  Example:
+
+    (iterate (for x :from 0)
+             (for y :in '(a b c))
+             (collect-hash ((1+ x) . y)))
+    ; => {1 a
+    ;     2 b
+    ;     3 c}
+
+  "
+  (destructuring-bind (key . value) key-and-value
+    (let ((hash-table (or var iterate::*result-var*)))
+      `(progn
+         (with ,hash-table = (make-hash-table :test ,test))
+         (setf (gethash ,key ,hash-table) ,value)))))
+
+
 (defun keywordize-clause (clause)
   (iterate
     (for (k v . nil) :on clause :by #'cddr)
@@ -1506,6 +1534,7 @@
                            (keywordize-clause clause))))))
 
 
+
 ;;;; Hash Tables --------------------------------------------------------------
 (defun mutate-hash-values (function hash-table)
   "Replace each value in `hash-table` with the result of calling `function` on it.
@@ -1883,6 +1912,10 @@
   (terpri stream)
   (values))
 
+(defun pht (hash-table &optional (stream t))
+  "Synonym for `print-hash-table` for less typing at the REPL."
+  (print-hash-table hash-table stream))
+
 (defun print-hash-table-concisely (hash-table &optional (stream t))
   "Print a concise representation of `hash-table` to `stream.`
 
--- a/package.lisp	Mon Feb 06 14:36:36 2017 +0000
+++ b/package.lisp	Tue Feb 07 12:26:05 2017 +0000
@@ -80,7 +80,8 @@
     #+sbcl :stop-profiling
     :print-table
     :print-hash-table
-    :print-concisely))
+    :print-hash-table-concisely
+    :pht))
 
 (defpackage :losh.eldritch-horrors
   (:documentation "Abandon all hope, ye who enter here.")
@@ -144,8 +145,10 @@
   (:use :iterate) ; need this for iterate's `for` symbol fuckery
   (:documentation "Custom `iterate` drivers and clauses.")
   (:export
+
     :across-flat-array
     :averaging
+    :collect-hash
     :cycling
     :every-nth
     :for-nested
@@ -163,8 +166,10 @@
     :run-time
     :since-start-into
     :skip-origin
+    :test
     :timing
     :within-radius
+
     ))
 
 (defpackage :losh.licensing