string – Normalizing space characters in Prolog atoms – Education Career Blog

What is the best way to normalize whitespace characters (space, newline, tab) in a Prolog atom, e.g. in SWI-Prolog.
I.e. I would like to have a rule:

normalize_space_in_atom(+Atom1, -Atom2)

such that Atom2

  • has any sequence of whitespace characters turned into a single space
  • starts with a non-space
  • ends with a non-space


SWI Prolog provides normalize_space/2, and so you could define your predicate as follows:

normalize_space_in_atom(A1,A2) :- normalize_space(atom(A2),A1).

I’ve tried this out with SWI Prolog 5.7.5 and it appears to work. You could add more error handling if you wish.

Leave a Comment