Search code examples
prologdcg

How to code a prolog program that does some operations on list


I want to program a list that uses only the characters {a, b}.

My objective is that Prolog returns true only if the list that the user enter contains n number of a, or at least one a but has to finish with one b only, no more and no less than just one b.

Example: aaab is correct, aba is incorrect, b is incorrect, a is incorrect.

Here's my code :

langage([]).
langage([a | S]):-
    langage(S).

The problem here is that it only accepts n numbers of a, and does not finish with b. But I want it to finish with the letter b.

I hope someone can help me.


Solution

  • You could write it like this:

    langage([a,b]).
    langage([a | S]):-
        langage(S).
    

    So your list needs to end on a and b, any leading a's will be stripped by the second rule. Tested with SWISH:

    ?- langage([a,a,a,b]).
    true;
    false.
    
    ?- langage([a,b,a]).
    false.
    
    ?- langage([a]).
    false.
    
    ?- langage([b]).
    false.
    

    However, if you wanted to have a list starting with a with n>=1 follow up b, try this (not tested):

    langageB([b]).
    langageB([b| S]):-
        langageB(S).
    
    langage([a| S]):-
        langageB(S).