简体   繁体   English

在Prolog中删除列表的第一个元素

[英]Removing first elements of a list in Prolog

my problem is how to remove first elements of a list until an element (first occurrence). 我的问题是如何删除列表中的第一个元素,直到一个元素(第一次出现)。 The list can have repeated elements. 该列表可以包含重复的元素。

Eg 例如

?- L = [a, b, c, a, c, d], remove_elements(c, L, Result).
Result = [c, a, c, d].

What I have so far is this: 我到目前为止所拥有的是:

remove_elements(Element, [], []).
remove_elements(Element, [Element|Tail], [Tail]).
remove_elements(Element, [Head|Tail], [Tail]) :-
    Head \== Element,
    remove_elements(Element, Tail, Tail).

I cannot use any library. 我不能使用任何图书馆。

If the Element is in the first position, the solution is correct but if it's in the middle it fails. 如果Element在第一个位置,则解决方案是正确的,但如果在中间,则解决方案将失败。

Thanks 谢谢

Just little corrections, be careful with unification. 只需进行少量更正,请小心统一。

remove_elements(Element, [], []).
remove_elements(Element, [Element|Tail], [Element|Tail]).
remove_elements(Element, [Head|Tail], List) :- 
                Head \== Element, remove_elements(Element, Tail, List).

Terms S and T are unifiable if: 如果满足以下条件,则术语S和T是不可更改的:

  • S a T are identical constants S a T是相同的常数
  • S a T are (free) variables (S and T are made equal (they co-refer)) S a T是(自由)变量(S和T相等(它们共同引用))
  • S is a variable, T is a term ≠ variable (term T is substituted to variable S) S是变量,T是项≠变量(项T替换为变量S)
  • T is a variable, S is a term ≠ variable (term S is substituted to variable T) T是变量,S是项≠变量(项S替换为变量T)
  • S a T are compound terms (with identical main functor, corresponding arguments are unifiable) S a T是复合项(具有相同的主函子,对应的论点不可确定)

Examples: 例子:

?- f(X,a(b,c)) = f(d,a(Y,c)).

X = d, Y = b. X = d,Y = b。

?- f(X,a(b,c)) = f(Y,a(Y,c)).

X = Y = b X = Y = b

?- f(c,a(b,c)) = f(Y,a(Y,c)).

false. 假。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM