【问题标题】:Return List which element belongs to up until the element position [duplicate]返回列表直到元素位置为止属于哪个元素[重复]
【发布时间】:2018-05-05 16:40:54
【问题描述】:

我想构建一个谓词,给定列表的List 和坐标X 的Element,检查X 是否属于该主列表中的任何列表,如果它属于任何列表,则返回ReturnList作为一个列表,直到找到元素 X 的位置为止。

例如,给定;

?-checklist((3,4),[[(1,3), (1,2), (1,1)],[(1,4), (2,4), (3,4), (4,4)]], ReturnList)

返回

ReturnList = [(1,4), (2,4), (3,4)]

我正在尝试实现这一点,到目前为止我已经

get_list([],_,[]).
get_list([List], Element, ReturnList):- 
  member(List, Element),
  get_list(List|Rest, Element, List).

但这是我的第一个序言程序之一,我发现很难掌握逻辑

【问题讨论】:

    标签: list prolog


    【解决方案1】:

    我的解决方案(使用 cmets)使用 Prolog 内置函数 member/2append/3

    checklist(Elem, List, ReturnList) :-
        member(SubList, List),          % SubList is contained in List
        member(Elem, SubList),          % Elem is contained in SubList
        append(ReturnList, _, SubList), % ReturnList is a prefix of SubList
        append(_, [Elem], ReturnList).  % Elem is the last element of ReturnList
    

    测试:

    ?- checklist((3,4),[[(1,3), (1,2), (1,1)],[(1,4), (2,4), (3,4), (4,4)]], ReturnList).
    ReturnList = [(1, 4),  (2, 4),  (3, 4)] ;
    false.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 2021-12-04
      • 2020-07-31
      相关资源
      最近更新 更多