0

I would like to trim right whitespace from strings for example. "Dog " becomes "Dog" , " " becomes "". How could this be achieved?

I know SWI prolog has trim whitespace predicate however it trims String from right and left.

However I am also using GNU prolog so looking to write my own solution.

Mandy
  • 145
  • 6
  • 1
    As a follow-on to [yesterday's question](https://stackoverflow.com/questions/55365567/how-to-use-read-line-to-codes-atom-codes-iteratively-to-generate-array-of-line), let me reiterate that it would be a good idea to investigate [tag:dcg]s and try solving your problem holistically in a new way, rather than getting frustrated trying to convert your Python or whatever directly to Prolog. – Daniel Lyons Mar 28 '19 at 15:21

3 Answers3

1

You can convert a string into a list of characters (see convert string to list in prolog), write a predicate to manipulate it however you want, and then convert the resulting list back to a string.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • Alternatively, [`:- set_prolog_flag(double_quotes, chars).`](https://stackoverflow.com/a/8269897/772868) In this manner it is true that `"abc" = [a,b,c].` – false Mar 28 '19 at 17:13
0

Here's how to accomplish this using a DCG in SWI-Prolog. I know you said you're using GNU Prolog, but maybe this will at least be helpful for others using SWI-Prolog:

:- use_module(library(dcg/basics)).

trimmed(S) --> blanks, string(S), blanks, eos, !.

trim(S, T) :-
  string_codes(S, C), phrase(trimmed(D), C), string_codes(T, D).
Adam Dingle
  • 3,114
  • 1
  • 16
  • 14
0

GNU Prolog is one of the supported Logtalk backend compilers. With it, you gain access to (portable) libraries (and developer tools!) that allows you to easily solve the problem. For example, if your strings are represented using atoms, you can use the atom::replace_sub_atom/4 predicate:

| ?- {types(loader)}.
...
yes

| ?- atom::replace_sub_atom(' ', '', 'Dog ', Output).          

Output = 'Dog'

yes
| ?- atom::replace_sub_atom(' ', '', ' becomes ', Output).

Output = becomes

If instead you're using double-quoted terms, their meaning depends on the double_quotes flag value, In this case, you can use the list::subtract/3 predicate. For example:

| ?- current_prolog_flag(double_quotes, Value).

Value = codes

yes

yes
| ?- list::subtract("Dog ", " ", Output).

Output = [68,111,103]

yes
| ?- list::subtract(" becomes ", " ", Output).

Output = [98,101,99,111,109,101,115]

yes

| ?- set_prolog_flag(double_quotes, chars).

yes
| ?- list::subtract("Dog ", " ", Output).

Output = ['D',o,g]

yes
| ?- list::subtract(" becomes ", " ", Output).

Output = [b,e,c,o,m,e,s]

yes

| ?- set_prolog_flag(double_quotes, atom).    

yes
| ?- atom::replace_sub_atom(" ", "", "Dog ", Output).

Output = 'Dog'

yes
| ?- atom::replace_sub_atom(" ", "", " becomes ", Output).

Output = becomes

yes
Paulo Moura
  • 18,373
  • 3
  • 23
  • 33