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).

Namudon'tdie
  • 159
  • 6

2 Answers2

4
 (replace-regexp-in-string " " "" "Hello world")
  • 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 01 '21 at 14:49
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.

TerryTsao
  • 1,216
  • 5
  • 18