Manipulating Strings: Yodaizer

Let’s make a function that talks like Yoda. It will take a sentence like “This is instructive” and output “Instructive, this is.”

To do this we’ll need to teach Emacs some adjectives:

1: (setq adjectives '("happy" "sad" "fun" "clever" "instructive"))

We’ll split the sentence into a list of words, and we’ll prepare an empty list for the result of the function:

1: let (  (result '())
2:         (words (split-string s))
3:      )

We’ll use a dolist macro to traverse the words, checking for adjectives, and we’ll use the old lisp trick of concatenating the word we’ve found at the front or the back of the result list, as appropriate.

1: (dolist (element words result)
2: (if (member element adjectives) (setq result (concat (capitalize element) ", " result)) (setq result (concat result " " element))  )
3: )

Lastly, we won’t forget to captalize the first word of the sentence and add a comma…

1: (concat (capitalize element) ", " result)

Put it together and we get the finished function:

 1: (defun yodaizer (s)
 2: "Moves adjective to the front of the sentence."
 3: (interactive "sInput a phrase:")
 4: (setq adjectives '("happy" "sad" "fun" "clever" "instructive"))
 5: 
 6: (let (  (result '())
 7:         (words (split-string s))
 8:      )
 9: (dolist (element words result)
10: (if (member element adjectives) (setq result (concat (capitalize element) ", " result)) (setq result (concat result " " element))  )
11: )
12: (message result)))

that was instructive

Instructive, that was

Next: Date and Time

Leave a Comment