Prolog-返回包含特定元素的列表? [英] Prolog - Return a list with specific elements?
问题描述
我正在尝试学习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显示一个,然后跳过一个,然后连续执行此操作. 这是我所做的,但这是不正确的.
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屋!