如何在 Prolog 中编写对列表进行操作的函数 [英] How to program in Prolog a function that does operations on lists

查看:22
本文介绍了如何在 Prolog 中编写对列表进行操作的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Prolog 中制作一个包含 n 个 a 和 n 个 b 的程序,这里需要注意的是列表中 a 和 b 的数量必须相等,并且列表必须始终以 a 开头并以 b 结束,否则为假.示例:[a,b]true[a,a,a,b,b,b]true, [a,a,a,a]false 并且 [a,a,a,b,b] 也是.

How can I make a program in Prolog that contains n numbers of a and n numbers of b, it's important to note here that the number of a and b in the list must be equal, also the list must always start with a and finish with b, otherwise it's false. Example : [a,b] is true, [a,a,a,b,b,b] is true, [a,a,a,a] is false and [a,a,a,b,b] is also false.

这是我尝试做的:

langageB([b]).
langageB([b| S]):- langageB(S).

language([]).

langage([a,b]).
langage([a | S]):- langage(S).
langage([a| S]):- langageB(S).

但它并没有像我想要的那样工作.

But it does not work as I want it to.

推荐答案

使用DCG表示法,所需语言可以定义为:

Using DCG notation, the desired language can be defined as:

langage --> [a,b].
langage --> [a], langage, [b]. % For each a at the beginning of the list 
                               % there must be a corresponding b at the end

langage(List) :- phrase(langage, List).

例子:

?- langage([a,a,a,b,b,b]).
true .

?- langage([a,a,b,b,b]).
false.

?- langage(L).
L = [a, b] ;
L = [a, a, b, b] ;
L = [a, a, a, b, b, b] ;
L = [a, a, a, a, b, b, b, b] .

如果你想看如何直接使用差异列表定义谓词,可以列出谓词的子句langage/2:

If you want to see how to define the predicate directly using difference lists, you can list the clauses of the predicate langage/2:

?- listing(langage).

langage([a, b|A], A).

langage([a|A], B) :-
    langage(A, C),
    C=[b|B].

因此,另一种解决方案是:

So, an alternative solution is:

langage(List) :-
  langage(List, []).

langage([a, b|A], A).

langage([a|A], B) :-
    langage(A, C),
    C = [b|B].

这篇关于如何在 Prolog 中编写对列表进行操作的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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