【发布时间】:2021-12-27 13:33:30
【问题描述】:
我正在尝试对列表进行切片,并创建一个结果列表,其中包含位于两个索引之间的元素,互斥。
indexOf([Element|_], Element, 0). % We found the element
indexOf([_|Tail], Element, Index):-
indexOf(Tail, Element, Index1), % Check in the tail of the list
Index is Index1+1. % and increment the resulting index
less_than(0, 0).
less_than(X, N) :-
X < N.
greater_than(0, 0).
greater_than(X, N) :-
X > N.
slice([], 0, 0, []).
slice([H|T], I, N, R) :-
indexOf([H, T], H, Ind), % get the index of the H
(less_than(Ind, N),
greater_than(Ind, I), % check if that index is between I and N
slice(T, I, N, H|R); % if it is - call the slice again, but append the H to the result
slice(T, I, N, R)). % if it's not, just call the slice regularly with the rest of the items
例如,slice([a,b,c,d], 0, 4, R) R 应该是 [b,c]。
现在这总是失败,但我不知道为什么。 它是基本情况,还是括号之间的“if-else”语句? 我想在不使用内置谓词的情况下完成此操作。
【问题讨论】:
-
当我尝试运行这段代码时,Prolog 只告诉我“indexOf/3 不存在”。它应该如何工作?
-
什么意思,“两个索引之间,互斥的”。
slice([a,b,c,d], 1, 2, Slice)会发生什么? -
抱歉,忘记添加那部分了。
-
slice([a,b,c,d], 1, 2, Slice) 应该返回空列表。 slice([a,b,c,d], 0, 4, Slice) 应该返回 [b,c]。
-
H|R不是列表语法。你的意思可能是[H|R]。