; -*- Scheme -*-
;
; $Id: mawk00.scm,v 1.1 1998/03/16 07:58:41 foner Exp $

(require 'read-line)

;;+doc
;; procedure: mawk:for-each
;; arguments: action[line line-number next state] state
;; signature: forall a => (string x int x (a -> a) x a -> a) x a -> a
;; arguments: action[line line-number next state] state port
;; signature: forall a => (string x int x (a -> a) x a -> a) x port x a -> a
;; pre:       (input-port? port)
;;
;; Applies ACTION to the first line read from PORT or from (CURRENT-INPUT-PORT)
;; if PORT is not defined.  The second argument to ACTION is the line
;; number of that line (starts at 1).  The third argument a procedure
;; which takes the STATE and applies ACTION to the next line in the input.
;; It is up to the writer of ACTION to call this in ACTION if ACTION is to
;; be applied to more than the first line of input.  The fourth argument
;; to ACTION is a STATE which the ACTION can manipulate and should also return.
;;
;; This version of MAWK is for the pure of heart who try to eschew the
;; use of assignment/implicit-state (well as pure as you can get with
;; side-effecting I/O :-).
;;-doc

(define mawk:for-each
  (lambda (a r . opt)
    (let ((ip (if (null? opt) (current-input-port) (car opt))))
      (let loop ((l (read-line ip)) (ln 1) (r r))
	(if (eof-object? l)
	    r
	    (a l ln (lambda (r) (loop (read-line ip) (+ ln 1) r))))))))

;;+doc
;; procedure: mawk:for-all
;; arguments: action[line line-number state] state
;; signature: forall a => (string x int x a -> a) x a -> a
;; arguments: action[line line-number state] state port
;; signature: forall a => (string x int x a -> a) x port x a -> a
;; pre:       (input-port? port)
;;
;; Applies ACTION to each line read from PORT or from (CURRENT-INPUT-PORT)
;; if PORT is not defined.  The second argument to ACTION is the line
;; number of that line (starts at 1).  The third argument is a STATE
;; which the ACTION can manipulate and should return.
;;
;; This version of MAWK is for the pure of heart who try to eschew the
;; use of assignment/implicit-state (well as pure as you can get with
;; side-effecting I/O :-).
;;-doc

(define mawk:for-all
  (lambda (a r . opt)
    (let ((ip (if (null? opt) (current-input-port) (car opt))))
      (let loop ((l (read-line ip)) (ln 1) (r r))
	(if (eof-object? l)
	    r
	    (loop (read-line ip) (+ ln 1) (a l ln r)))))))

; eof
