jijixi #4341(2007/11/22 13:35 GMT) [ Scheme ] Rating0/0=0.00
#4300 のほぼ直訳。 パターンマッチ大好きです。
see: #4300
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
(use util.match) (use util.list) (define PARENS (alist->hash-table '(("(" . ")") ("{" . "}") ("[" . "]")) 'equal?)) (define RPARENS (alist->hash-table (hash-table-map PARENS (lambda (a b) (cons b a))) 'equal?)) (define (reverse-string2_ str acc paren) (match str (() (cons acc '())) ((ch . rest) (cond ((hash-table-exists? PARENS ch) (match-let1 (str_ . rest_) (reverse-string2_ rest '() ch) (let1 ch_ (if (equal? ch (car str_)) (hash-table-get PARENS ch) ch) (reverse-string2_ rest_ (append str_ (list ch_) acc) paren)))) ((and paren (hash-table-exists? RPARENS ch)) (let1 ch_ (if (equal? ch (hash-table-get PARENS paren)) (hash-table-get RPARENS ch) ch) (cons (append (list ch_) acc) rest))) (else (reverse-string2_ rest (cons ch acc) paren)))))) (define (reverse-string2 str) (let1 str_ (map string (string->list str)) (match-let1 (reversed . _) (reverse-string2_ str_ '() #f) (string-join reversed "")))) (define SAMPLES '(("文字列(もじれつ)の反転(はんてん)" "(んてんは)転反の(つれじも)列字文") ("対応[の{とれている(さまざまな)括弧}の(例)]です。" "。すで[(例)の{弧括(なまざまさ)るいてれと}の]応対") ("これ(は(対応のとれていない)括弧がある例です。" "。すで例るあが弧括(いないてれとの応対)は(れこ") ("これ(も{対応の)とれていない}括弧の例です。" "。すで例の弧括}いないてれと)の応対{も(れこ"))) (define (test-reverse-string2) (for-each (match-lambda ((input expected) (let* ((result (reverse-string2 input)) (cond_ (if (equal? expected result) 'OK 'NG))) (begin (format #t "(reverse-string2 ~s)\n" input) (format #t " expected: ~s\n" expected) (format #t " result: ~s" result) (format #t " ... ~s\n" cond_))))) SAMPLES)) (define (main argv) (test-reverse-string2))
Rating0/0=0.00-0+
[ reply ]
jijixi
#4341()
[
Scheme
]
Rating0/0=0.00
#4300 のほぼ直訳。 パターンマッチ大好きです。
see: #4300
Rating0/0=0.00-0+
[ reply ]