Sum
March 25, 2011
Here is our version of the program:
#! /usr/bin/scheme --script
(define (sum)
(let loop ((c (read-char)) (s 0) (b 0))
(if (eof-object? c)
(values s (+ (quotient b 512) (if (zero? (modulo b 512)) 0 1)))
(loop (read-char) (modulo (+ s (char->integer c)) 65535) (+ b 1)))))
(if (null? (cdr (command-line)))
(let-values (((s b) (sum)))
(display s) (display " ") (display b) (newline))
(do ((files (cdr (command-line)) (cdr files))) ((null? files))
(with-input-from-file (car files)
(lambda ()
(let-values (((s b)(sum)))
(display s) (display " ")
(display b) (display " ")
(display (car files)) (newline))))))
The first line and the (command-line)
function are unique to Chez Scheme; (command-line)
returns the command line by which the program was called, including the name of the program in its car
. The main body of the program is a two-legged if
; the first leg handles input from stdin
and the second leg handles input from named files. Scheme provides no standard way to trap file-opening errors, so we don’t implement the return codes of the original sum
command; we could do so if we used a Chez-specific error handler, but the details aren’t germane here, so we simply ignore the issue.
The (sum)
function calculates the checksum and block size for the current input port, which is set in the main body of the code. The checksum adds the values of the bytes in the file, taking each partial sum modulo 216−1. The calculation of the block size is careful to add 1 for a partial block at the end of the file.
The code is assembled at http://programmingpraxis.codepad.org/ml5SKPg0.
I’m not sure that this is quite in the spirit of the site but:
My Haskell solution (see http://bonsaicode.wordpress.com/2011/03/25/programming-praxis-sum/ for a version with comments):
[…] today’s Programming Praxis exercise, our goal is to implement a unix checksum utility. Let’s get […]
I implemented a version in Factor (the short version is below):
The full version is here:
http://re-factor.blogspot.com/2011/03/sum.html
Whoops, mis-understood the requirements – this is a fixed version for Factor:
Here’s a go in Common Lisp using LOOP, also had a bit of fun on tweaking the reading of the file and inlining the calculation:
(defun sv4r-sum (file)
"Calculate a Unix SV4R-style file checksum"
(with-open-file (stream file :direction :input :element-type 'unsigned-byte)
(loop :with buffer = (make-array 512 :element-type 'unsigned-byte)
:and csum = 0
:for pos = (read-sequence buffer stream)
:while (plusp pos)
:do (loop :for b :from 0 :to (1- pos)
:do (setf csum (mod (+ csum (svref buffer b)) 65535)))
:counting buffer :into c
:finally (return (values csum c)))))
You can never have to many Scheme solutions ;)