本文介绍了序言:以第一个"N"为准列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个Prolog谓词take(L, N, L1),如果列表L1以相同的顺序包含列表L的前N个元素,则该谓词成功.例如:

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 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?

推荐答案

此处是使用Haskell 之类的功能语言实现与take的关系副本的定义.首先,参数顺序应该不同,这有利于部分应用.有一个切入点,但是只有在生成内置instantiation_error的内置错误(=<)/2进行错误检查之后,该参数才能包含变量.

Here is a definition that implements the relational counterpart to take in functional languages like Haskell. 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] ? ;
no

请注意上述查询的读取方式:

Note how above query reads:

有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.

这篇关于序言:以第一个"N"为准列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:27