Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternating upcase/downcase for a string in Common Lisp

I want to write a function that will return a string formatted with alternative upcase/downcase in Common Lisp. For example, entering "stackoverflow" should return the string "StAcKoVeRfLoW". Here's my attempt, but it just returns a list of cons pairs. Am I on the right track?

(defun mockify (chars)
  (let ((lst (coerce chars 'list)))
    (if (equal lst nil) nil
        (coerce (cons
                 (cons (char-upcase (car lst)) (char-downcase (cadr lst)))
                      (mockify (cddr lst)))
                'string))))

CL-USER> (mockify "meow")
((#\M . #\e) (#\O . #\w))
like image 466
jhsandoval Avatar asked Dec 05 '22 08:12

jhsandoval


1 Answers

Using MAP: we are creating a new string, moving over the original string and upcase/downcase based on an alternating boolean variable.

CL-USER 353 > (let ((string "stackoverflow")
                    (upcase t))
                (map (type-of string)
                     (lambda (element)
                       (prog1 (if upcase
                                  (char-upcase element)
                                (char-downcase element))
                         (setf upcase (not upcase))))
                     string))
"StAcKoVeRfLoW"
like image 83
Rainer Joswig Avatar answered Jan 17 '23 22:01

Rainer Joswig