问题描述
我想做的是在任何谓词为真时在控制台上写一些东西.一个例子是:
write('hello') IF 成员('a',['a','b']).
一个连词 a, b
为真(成功)如果 a
为真,并且 b
是真的.顺序很重要:
写hello"并检查x
是否在[a,b]
?- write(hello), member(x, [a,b]).你好错误的.
检查x
是否在[a,b]
中,如果是就写hello"
?- member(x, [a,b]), write(hello).错误的.
检查a
是否在[a,b]
中,如果是,写hello"
?- member(a, [a,b]), write(hello).你好 % 按 Enter真的 .
if-then-else 结构 Condition ->然后 ;Else
略有不同,仅根据您的问题,我不知道您是否真的需要它.例如,为了避免这些示例中的额外选择点,您可能需要这样写:
?- memberchk(a, [a,b]), write(hello).你好真的.
当然,您实际上可能需要查看每个成员.例如:
只打印字符列表中的大写字母
?- member(X, [a, b, 'C', 'D', e, f, 'G']), char_type(X, upper).X = 'C' ;X = 'D' ;X = 'G'.
你应该仔细看看这个.没有if-then-else,也没有打印.我几乎可以说您正在尝试解决一个非问题.一般而言,您不应该经常需要 if-then-else 或使用 write
或 format
打印.
if-then-else 可以通过使用为您做的谓词来避免,如上所示的 member/2
与 memberchk/2
.
打印由顶层完成.我很难想出 write
和 format
的有效用法,除非您需要写入文件/流.即便如此,先准备好最终结果,然后一次性将其写入文件也更清晰、更容易.
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']).
A conjunction a, b
is true (succeeds) if a
is true, and b
is true. The order is significant:
?- write(hello), member(x, [a,b]).
hello
false.
?- member(x, [a,b]), write(hello).
false.
?- 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:
?- 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.
这篇关于模拟if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!