Prolog: removing extra spaces in a character stream

Total newb for Prolog. It disappoints me a little. My "solution" is below - I'm trying to make Prolog procedural ...

This will remove the spaces or add a space after the decimal point, if necessary, that is, until a period occurs:

squish:-get0(C),put(C),rest(C). rest(46):-!. rest(32):-get(C),put(C),rest(C). rest(44):-put(32), get(C), put(C), rest(C). rest(Letter):-squish. 

PURPOSE: I am wondering how to remove spaces before the comma.

The following works, but it is so wrong on so many levels, especially in "exit"!

 squish:- get0(C), get0(D), iteratesquish(C,D). iteratesquish(C,D):- squishing(C,D), get0(E), iteratesquish(D,E). squishing(46,X):-put(46),write('end.'),!,exit. squishing(32,32):-!. squishing(32,44):-!. squishing(32,X):-put(32),!. squishing(44,32):-put(44),!. squishing(44,44):-put(44), put(32),!. squishing(44,46):-put(44), put(32),!. squishing(44,X):-put(44), put(32),!. squishing(X,32):-put(X),!. squishing(X,44):-put(X),!. squishing(X,46):-put(X),!. squishing(X,Y):-put(X),!. 
+4
source share
1 answer

As you are describing lists (in this case: character codes), consider using a DCG entry. For example, so that any comma is followed by a single space, use code similar to:

 squish([]) --> []. squish([(0',),(0' )|Rest]) --> [0',], spaces, !, squish(Rest). squish([L|Ls]) --> [L], squish(Ls). spaces --> [0' ], spaces. spaces --> []. 

Request example:

 ?- phrase(squish(Ls), "a, b,c"), format("~s", [Ls]). a, b, c 

So, first focus on a clear declarative description of the relationship between sequences of characters and the desired β€œclean” string. Then you can use the SWI-Prolog (pio) library to read from files through these grammar rules. To remove all spaces preceding the comma, you only need to add one rule in the DCG above (to squish // 1), which I leave as an exercise for you. Of course, of course, if the comma is followed by another comma, and in this case the requirements are contradictory :-)

+4
source

Source: https://habr.com/ru/post/1333921/


All Articles