Prolog:取第一个“N";列表的元素 [英] Prolog: Take the first "N" elements of a list
问题描述
我需要编写一个 Prolog 谓词 take(L, N, L1)
如果列表 L1
包含第一个 N
元素以相同的顺序列出 L
.例如:
I need to write a Prolog predicate take(L, N, L1)
which succeeds if list L1
contains the first N
elements of list L
, in the same order. For example:
?- take([5,1,2,7], 3, L1).
L1 = [5,1,2]
?- take([5,1,2,7], 10, L1).
L1 = [5,1,2,7]
到目前为止,Prolog 对我来说意义不大,我很难分解它.这是我目前所拥有的:
Prolog thus far is making little sense to me, and I'm having a hard time breaking it down. Here is what I have so far:
take([H|T], 0, []).
take([H|T], N, L1) :-
take(T, X, L2),
X is N-1.
你能解释一下我在这里做错了什么吗?
Can you please explain what I did wrong here?
推荐答案
这是一个在 Haskell1 等函数式语言中实现 take
的对应关系的定义.首先,参数顺序应该不同,这有利于部分应用.有一个切入点,但只有在错误检查内置 (=<)/2
产生 instantiation_error
参数应该包含变量之后.
Here is a definition that implements the relational counterpart to take
in functional languages like Haskell1. First, the argument order should be different which facilitates partial application. There is a cut, but only after the error checking built-in (=<)/2
which produces an instantiation_error
should the argument contain a variable.
take(N, _, Xs) :- N =< 0, !, N =:= 0, Xs = [].
take(_, [], []).
take(N, [X|Xs], [X|Ys]) :- M is N-1, take(M, Xs, Ys).
?- take(2, Xs, Ys).
Xs = [], Ys = []
; Xs = [_A], Ys = [_A]
; Xs = [_A,_B|_C], Ys = [_A,_B].
注意上面的查询是如何读取的:
Note how above query reads:
如何从Xs
中取出2个元素得到Ys
?
How can one take 2 elements from
Xs
to getYs
?
并且有 3 个不同的答案.如果 Xs
为空,那么 Ys
也是如此.如果 Xs
是一个包含一个元素的列表,那么 Ys
也是如此.如果 Xs
至少有 2 个元素,那么这两个是 Ys
.
And there are 3 different answers. If Xs
is empty, then so is Ys
. If Xs
is a list with one element, then so is Ys
. If Xs
has at least 2 elements, then those two are Ys
.
1) 唯一的区别是 take(-1, Xs,Ys)
失败(对于所有 Xs, Ys
).可能最好的方法是发出类似于 arg(-1,s(1),2)
的 domain_error
1) The only difference being that take(-1, Xs,Ys)
fails (for all Xs, Ys
). Probably the best would be to issue a domain_error
similar to arg(-1,s(1),2)
这篇关于Prolog:取第一个“N";列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!