Tuesday, April 5, 2011

Normalizing space characters in Prolog atoms

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
From stackoverflow
  • 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.

    Kaarel : Thanks, works in 5.6.61 as well. I can't believe I couldn't find it in the documentation.

0 comments:

Post a Comment