Prolog - 返回包含特定元素的列表? [英] Prolog - Return a list with specific elements?

查看:21
本文介绍了Prolog - 返回包含特定元素的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力学习 Prolog,并且一直在做一些练习.

I am trying to learn Prolog and I've been doing some exercises.

有一个包含学生姓名的列表.编写谓词 filter(L,LN) 以返回名为 LN 的第二个列表,其中包括如下名称:

There is a list with student's names. Write the predicate filter(L,LN) that returns a second list named LN which includes the names like this:

?- filter([kostas, dimitris, anna, antonis, antonia], LN).
LN = [kostas, anna, antonia]

所以..它显示一个然后跳过一个并连续执行此操作.这是我所做的,但它不正确.

So..it shows one and then skips one and does this continuously. This is what I've done but it isn't correct.

filter([],[]).
filter([H|T],[H|LN]) :-
    filter(T,LN,0).

filter([H|T],[H|LN],C) :-
    0 is C mod 2, 
    append(H,LN),
    C = C + 1, 
    filter(T,LN,C). 
filter([H|T],LN,C) :-
    (C/2) = 0,
    C = C + 1,
    filter(T,LN,C).

推荐答案

使用 DCG 让您的生活更轻松的众多案例之一:

One of the many cases when using a DCG makes your life much easier:

s([]) --> [].
s([X|Xs]) --> [X], t(Xs).

t([]) --> [].
t(Xs) --> [_], s(Xs).

filter_dcg(List, Filtered) :-
    phrase(s(Filtered), List).

如果没有 DCG,这将类似于:

Without a DCG, this would look something like:

q([], []).
q([X|Xs], [X|Ys]) :-
    r(Xs, Ys).

r([], []).
r([_|Xs], Ys) :-
    q(Xs, Ys).

filter_pred(List, Filtered) :-
    q(List, Filtered).

这里的主要信息是,您想要实现的目标很容易实现为具有两种状态的状态机.它们中的每一个都转换到另一个,一个保留其输入,另一个将其丢弃.

The take home message here is that what you are trying to achieve is easily implemented as a state machine with two states. Each of them transitions to the other, one keeps its input and the other one throws it away.

这篇关于Prolog - 返回包含特定元素的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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