From mboxrd@z Thu Jan 1 00:00:00 1970 From: Ricardo Wurmus Subject: Re: Adding wc to Bournish Date: Wed, 25 May 2016 11:26:11 +0200 Message-ID: References: <20160524184720.GA27449@debian-netbook> Mime-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Return-path: Received: from eggs.gnu.org ([2001:4830:134:3::10]:51308) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1b5V59-00018F-Tw for guix-devel@gnu.org; Wed, 25 May 2016 05:26:28 -0400 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1b5V55-0003S1-TB for guix-devel@gnu.org; Wed, 25 May 2016 05:26:27 -0400 In-Reply-To: <20160524184720.GA27449@debian-netbook> List-Id: "Development of GNU Guix and the GNU System distribution." List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Errors-To: guix-devel-bounces+gcggd-guix-devel=m.gmane.org@gnu.org Sender: "Guix-devel" To: Efraim Flashner Cc: guix-devel@gnu.org Efraim Flashner 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=E2=80=99s unusual for me to see the use of =E2=80=9Cwhile=E2=80=9D and= =E2=80=9Cset!=E2=80=9D 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=E2=80=99s 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 =E2=80=9Cwc=E2=80=9D. There=E2=80=99s an example of how to define a file stream in the Guile ma= nual in the documentation for SRFI-41. ~~ Ricardo