没有 if 和 else 语句的 Prolog [英] Prolog without if and else statements

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

问题描述

我目前正在尝试学习一些基本的序言.随着我的学习,我想远离 if else 语句以真正理解该语言.不过,我在这样做时遇到了麻烦.我有一个看起来像这样的简单函数:

I am currently trying to learn some basic prolog. As I learn I want to stay away from if else statements to really understand the language. I am having trouble doing this though. I have a simple function that looks like this:

if a > b then 1
else if
   a == b then c
else
    -1;;

这只是我想转换成序言的非常简单的逻辑.

This is just very simple logic that I want to convert into prolog.

所以在这里我很困惑.我想先检查是否 a > b,如果是,则输出 1.我是否只需这样做:

So here where I get very confused. I want to first check if a > b and if so output 1. Would I simply just do:

sample(A,B,C,O):-
   A > B, 1,
   A < B, -1,
   0.

这就是我想出的.o 作为输出,但我不明白如何使 1 成为输出.有什么想法可以帮助我更好地理解这一点吗?

This is what I came up with. o being the output but I do not understand how to make the 1 the output. Any thoughts to help me better understand this?

在尝试了更多之后,我想出了这个,但它似乎不正确:

After going at it some more I came up with this but it does not seem to be correct:

Greaterthan(A,B,1.0).
Lessthan(A,B,-1.0).
Equal(A,B,C).

Sample(A,B,C,What):-
    Greaterthan(A,B,1.0),
    Lessthan(A,B,-1.0),
    Equal(A,B,C).

我是否走在正确的轨道上?

Am I headed down the correct track?

推荐答案

您的代码同时存在语法和语义问题.

Your code has both syntactic and semantic issues.

谓词以小写开头,逗号表示连词.也就是说,您可以将您的子句解读为

Predicates starts lower case, and the comma represent a conjunction. That is, you could read your clause as

sample(A,B,C,What) if
    greaterthan(A,B,1.0) and lessthan(A,B,-1.0) and equal(A,B,C).

然后请注意,What 参数是无用的,因为它没有获得值 - 它被称为单例.

then note that the What argument is useless, since it doesn't get a value - it's called a singleton.

一种可能的写析取方式(即 OR)

A possible way of writing disjunction (i.e. OR)

sample(A,B,_,1) :- A > B.
sample(A,B,C,C) :- A == B.
sample(A,B,_,-1) :- A < B.

注意测试 A <B 来保护值-1 的赋值.这是必要的,因为如果需要,Prolog 将执行 all 子句.强制 Prolog 避免某些我们知道应该完成的计算的基本结构是 cut:

Note the test A < B to guard the assignment of value -1. That's necessary because Prolog will execute all clause if required. The basic construct to force Prolog to avoid some computation we know should not be done it's the cut:

sample(A,B,_,1) :- A > B, !.
sample(A,B,C,C) :- A == B, !.
sample(A,B,_,-1).

无论如何,我认为您应该使用 if/then/else 语法,即使在学习时也是如此.

Anyway, I think you should use the if/then/else syntax, even while learning.

sample(A,B,C,W) :- A > B -> W = 1 ; A == B -> W = C ; W = -1.

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

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