Skip to content

Instantly share code, notes, and snippets.

@UnkindPartition
Created October 17, 2012 07:58
Show Gist options
  • Save UnkindPartition/3904294 to your computer and use it in GitHub Desktop.
Save UnkindPartition/3904294 to your computer and use it in GitHub Desktop.
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))
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.~%"))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment