开发者

Prolog - get the first list from a list of lists

开发者 https://www.devze.com 2023-01-23 07:46 出处:网络
I\'ve got a list consisting of smaller lists inside of it, each list consisting of 2 items: [[a,1],[b,2],[c,3]]

I've got a list consisting of smaller lists inside of it, each list consisting of 2 items:

[[a,1],[b,2],[c,3]]  

I'm using a function called take(1,L,R) to take the first item from list L and return the item R. The code for the take function is here:

take(0,X,X).
take(N,[H|T],[H|R]):- 
    N>0, M is N-1,
    take(M,T,R).  

At the moment a run may look like this:

1 ?- take(1,[[a],[b],[c]],Taken).
Taken = [[a], [b], [c]]

Which is the same as the input! This is the开发者_开发知识库 same for a "regular" 1-level-depth list:

2 ?- take(1,[a,b,c],Taken).
Taken = [a, b, c]

Question:

The question for you is how can I make the result look like:

1 ?- take(1,[[a],[b],[c]],Taken).
Taken = [a]

I want to return the first N items of the list I send it.


Your base case take(0, X, X). is doing exactly what it says -- given any value X, the result is X. What I think you were trying to say is take(1, [H|T], H). (which yields the first element of a list).

What I think you're actually after is take(0, _, [ ]). which yields an empty list when "taking" 0 items from any list. This works well with your existing recursive case.

You say that you want to get the "first N items of the list" -- such a result must be stored in a list of N items. It follows that take(1, [a, b, c], Taken) would yield Taken = [a], not Taken = a. Similarly, take(1, [[a], [b], [c]], Taken). would yield Taken = [[a]].. To special-case the take(1, ...) form to return the first item only (without it being wrapped in a list) would break your recursion.

0

精彩评论

暂无评论...
验证码 换一张
取 消