(defun read-to-char (c stream)
(let ((x (read-char stream nil)))
(cond ((null x) nil)
((char= x c) t)
(t (read-to-char c stream)))))
This isn't much worse looking then the obvious iterative solutions.
..only it has Scheme written all over it ;-) In Common Lisp this is
spelled as
(defun read-to-char (c stream)
(loop for x = (read-char stream nil)
while x do (when (char= x c) (return t))))
Frode Vatvedt Fjeld wrote:
(defun read-to-char (c stream)
(let ((x (read-char stream nil)))
(cond ((null x) nil)
((char= x c) t)
(t (read-to-char c stream)))))
This isn't much worse looking then the obvious iterative solutions.
..only it has Scheme written all over it ;-) In Common Lisp this is
spelled as
(defun read-to-char (c stream)
(loop for x = (read-char stream nil)
while x do (when (char= x c) (return t))))
It's shorter in Gauche Scheme:
(use srfi-42) ;; first-ec
(define (read-to-char c port)
(first-ec #f
(:port x port read-char)
(if (char=? x c))
#t))
Testing.
(call-with-input-string "foo-Frodo is foolish."
(lambda (in) (read-to-char #\- in)
(read-line in)))
"Frodo is foolish."
Shorter yet:
(use srfi-121) ; generators
(define (read-to-char c port)
(generator-find (is c) (cut read-char port)))
Given:
(define-syntax is
(syntax-rules ()
[(is x)
(lambda (y) (equal? y x))]
[(is compare x)
(lambda (y) (compare y x))]
[(is key compare x)
(lambda (y) (compare (key y) x))]))
(defun read-to-char (c stream)
(loop for x = (read-char stream nil)
while x do (when (char= x c) (return t))))
How verbose!! The function can be expressed much more concisely as:
(defun read-to-char (c stream)
(loop for x = (read-char stream nil)
while x when (char= x c) return t))
or if one doesn't mind the possibility of an extra return value, as:
(defun read-to-char (c stream)
(ignore-errors (loop when (eql (read-char stream) c) return it))
(defun read-to-char (c stream)
(loop for x = (read-char stream nil)
while x do (when (char= x c) (return t))))
How verbose!! The function can be expressed much more concisely as:
(defun read-to-char (c stream)
(loop for x = (read-char stream nil)
while x when (char= x c) return t))
or if one doesn't mind the possibility of an extra return value, as:
(defun read-to-char (c stream)
(ignore-errors (loop when (eql (read-char stream) c) return it))
Why is LOOP needed?
Scheme:
(define (read-to-char c port)
(let ((r (read-char port)))
(unless (or (eof-object? r) (eq? c r))
(read-to-char c port))))
| Sysop: | Keyop |
|---|---|
| Location: | Huddersfield, West Yorkshire, UK |
| Users: | 715 |
| Nodes: | 16 (2 / 14) |
| Uptime: | 34:53:40 |
| Calls: | 12,109 |
| Files: | 15,006 |
| Messages: | 6,518,344 |