(seq alpha (zero-more (one-of alpha numeric))), and we stopped at refactoring the numeric and alpha parsers, and ended up with return, fail, and char-test. char-test Expandedchar-test gives us a good base for building a bunch of other character-based parser:
;; char= returns a parser to test whether the next char equals c
(define (char= c)
(char-test (lambda (it)
(char=? it c))))
;; in-chars returns a parser to match against the list of chars
(define (in-chars lst)
(char-test (lambda (it)
(member it lst))))
;; not-in-chars is the reverse of in-chars
(define (not-in-chars lst)
(char-test (lambda (it)
(not (member it lst)))))
;; in-char-range returns a parser to match char between from & to chars
(define (in-char-range from to)
(char-test (lambda (it)
(char<=? from it to))))
;; the oppposite of in-char-range
(define (not-in-char-range from to)
(char-test (lambda (it)
(not (char<=? from it to)))))
So we can build parsers such as the following:
;; a parser to test for the backslash
(define backslash (char= #\\))
;; writing numeric using in-chars
(define numeric (in-chars '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))
;; writing equivalent to regexp \S (non-whitespace)
(define non-whitespace (not-in-chars '(#\tab #\return #\newline #\space #\vtab)))
;; lower-case alpha using in-char-range
(define lower-case (in-char-range #\a #\z)))
;; upper-case alpha using in-char-range
(define upper-case (in-char-range #\A #\Z)))
It would be nice to write alpha in terms of upper-case and lower-case as defined above:
(define alpha (one-of upper-case lower-case))
So let's see how we can write one-of.Higher order Parsers
The idea of
one-of is straight forward - take in a list of the parsers to test against the input, one parser at a time. The first one that succeeded would be returned: