Prolog 中的条件语句 [英] Conditional Statements in Prolog

查看:54
本文介绍了Prolog 中的条件语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 prolog,想知道我们是否也可以在 Prolog 中实现像 (if.​​else) 这样的条件语句,如果可以,如何实现?有人可以在 Prolog 中实现此代码仅作为示例-

I have just started prolog and was wondering if we can implement conditional statements like(if.else)in Prolog also and if so how?? Can someone implement this code in Prolog just for an example-

if(a==2)
 print("A is 2");
if(a==3)
 print("A is 3");
else
 print("HAhahahahaah");

好的,所以我在 Sergey Dymchenko 回答之后这样做.

Ok so I am doing this after Sergey Dymchenko answer.

Test(A) :-read(A),
 ( A =:= 2 ->
    write('A is 2')
 ;
    ( A =:= 3 ->
        write('A is 3')
    ;
        write('HAhahahahaah')
    )
 ).

这给出了正确的答案,除了这显示 A = 2 也是我不想要的(如果我给出输入 2).

This is giving right answer except this is displaying A = 2 also which I dont want(If I give input 2).

推荐答案

一种方法:

test(A) :-
    (   A =:= 2 ->
        write('A is 2')
    ;   A =:= 3 ->
        write('A is 3')
    ;   write('HAhahahahaah')
    ).

另一种方法:

test(2) :-
    write('A is 2').
test(3) :-
    write('A is 3').
test(A) :-
    A \= 2, A \= 3,
    write('HAhahahahaah').

这两个代码有区别,比如选择点、A未实例化时的行为以及A是否被视为数字.但是两者都以相同的方式工作(除了左边的选择点)和查询 test(2)., test(3)., test(42).).

There are differences with these two codes, like choice points, behavior when A is not instantiated, and if A is treated as a number or not. But both will work the same way (except choice points left) and as expected with queries test(2)., test(3)., test(42).

这篇关于Prolog 中的条件语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆