English 中文(简体)
SWI-Prolog conditional statements
原标题:
  • 时间:2009-11-17 15:55:32
  •  标签:
  • prolog

I m trying to write a function that will test to see if the word hello is contained in a list. If it is contained, i don t want it to say "true", i want it to say : "yes, the word hello is contained here", any ideas?

Here s my code :

contains_hello([hello|_]).
contains_hello([Head|Tail]):- Head = hello, contains_hello(Tail).
问题回答

It is clear form your code that you only want the message to be printed once. Currently you solve this by adding Head = hello to the second clause. This is not how one usually solves this in Prolog.

Observe that your second clause excludes precisely that situation which is matched by the first clause. So, it is much more convenient to cut in the first clause. This stops backtracking. I.e., if the first clause matches, then the second clause will not be considered.

A cut is signified by the exclamation mark (!). Thus:

contains_hello([hello|_]) :-
  write( yes, the word hello is contained here ), nl, !.

contains_hello([_|T]) :- contains_hello(T).

This is untested but try:

contains_hello([hello|_]) :-
  write( yes, the word hello is contained here ),
  nl.
contains_hello([Head|Tail]) :- Head = hello, contains_hello(Tail).




相关问题
Prolog : Learning by example

I am trying to learn a little bit about swi-prolog (beyond the basic, useless programs). Can anyone explain (perhaps in pseudocode) what this sudoku solver and the related functions are doing? If ...

Working with lists in Prolog

First off let me state that this is part of a class exercise given as homework. But, the entire assignment is much more involved than the subject of this question. So.. I am searching through two ...

SWI-Prolog conditional statements

I m trying to write a function that will test to see if the word hello is contained in a list. If it is contained, i don t want it to say "true", i want it to say : "yes, the word hello is contained ...

prolog cut off in method

I have a question I would like to ask you something about a code snippet: insert_pq(State, [], [State]) :- !. insert_pq(State, [H|Tail], [State, H|Tail]) :- precedes(State, H). insert_pq(State, [...

Max out of values defined by prolog clauses

I know how to iterate over lists in Prolog to find the maximum, but what if each thing is a separate clause? For example if I had a bunch of felines and their ages, how would I find the oldest kitty? ...

热门标签