public
Created

Simple parser combinators in Scheme

  • Download Gist
parsec.scm
Scheme
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
(define (return v) (lambda (s ks kf) (ks v s)))
(define fail (lambda (s ks kf) (kf)))
 
; >>=
(define (bind a f)
(lambda (s ks kf)
(a s
(lambda (av s1) ((f av) s1 ks kf))
kf)))
 
(define (mplus a b)
(lambda (s ks kf)
(a s ks
(lambda () (b s ks kf)))))
 
(define (psym pred)
(lambda (s ks kf)
(if (null? s)
(kf)
(if (pred (car s))
(ks (car s) (cdr s))
(kf)))))
 
(define (char a) (psym (lambda (c) (eq? a c))))
 
(define (many p)
(mplus
(bind
p (lambda (pv)
(bind (many p) (lambda (pvs) (return (cons pv pvs))))))
(return '())))
 
(define (run-parser p str)
(p (string->list str)
(lambda (v s) (format #t "Parser ran successfully. Result is ~a, remainder is ~a.~%" v (list->string s)))
(lambda () (format #t "Parser failed.~%"))))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.