refactor(transducers): foldling -> reduce-generic

This commit is contained in:
fiddlerwoaroof
2020-12-18 22:31:54 -08:00
parent 498d659978
commit 9ff7f44684

View File

@ -78,21 +78,30 @@
(defgeneric init (it)) (defgeneric init (it))
(defgeneric stepper (it)) (defgeneric stepper (it))
(defgeneric foldling (seq func init) (defgeneric reduce-generic (seq func init)
(:method ((seq sequence) (func function) init) (:method ((seq sequence) (func function) init)
(reduce func seq :initial-value init)) (reduce func seq :initial-value init))
(:method ((seq sequence) (func symbol) init) (:method ((seq sequence) (func symbol) init)
(reduce func seq :initial-value init))) (reduce func seq :initial-value init))
(:method (seq (func symbol) init)
(foldling seq (symbol-function func) init))
(:method ((seq hash-table) (func function) init)
(let ((acc init))
(maphash (lambda (k v)
(setf acc (funcall func acc (list k v))))
seq)
acc)))
(defun transduce (xf build seq) (defun transduce (xf build seq)
(unwrap build (unwrap build
(catch 'done (catch 'done
(foldling seq (reduce-generic seq
(funcall xf (stepper build)) (funcall xf (stepper build))
(init build))))) (init build)))))
(defclass lazy-sequence () (defclass lazy-sequence ()
((%next :initarg :next :reader next))) ((%next :initarg :next :reader next)))
(defmethod foldling ((seq lazy-sequence) (func function) init) (defmethod reduce-generic ((seq lazy-sequence) (func function) init)
(let ((next (next seq))) (let ((next (next seq)))
(loop for next-val = (funcall next) (loop for next-val = (funcall next)
for acc = init then next-acc for acc = init then next-acc