简体   繁体   中英

how can i call prolog rule while asking prolog

my_list([hello,hello,hello])

counthowmany(_, [], 0) :- !.
counthowmany(X, [X|Q], N) :- !, counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [_|Q], N) :- counthowmany(X, Q, N).

in the code above if ask Prolog after compile buffer

my_list(L),counthowmany(hello,L,N).

this question then it gives me the number of hello.....

now if i modify the code in the following way

my_list([hello,hello,hello])

counthowmany(_, [], 0) :- !.
counthowmany(X, [X|Q], N) :- !, counthowmany(X, Q, N1), N is N1+1.
counthowmany(X, [_|Q], N) :- counthowmany(X, Q, N).

numberofhello :- my_list(L), counthowmany(hello,L,N).

% i. e. I want to insert the question in a rule 

and after compile buffer (though i get a singleton variable warning) if i ask Prolog

numberofhello.

it just gives me "true" and i don't get the number of hello.

Your problem is the fact that your query ( numberofhello. ) does not have a variable (ie a "wh-word"), thus becomes "Can you count how many hellos?" yes-no question instead of "How many hellos". This should fix it:

numberofhello(N) :- my_list(L), counthowmany(hello, L, N).

With this,

?- numberofhello(N).

you should be getting your N = 3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM