将列表中的某些字符复制到序言中的另一个字符 [英] Copy certain characters from a list to another on prolog
问题描述
所以我有这段代码,可以将列表中的所有内容复制到另一个列表中. 为了复制,我应该如何修改它,比如说前两个字符.
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).
我希望它是什么的示例:?-复制([a,b,c,d,e,f],X, 2 ). -> X = [a,b]
example of what i want it to be: ?- copy([a,b,c,d,e,f],X,2). --> X = [a,b]
推荐答案
您可以统一复制列表:
?- [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].
可以定义一个像您描述的谓词一样的谓词,它复制了列表的前N个元素:
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).
其工作方式如下:
?- first_n([a,b,c,d,e], 2, X).
X = [a, b].
有很多不同的方式来编写类似的谓词.我定义first_n/3
的方式,如果N大于List
的长度(在注释中@false指出),它将失败.可以改写通用功能的类似物 take ,如果N
的长度大于List
的长度,则会完全返回List
:
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)
).
这个答案在@false的有益批评的指导下得到了多次纠正.
这篇关于将列表中的某些字符复制到序言中的另一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!