#lang racket (define (tokenize s) (let loop ([i 0] [tok ""] [result '()]) (if (< i (string-length s)) (let ([c (substring s i (+ 1 i))]) (cond [(regexp-match #rx"[ \t\r\n]" c) (loop (+ 1 i) "" (append result (if (> (string-length tok) 0) (list tok) '())))] [(regexp-match #rx"[()]" c) (loop (+ 1 i) "" (if (> (string-length tok) 0) (append result (list tok c)) (append result (list c))))] [else (loop (+ 1 i) (string-append tok c) result)])) (if (> (string-length tok) 0) (append result (list tok)) result)))) (define-syntax-rule (++ x) (set! x (+ 1 x))) (define (process-tokens lst) (define pos 0) (define (proc accum) ;(displayln (list "pos" pos)) (if (< pos (length lst)) (begin (let ([t (list-ref lst pos)]) (++ pos) (cond [(string=? t "(") (proc (append accum (list (proc '()))))] [(string=? t ")") accum] [else (proc (append accum (list t)))])) ) accum)) (proc '())) (define (parse-list s) (let ([tokens (tokenize s)]) (process-tokens tokens))) (define (main) (define test "(a b call (d e) foo)") (for ([x (tokenize test)]) (displayln x)) (define r (parse-list test)) (displayln r) (for ([x r]) (displayln x))) (main)
'My Computer Programs' 카테고리의 다른 글
(Racket) permute (0) | 2012.10.05 |
---|---|
(Racket) tLISP (0) | 2012.09.25 |
(newLISP) get web page, KOSPI200 시세 얻기 (0) | 2012.09.23 |
(Javascript) Clock (0) | 2012.09.15 |
(Javascript) KOSPI200 시세 얻기 (0) | 2012.09.15 |