Copy certain characters from a list to another on prolog

点点圈 提交于 2019-12-11 02:09:26

问题


So i have this code which copies everything from a list to another one. How should I modify it in order to copy, lets say the first two character.

$copy(L,R) :- 
    copy2(L,R).
copy2([X],[X]).
copy2([H|T1],[H|T2]) :-
    copy2(T1,T2).

example of what i want it to be: ?- copy([a,b,c,d,e,f],X,2). --> X = [a,b]


回答1:


You can copy lists just with unification:

?- [a,b,c,d,e] = List.
List = [a, b, c, d, e].

?- [a,b,c,d,e] = [V,W,X,Y,Z].
V = a,
W = b,
X = c,
Y = d,
Z = e.

?- [a,b,c,d,e] = [V,W|Rest].
V = a,
W = b,
Rest = [c, d, e].

A predicate like the one you describe, copying the first N elements of a list, can be defined thus:

first_n(List, N, Xs) :-
    length(Xs, N),
    append(Xs _, List).

Which works like so:

?- first_n([a,b,c,d,e], 2, X).
X = [a, b].

There are a bunch of different ways to write a similar predicate. The way I have defined first_n/3, it will fail if N is larger than the length of List (this was pointed to out by @false in the comments). One could instead write an analog of the common function take, which will return List in its entirety in the event that N is greater than List's length:

take_n(N, List, Taken) :-
    ( length(List, M),
      N > M
    ->
      Taken = List
    ;
      length(Taken, N),
      append(Taken, _, List)
    ).

This answer was corrected (several times) under the guidance of @false's helpful criticism.



来源:https://stackoverflow.com/questions/25633690/copy-certain-characters-from-a-list-to-another-on-prolog

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!