0

I wanted to define a function that removes all spaces from a given string:

(defun remove-whitespace (raw-string)
  (cl-reduce (lambda (acc char)
               (if (equal " " (char-to-string char))
                   acc
                 (concat acc char))) raw-string :initial-value " "))

However, evaluating (remove-whitespace "hello world") results in:

Debugger entered--Lisp error: (wrong-type-argument sequencep 104)
  concat(" " 104)
  (if (equal " " (char-to-string char)) acc (concat acc char))
  (lambda (acc char) (if (equal " " (char-to-string char)) acc (concat acc char)))(" " 104)
  cl-reduce((lambda (acc char) (if (equal " " (char-to-string char)) acc (concat acc char))) "hello world" :initial-value " ")
  remove-whitespace("hello world")

This is odd because the char code 104 must have been converted to a string by char-to-string. What am I missing?

Self-answer: It should have been (concat acc (char-to-string char)), not just (concat acc char).

0
2
(defun remove-whitespace (raw-string)
  (cl-reduce (lambda (acc char)
               (if (equal ?\s char)
                   acc
                 (concat acc (char-to-string char)))) raw-string :initial-value ""))

OR

(defun remove-whitespace (raw-string)
  (cl-reduce (lambda (acc char)
               (if (equal " " (char-to-string char))
                   acc
                 (concat acc (char-to-string char)))) raw-string :initial-value ""))

NOTE that char is an integer, therefore you can't concat it.

1
  • You're right! It was a simple type error. Jun 1 at 5:00
4
 (replace-regexp-in-string " " "" "Hello world")
1
  • 1
    Note that starting in emacs-28 you're be able to use 'string-replace' if you just want to replace a fixed string with another fixed string
    – rpluim
    Jun 1 at 14:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.