Sysop: | Amessyroom |
---|---|
Location: | Fayetteville, NC |
Users: | 23 |
Nodes: | 6 (0 / 6) |
Uptime: | 52:39:41 |
Calls: | 583 |
Files: | 1,139 |
D/L today: |
179 files (27,921K bytes) |
Messages: | 111,617 |
I once wrote a program (in Python) that reads a file and counts how
often each byte between 0 and 255 occurs. It then printed the
results like that:
0: 417
1: 120
...
254: 595
255: 326
With this tool I wanted to get an evidence how compressed a file
is. This "program" was a 3-liner. How can I do it in max. 3 lines in
Lisp?
Here's my go :
(with-open-file (s "/home/drewc/TIM_BEACHY.txt" :element-type unsigned-byte)
(loop for byte = (read-byte s nil)
until (eql byte nil)
with count-plist = (list)
do (setf (getf count-plist byte)
(1+ (or (getf count-plist byte) 0)))
finally (return count-plist)))
I need only two lines:
(format t "~:{~3D: ~4D~%~}" (mapcar (lambda (c) (list (car c) (cdr c))) (make-histogram (coerce (BINARY-FILE-CONTENTS "tmp/misc/wang.accented") 'list))))
Of course, I used some library functions, all previously written, loaded with:
(use-package :com.informatimago.common-lisp.package)
(load-package :com.informatimago.common-lisp.list)
(use-package :com.informatimago.common-lisp.list)
(load-package :com.informatimago.common-lisp.file)
(use-package :com.informatimago.common-lisp.file)
(load "~/src/lisp/encours/word-count.lisp")
But I bet in Python too you have to load libraries to do it, no?
Pascal Bourguignon wrote:
I once wrote a program (in Python) that reads a file and counts how
often each byte between 0 and 255 occurs. It then printed the
results like that:
0: 417
1: 120
...
254: 595
255: 326
With this tool I wanted to get an evidence how compressed a file
is. This "program" was a 3-liner. How can I do it in max. 3 lines in
Lisp?
Here's my go :
(with-open-file (s "/home/drewc/TIM_BEACHY.txt" :element-type unsigned-byte)
(loop for byte = (read-byte s nil)
until (eql byte nil)
with count-plist = (list)
do (setf (getf count-plist byte)
(1+ (or (getf count-plist byte) 0)))
finally (return count-plist)))
I need only two lines:
(format t "~:{~3D: ~4D~%~}" (mapcar (lambda (c) (list (car c) (cdr c))) (make-histogram (coerce (BINARY-FILE-CONTENTS "tmp/misc/wang.accented") 'list))))
Of course, I used some library functions, all previously written, loaded with:
(use-package :com.informatimago.common-lisp.package)
(load-package :com.informatimago.common-lisp.list)
(use-package :com.informatimago.common-lisp.list)
(load-package :com.informatimago.common-lisp.file)
(use-package :com.informatimago.common-lisp.file)
(load "~/src/lisp/encours/word-count.lisp")
But I bet in Python too you have to load libraries to do it, no?
Gauche Scheme
(let1 v (make-vector 256 0) (with-input-from-file "foo.exe"
(cut until (read-byte) eof-object? => b (inc! (ref v b))))
(dotimes (i 256) (print i ": " (ref v i))))
0: 28553
1: 1195
2: 1143
3: 1787
4: 1300
...
251: 25
252: 41
253: 33
254: 215
255: 1355