Skip to content

Instantly share code, notes, and snippets.

@ytaki0801
Last active February 21, 2022 17:41
Show Gist options
  • Save ytaki0801/3bcf807328548b83ec53491f04030933 to your computer and use it in GitHub Desktop.
Save ytaki0801/3bcf807328548b83ec53491f04030933 to your computer and use it in GitHub Desktop.
Parser for simplest S-expression by using 1-character input in Scheme
(define *lh* #f)
(define (get-token)
(define (put-c1 x) (set! *lh* x))
(define (null-c1) (set! *lh* #f))
(define (get-c1) (if *lh* (let ((lh *lh*)) (null-c1) lh) (read-char)))
(define (tstring t) (list->string (reverse t)))
(define (skip-spaces)
(do ((c (get-c1) (get-c1)))
((not (member c (string->list " \n\r"))) (put-c1 c))))
(let loop ((c (get-c1)) (t '()))
(cond ((member c (string->list " \n\r"))
(cond ((null? t)
(skip-spaces)
(loop (get-c1) t))
(else (tstring t))))
((eq? c #\() (skip-spaces) (string c))
((eq? c #\))
(if (null? t) (string c) (begin (put-c1 c) (tstring t))))
(else (loop (get-c1) (cons c t))))))
(define (sread)
(define (slist)
(let ((t (get-token)))
(cond ((equal? t ")") '())
((equal? t "(") (let ((h (slist))) (cons h (slist))))
(else (cons t (slist))))))
(let ((t (get-token)))
(if (equal? t "(") (slist) t)))
(write (sread)) (newline)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment