쉬운 솔루션은 이러한 라인을 따라, length/2
및 append/3
사용 순서는별로 중요하지 않습니다
가
trim(L,N,S) :- % to trim N elements from a list
length(P,N) , % - generate an unbound prefix list of the desired length
append(P,S,L) . % - and use append/3 to get the desired suffix.
참고. 이 역시 작동합니다 :
trim(L,N,S) :- % to trim N elements from a list
append(P,S,L) , % - split L into a prefix and suffix
length(P,N) . % - succeed if the prefix is of the desired length
나는 강사는 당신이/재귀 솔루션을 파악하고자하는 것을 상상한다. 하나는 목록의 왼쪽 끝에서 항목을 트리밍 알고리즘은 매우 간단 있습니다 있습니다
- 워크 목록 당신이
N
요소를 방문한 때까지.
- 일단 작업을 완료하면 원하는 결과가 남습니다. 간단한 해결책에 이르게
: 당신이 학자가되고 싶었 경우
trim(L , 0 , L) . % Trimming zero elements from a list yields the original, unchanged list
trim([H|T] , N , R) :- % Otherwise,
N > 0 , % - assuming N is greater than zero
N1 is N-1 , % - we decrement N
trim(T , N1 , R) % - and recurse down, discarding the head of the list.
. % That's about all there is too it.
은, 하나는 목록이 실제로 목록이어야합니다 제약 (또는 적어도 목록과 같은)을 적용 할 수있는, 뭔가 같은 :
trim([] , 0 , [] ) . % Trimming zero elements from the empty list yields the empty list
trim([H|T] , 0 , [H|T]) . % Trimming zero elements from a non-empty list yields the same list
trim([H|T] , N , R ) :- % Otherwise,
N > 0 , % - given that N is greater than zero
N1 is N-1 , % - we decrement N
trim(T , N1 , R) % - and recurse down, discarding the head of the list.
. % That's about all there is to it.
주 그 무언가
trim([a,b,c] , 5 , R) .
같은
이 실패합니다 : R = []
으로 위와 같은 것을 만드는 방법을 알아낼 수 있는지 확인하십시오. 힌트 : 어렵지 않습니다.
이
편집 참고하기 :를 실제로 1 N리스트의 요소를 먹고 싶어하면, 그것은 더 이상 어려운 없습니다 :
prefix_of(L,N,P) :-
append(P,_,L) ,
length(P,N)
.
또는 자신의 압연, 당신은 같은 것을 할 수있는 :
를
prefix_of(_ , 0 , [] ) . % once we've counted down to zero, close the result list and succeed.
prefix_of([X|Xs] , N , [X|Ys]) :- % otherwise,
N > 1 , % - given that N is greater than zero,
N1 is N-1 , % - decrement N
prefix_of(Xs , N1 , Ys) % - and recurse down, with X prepended to the resullt list.
. % Again, that's about all there is to it.
'append/3'을 사용해보세요. –
@ Tudor 답변을 말씀해 주실 수 있습니까? 나는 N을 포함하는 방법과 혼동 스럽다 –
'trim/3' 관계를 표현하기 위해'length/2'와'append/3'을 혼합 해보십시오. –