単語ごとに区切るプログラム
30分プログラム、その191。 文字列を渡されると、それを単語ごとに区切るプログラム。
コンピュータプログラミングの概念・技法・モデル(asin:4798113468)に載っていたアルゴリズムのぱくり。でも記憶を頼りに書いているので、多少違っているかもしれない。
共著でありがちな言い訳をすると『このアルゴリズムの素晴しいところは彼のおかげで、間違っているところはすべて私のせいである。』
使い方
gosh> (split-word "hello world") ("hello" "world") gosh> (split-word "howdy,world") ("hwody" "world")
ソースコード
#! /opt/local/bin/gosh ;; -*- mode:scheme; coding:utf-8 -*- ;; ;; word-split.scm - word split ;; ;; Copyright(C) 2007 by mzp ;; Author: MIZUNO Hiroki ;; http://mzp.sakura.ne.jp/ ;; ;; Timestamp: 2007/11/26 23:03:11 ;; ;; This program is free software; you can redistribute it and/or ;; modify it under the same terms as Scheme itself. ;; (use srfi-14) (define (is-word c) (char-set-contains? (char-set-union char-set:lower-case char-set:upper-case) c)) (define (split-word-sub current str) (cond ;; end of string ((and (eq? str '()) (eq? current '())) '()) ;; no accumulate ((eq? str '()) (list (reverse current))) ;; have accumulate ;; within word ((is-word (car str)) ;; accumulate this char (split-word-sub (cons (car str) current) (cdr str))) ;; end of word ((not (eq? current '())) ;; append current word (cons (reverse current) (split-word-sub '() (cdr str)))) (else ;; skip (split-word-sub '() (cdr str))))) (define (split-word str) (map list->string (split-word-sub '() (string->list str))))