Simulate if statement [duplicate]

2019-09-16 09:20发布

This question already has an answer here:

What I'm trying to do is to write something on the console if any predicate is true.An example would be:

write('hello') IF member('a',['a','b']).

标签: prolog
2条回答
冷血范
2楼-- · 2019-09-16 09:51

A conjunction a, b is true (succeeds) if a is true, and b is true. The order is significant:

Write "hello" and check if x is in [a,b]

?- write(hello), member(x, [a,b]).
hello
false.

Check if x is in [a,b], and if it is, write "hello"

?- member(x, [a,b]), write(hello).
false.

Check if a is in [a,b], and if it is, write "hello"

?- member(a, [a,b]), write(hello).
hello % press Enter
true .

The if-then-else construct Condition -> Then ; Else is something slightly different and based on your question alone, I don't know if you really need it. For example, to avoid the extra choice point in these examples, you might want to write:

?- memberchk(a, [a,b]), write(hello).
hello
true.

Of course, you might actually need to look at each member. For example:

Print out only the capital letters in a list of chars

?- member(X, [a, b, 'C', 'D', e, f, 'G']), char_type(X, upper).
X = 'C' ;
X = 'D' ;
X = 'G'.

You should look at this carefully. There is no if-then-else, nor printing. I'd almost say that you are trying to solve a non-problem. Very generally speaking, you shouldn't need if-then-else or printing with write or format too often.

The if-then-else can be avoided by using predicates that do it for you, as member/2 vs. memberchk/2 shown above.

The printing is done by the top level. I have trouble coming up with valid uses of write and format, unless you need to write to a file/stream. Even then, it is cleaner and easier to first get the final result ready, then write it to a file in one go.

查看更多
冷血范
3楼-- · 2019-09-16 10:02

You could write:

 ?- member('a',['a','b']) -> write('hello').
 hello
 true.

or define a clause:

write:-member('a',['a','b']) -> write('hello').

and query:

?- write.
hello
true.
查看更多
登录 后发表回答