Search code examples
prologdcg

Why do some DCG test cases use assertion( Rest == [])?


This answer uses assertion( Rest == [] )?

pharse/3 is

phrase(:DCGBody, ?List, ?Rest)

Since phrase/2 is equivalent to phrase(DCGBody, InputList, []). which is just Rest = [] and in the test case Rest == [], whats the point? What benefit does adding assertion( Rest == [] ) give?


Solution

  • phrase(GB__2, Xs, []) is equivalent to phrase(GB__2, Xs) but it is not necessarily the case that the first solution of phrase(GB__2, Xs0,Xs) will be Xs == [].

    Here is a minimal example:

    :- set_prolog_flag(double_quotes, chars).
    
    ao1 --> "a" | [].
    
    ao2 --> [] | "a".
    

    While phrase(aoX, "a") just succeeds for both, phrase(aoX, "a", Xs) shows a difference in the sequence of solutions found.

    ?- phrase(ao1, "a", Xs).
       Xs = "a"
    ;  Xs = [].
    ?- phrase(ao2, "a", Xs).
       Xs = []
    ;  Xs = "a".