guix-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Adding wc to Bournish


From: Ricardo Wurmus
Subject: Re: Adding wc to Bournish
Date: Wed, 25 May 2016 11:26:11 +0200

Efraim Flashner <address@hidden> 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.

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.

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”.

There’s an example of how to define a file stream in the Guile manual in
the documentation for SRFI-41.

~~ Ricardo



reply via email to

[Prev in Thread] Current Thread [Next in Thread]