Concatenation of Lists in Prolog

前端 未结 4 652
失恋的感觉
失恋的感觉 2021-01-11 10:16

Can someone help me find the error in these rules?

concat([], List, List).
concat([Head|[]], List, [Head|List]).
concat([Head|Tail], List, Concat) :- concat(         


        
相关标签:
4条回答
  • 2021-01-11 10:30

    To fix your code, the way you intended it, you just need to transform Head into [Head] in your last call to concat/3 in your last clause. The problem was that you called your predicate with Head only as first argument, which is not a list.

    Though, here are several notes :

    • [Head|[]] is equivalent to [Head]
    • your algorithm has a poor complexity, n! I believe.
    • with no cut inserted after your second clause, you generate infinite choice points through the call of your third clause with a list of length 1 (that hence calls your second clause, that then is ran through your third clause, etc... infinite loop).

    Here is SWI-pl's version, to hint you towards good prolog recursion :

    append([], List, List).
    append([Head|Tail], List, [Head|Rest]) :-
        append(Tail, List, Rest).
    

    You can find other resources on recent posts here or in Learn Prolog Now! tutorial if you want to learn how to use recursion properly.

    0 讨论(0)
  • 2021-01-11 10:32

    It can be done by using append.

    concatenate(List1, List2, Result):-
       append(List1, List2, Result).
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-11 10:44

    The implementation is very simple. concatenation is nothing but appending the second list at the end of the first list. Keep on adding until the first list runs out of elements. Now add the second list to it.

    ap([],L,L).
    ap([H|T],L,[H|Z]):- ap(T,L,Z).
    

    OUTPUT

    ?-ap([1,2,3],[a,b,c],List).
      List=[1,2,3,a,b,c]
    
    ?-ap([1,2,3],[a,b],List).
      List=[1,2,3,a,b]
    
    ?-ap([1,2],[a,b,c],List).
      List([1,2,a,b,c])
    
    ?-ap([],[],List).
      List=[]
    
    0 讨论(0)
  • 2021-01-11 10:51

    Here is the concatenation between two lists rule:

    concat([],L2,L2). concat([Head|Tail],L2,[Head|L3]) :- concat(Tail,L2,L3). 
    
    0 讨论(0)
提交回复
热议问题