On Wed, May 25, 2016 at 11:26:11AM +0200, Ricardo Wurmus wrote: > > Efraim Flashner <efr...@flashner.co.il> writes: > > > +(define (wc-l-command file) > > + (let* ((input-file (open-file file "r")) > > + (line (read-line input-file)) > > + (line-count 0)) > > + (while (not (eof-object? line)) > > + (set! line-count (1+ line-count)) > > + (set! line (read-line input-file))) > > + line-count)) > > It’s unusual for me to see the use of “while” and “set!” in Scheme code. > You could do this in a functional manner using a fold (see SRFI-1) or > with file streams (see SRFI-41), which also provides a stream-fold.
I'm going to put set! in the GOTO box. GOTO worked well enough when I learned QBasic, but just because its implemented doesn't mean I should still use it. (ie: its there but try not to use it) > > The idea with a fold is that you have a function that takes a value > (e.g. from a list or a stream) and an intermediate result. The function > does something to the value and then returns a new intermediate result. I already like this much better > > Here’s a fold over a list of symbols implementing a count: > > (fold > (lambda (_ res) (+ res 1)) ; increase the result > 0 ; start at 0 > '(hello world bye)) ; items to count > > If you had a file stream, where each element represents one line, you > can fold over all lines in much the same way to get a count. You could > use the same framework with a different stream element generator > (reading one word or byte at a time instead of one line at a time) to > implement the other features of “wc”. I'll take another look at streams and rework that. I still think asking the filesystem how big the file is works well for `wc -c', but `wc -l' and `wc -w' should really be part of the same function. > > There’s an example of how to define a file stream in the Guile manual in > the documentation for SRFI-41. That looks like a good place to start then :) > > ~~ Ricardo -- Efraim Flashner <efr...@flashner.co.il> אפרים פלשנר GPG key = A28B F40C 3E55 1372 662D 14F7 41AA E7DC CA3D 8351 Confidentiality cannot be guaranteed on emails sent or received unencrypted
signature.asc
Description: PGP signature