2

Typing "prolog" in terminal gets:

GNU Prolog 1.3.0

By Daniel Diaz

Copyright (C) 1999-2007 Daniel Diaz

| ?- 

Typing:

| ?- member(2, [1,2,3]).

Gets:

true ? 

Then pressing enter gets:

yes

Typing:

| ?- member(4, [1,2,3]).

gets:

no

When i write a file; test.pl consisting of this:

:- member(4, [1,2,3]), nl, halt.

And then write in the terminal:

| ?- [test2].

I get:

compiling /path/test.pl for byte code...
/path/test.pl:1: warning: unknown directive (',')/2 - maybe use initialization/1 - directive ignored
/path/test.pl compiled, 1 lines read - 139 bytes written, 11 ms

yes

Shouldnt the answer here be no? What am i doing wrong. Also, how would you do this in prolog:

if (testInPrologTerminal(member(4, [1,2,3])) { do this; } 

I.e, i want to send queries to the prolog top level, and get an answer

false
  • 10,264
  • 13
  • 101
  • 209
user3573388
  • 191
  • 1
  • 6

1 Answers1

3

When you type the query member(2, [1,2,3]), GNU Prolog prompts you for a possible additional solution (hence the true ? prompt) as only by backtracking (and looking to the last element in the list, 3) it could check for it. When you press enter, you're telling the top-level interpreter that you are satisfied with the current solution (the element 2 in the list second position). The second query, member(4, [1,2,3]), have no solutions so you get a no.

To execute a query when a file is loaded, the standard and portable way of doing it, is to use the standard initialization/1 directive. In this case, you would write:

:- initialization((member(4, [1,2,3]), nl, halt)).

Note the ()'s surrounding the query, otherwise you may get a warning about an unknown initialization/3 standard, built-in, control construct. If you have more complex queries to be executed when a file is loaded, then define a predicate that makes the queries a call this predicate from the initialization/1 directive. For example:

main :-
    (   member(4, [1,2,3]) ->
        write('Query succeeded!'), nl
    ;   write('Query failed!'), nl
    ).

:- initialization(main).

Writing arbitrary queries as directives in a source file is legacy practice and thus accepted by several Prolog implementations but using the initialization/1 directive is the more clean, standard, and portable alternative.

Paulo Moura
  • 18,373
  • 3
  • 23
  • 33
  • 1
    Why "trying to redefine the (',')/2 standard built-in"? Without the additional parentheses it seems just as (unknown) initialization/3 call – user396672 Sep 11 '14 at 11:25