Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

13. カウント:繰り返しと正規表現

while ループを使って、リージョン内の句読点---終止符、カンマ、セミコロン、コロン、感嘆符、疑問符---の数を数える関数を書きなさい。同じ関数を再帰関数を使って書きなさい。

(defun count-punctuation-region (beginning end)  
  (interactive "r")
  (message "Counting punctuation marks in region ... ")

  (save-excursion
    (let ((count 0))
      (goto-char beginning)

      (while (and (< (point) end)
                  (re-search-forward "[.,;:?!]" end t))
        (setq count (1+ count)))

      (cond ((zerop count)
             (message
              "The region does NOT have any punctuation marks."))
            ((= 1 count)
             (message
              "The region has 1 punctuation mark."))
            (t
             (message
              "The region has %d punctuation marks." count))))))
;; 再帰バージョン
(defun count-punctuation-region2 (beginning end) 
  (interactive "r")
  (message "Counting punctuation marks in region ... ")
  (save-excursion
    (goto-char beginning)
    (let ((count (recursive-count-punctuation-mark end)))
      (cond ((zerop count)
             (message
              "The region does NOT have any punctuation marks."))
            ((= 1 count)
             (message "The region has 1 punctuation mark."))
            (t
             (message
              "The region has %d punctuation marks." count))))))

(defun recursive-count-punctuation-mark (region-end)
  (if (and (< (point) region-end)
           (re-search-forward "[.,;:?!]" region-end t))
      (1+ (recursive-count-punctuation-mark region-end)) 
    0))