Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple parser combinators in Scheme
(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))
(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)
(if (pred (car s))
(ks (car s) (cdr s))
(define (char a) (psym (lambda (c) (eq? a c))))
(define (many p)
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.~%"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment