(defun groups (seq &key (test #'eql) (key #'identity))
(loop for start = 0 then end
for end = (position-if (lambda (x)
(not (funcall test
(funcall key (elt seq start))
x)))
seq
:start start
:key key)
collect (subseq seq start end)
while end))
(defun string-alphanumericp (string)
(check-type string string)
(every #'alphanumericp string))
(defun escape-format-string (string)
(apply #'concatenate 'string
(loop for c across string
if (char= c #\~)
collect "~~"
else
collect (string c))))
(defun odai-pt14-651 (string)
(let* ((segments (groups string :key #'alphanumericp))
(fmt-string (format nil "~{~A~}~%"
(mapcar (lambda (s)
(if (string-alphanumericp s)
"~A"
(escape-format-string s)))
segments)))
(words (remove-if (complement #'string-alphanumericp) segments)))
(apply #'format t fmt-string (reverse words))))
(loop while (listen)
do (odai-pt14-651 (read-line)))