Sujet : Re: tuning - corrected shootout entry
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lisp comp.lang.schemeDate : 02. Sep 2024, 23:17:39
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vb5a1f$30apa$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
Nicolas Neuss wrote:
(defun wordcount (&optional (stream *standard-input*)
&aux (*readtable* (copy-readtable)) (table (make-hash-table)))
;; tweak readtable
(loop for char across "\".;,#:()[]{}" do
(set-syntax-from-char char #\Space))
;; count
(loop for word = (read stream nil #\.) until (eq word #\.)
do (incf (gethash word table 0)))
;; output
(let ((*print-pretty* nil))
(loop for (word . count) in
(sort (loop for a being the hash-keys of table using (hash-value b)
collect (cons a b))
#'(lambda (a b)
(or (> (cdr a) (cdr b))
(string<= (car a) (car b)))))
do (format t "~D : ~A~%" count (string-downcase word)))))
;;; Testing:
(wordcount (make-string-input-stream "A b a hello.B, a Hello b"))
Gauche Scheme
(use srfi-13) ; string-tokenize string-upcase
(use srfi-14) ; char. sets
(use srfi-42) ; do-ec
(define (wordcount :optional (port (current-input-port)))
(rlet1 al '()
(do-ec
(:port line port read-line)
(:list word (string-tokenize line char-set:letter))
(ainc! al (string-upcase word)))))
(call-with-input-string
"Foo.b,a:e c(d)e d
c b a[foo]FOO"
wordcount)
===>
(("D" . 2) ("C" . 2) ("E" . 2) ("A" . 2) ("B" . 2) ("FOO" . 3))
Given:
(define-syntax ainc!
(syntax-rules ()
[(_ alist key val func default)
(let ((pair (assoc key alist)))
(if pair
(set-cdr! pair (func val (cdr pair)))
(set! alist (cons (cons key (func val default)) alist))))]
[(_ alist key val func)
(ainc! alist key val func 0)]
[(_ alist key val)
(ainc! alist key val +)]
[(_ alist key)
(ainc! alist key 1)]))