【问题标题】:Prolog, access specific member of list?Prolog,访问列表的特定成员?
【发布时间】:2012-10-17 16:55:39
【问题描述】:

谁能告诉我如何访问序言中列表的特定成员?比如说我需要访问传递给规则的列表的第 3 个或第 4 个元素?

【问题讨论】:

    标签: list prolog unification


    【解决方案1】:

    nth0(Ind, Lst, Elem) 或 nth1(Ind, Lst, Elem) 使用 SWI-Prolog,nth0 第一个元素的索引为 0。

    例如,

    nth0(3, [a, b, c, d, e], Elem). %Binds d to Elem
    nth1(3, [a, b, c, d, e], Elem). %Binds c to Elem
    
    nth0(Ind, [a, b, c, d, e], d).  %Binds 3 to Ind
    nth0(3, [a, b, c, X, e], d).    %Binds d to X
    
    nth0(3, [a, b, c, d, e], c).    %Fails.
    

    【讨论】:

    • 所以如果制定一个规则,需要将某些东西与传入的列表的某些元素统一起来,我将如何使用它?
    • 这里是使用示例?- L = [a,b,c], nth0(Ind, L, a),nth0(2, L, X)。 L = [a,b,c],Ind = 0,X = c。或 ?- L = [a,b,c], nth1(Ind, L, a), nth1(2, L, X)。 L = [a,b,c],Ind = 1,X = b。
    【解决方案2】:

    当您需要访问的索引非常小时,您可以使用模式匹配。假设我们需要第三个或第四个元素:

    third([_,_,E|_], E).
    fourth([_,_,_,E|_], E).
    

    如果使用“内联”,当列表包含与位置相关的信息时,这可能会更有用。比如

    your_rule([_,_,E|Rest], Accum, Result) :-
       Sum is Accum + E,
       your_rule(Rest, Sum, Result).
    ...
    

    【讨论】:

      【解决方案3】:

      序言列表是经典列表。访问不是直接的。你必须迭代才能找到你需要的东西。

      你可以这样得到第n个元素:

      foo( [X1,X2,X3,X4,...,XN|Xs] ) :- ...
      

      其中 [code]X[/code]n 是列表的第 nth 个元素。 n 大于一个小的值是不切实际的。这大致类似于 C/C++ 指针表达式:

      LLNode *nthElement = root->next->...->next ;
      

      否则,您必须使用内置谓词或自制谓词遍历列表以找到所需的元素,例如:

      foo(Xs) :- nth_element(Xs,9,X) , ...

      nth_element(Xs,N,X) :- nth_element(Xs,0,N,X) .

      nth_element([X|Xs],N,N,X) :- !. nth_element([_|Xs],T,N,X) :- T1 是 T+1 , nth_element(Xs,T1,N,X)。

      【讨论】:

        【解决方案4】:

        使用 SWI-Prolog 的 func 库,可以以更简洁的方式编写列表推导:

        :- use_module(library(func)).
        
        nth0((Index, List), Result) :-
            nth0(Index,List,Result).
        

        现在,您可以访问列表的两个元素并将它们添加在一起,如下所示:

        example :-
            List = [1,5,12,9],
            Y is (nth0 $ (0, List)) + (nth0 $(3,List)), %add the 1st and 4th elements of this list
            writeln(Y). %prints 10
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-11
          • 1970-01-01
          • 1970-01-01
          • 2012-08-07
          • 1970-01-01
          相关资源
          最近更新 更多