1

I want to write a predicate containsOnly(X,Y), which returns true, if string X contains only characters from string Y.

I wrote it this way:

containsOnly([],_).
containsOnly([H|T],AcceptableCharacters) :- 
    member(H, AcceptableCharacters),
    containsOnly(T,AcceptableCharacters).

But the queries below return false. How can I modify the predicate in order for them to return true?

containsOnly('A', 'ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöüАБВГДЕЁЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзиклмнопрстуфхцчшщъыьэюя-').
containsOnly('a', 'ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÜabcdefghijklmnopqrstuvwxyzäöüАБВГДЕЁЖЗИКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзиклмнопрстуфхцчшщъыьэюя-').
Glory to Russia
  • 17,289
  • 56
  • 182
  • 325
  • 2
    Please first read the [related question](http://stackoverflow.com/q/8264699/1613573) about the difference between `'` and `"` in Prolog, and the important flag `double_quotes`. – mat Feb 05 '16 at 12:28

2 Answers2

1

working with atoms, as in your question, an ISO compliant solution:

containsOnly(X,Y) :- forall(sub_atom(X,_,1,_,C), sub_atom(Y,_,1,_,C)).

while SWI-Prolog ver. >= 7 seems to accept it for 'strings' also.

CapelliC
  • 59,646
  • 5
  • 47
  • 90
0

Your problem is the datatype. You use atoms, but you treat them as char/code lists. You can try use double quotes " instead of single quotes ' and see if this helps.

With SWI-Prolog 7 or later, it won't help. You would have to use backticks instead of double quotes.

You really should figure out the documentation and the datatypes though.

This is a list of codes in SWI-Prolog 7:

`абвгд`

And 0'x is Prolog notation for character codes:

?- X = 0'г.
X = 1075.

?- X = `абв`.
X = [1072, 1073, 1074].

Another thing: if you are using SWI-Prolog, you should use memberchk/2 instead of member/2 in this particular case. If this is an efficiency bottleneck, however, you might also consider using the method described at the very bottom of this page. (This whole section of the manual is very important if you are going to be dealing with text in your SWI-Prolog program.)

  • 2
    Your answer is specific to SWI7 only. For a solution that works in all systems including SWI7, see [this answer](http://stackoverflow.com/a/8269897/772868). – false Feb 05 '16 at 12:16
  • @false Yes, indeed. The question was tagged [swi-prolog], so I allowed myself this frivolity. –  Feb 06 '16 at 22:38