久しぶりの Scheme。約5ヶ月ぶり。ネタも古くてこれ。
cf. 連続する数列をハイフンでまとめるPythonスクリプト – blog.PanicBlanket.com
(define f (lambda (p) (cond ((= (cadr p) 1) "") ((> (cadr p) 1) (string-append (number->string (car p)) ", "))))) (define g (lambda (p) (cond ((= (cadr p) 1) (string-append (number->string (car p)) "-")) ((> (cadr p) 1) (string-append (number->string (car p)) ", "))))) (define serial (lambda (s l) (let ((p (car l))) (cond ((= (cadr p) 1) (serial (string-append s (f p)) (cdr l))) ((> (cadr p) 1) (discrete (string-append s (f p)) (cdr l))) (else (string-append s (number->string (car p)))))))) (define discrete (lambda (s l) (let ((p (car l))) (cond ((= (cadr p) 1) (serial (string-append s (g p)) (cdr l))) ((> (cadr p) 1) (discrete (string-append s (g p)) (cdr l))) (else (string-append s (number->string (car p)))))))) (define list-with-diff (lambda (lis) (map list lis (append (map - (cdr lis) lis) (list 0))))) (define hyphenate (lambda (str) (letrec ((lis (map string->number (string-split str " "))) (l (list-with-diff lis))) (cond ((= (cadar l) 1) (serial (g (car l)) (cdr l))) (else (discrete (g (car l)) (cdr l))))))) (print (hyphenate "1 2 3")) (print (hyphenate "1 2 3 5 7 8")) (print (hyphenate "1 3 4 5 7"))
takatoh@nightschool $ gosh hyphenate_num.scm 1-3 1-3, 5, 7-8 1, 3-5, 7