Search code examples
prologprolog-anonymous-variable

Different answers when using anonymous variable and "normal" variable in Prolog


I have the following database:

vegetarian(jose).
vegetarian(james).
vegetable(carrot).
vegetable(egg_plant).
likes(jose,X):-vegetable(X).
loves(Who,egg_plant):-vegetarian(Who).

When I do the query vegetarian(_). I was expecting to get _ = jose; _ = james. but I am instead getting true; true.

If I instead do vegetarian(X)., then I get the expected answer X = jose; X = james. Why this difference?


Solution

  • If you're using SWI-Prolog, you can control this with the flag toplevel_print_anon). However, a name consisting of a single underscore (_) is special and never prints.

    $ swipl dd.pl
    Welcome to SWI-Prolog (threaded, 64 bits, version 8.3.16)
    SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
    Please run ?- license. for legal details.
    
    For online help and background, visit https://www.swi-prolog.org
    For built-in help, use ?- help(Topic). or ?- apropos(Word).
    
    ?- set_prolog_flag(toplevel_print_anon, true).
    true.
    
    ?- vegetarian(_X).
    _X = jose ;
    _X = james.
    
    ?- vegetarian(_).
    true ;
    true.
    
    ?- set_prolog_flag(toplevel_print_anon, false).
    true.
    
    ?- vegetarian(_X).
    true ;
    true.