Topic: "Prolog difference lists" (page 1 of 1)

1
Author Post
ZhekaS
groupmastergroupmastergroupmastergroupmaster
Well... I believe this forum is a one of a very few places where I can find people with some exotic/special knowlege. So I will post my question here.
The question is about Prolog language and a special data structure called "difference list" (if you don't know what it means, I believe you should not continue reading). So,lets represent a diff-list by a pair of lists L - Z. Now, the question is : Given difference list L-Z, divide it into two smaller difference lists L1-Z1, L2-Z2 , such that their lengths will be equal or differ by 1. E.g:
The query
divide_list([a,b,c,d,e|X]-X, L1-[], L2-[]).
will return
L1=[a,b,c]
L2=[d,e]

Actually the order of the L1, L2 elements is not important. It maybe reversed. The predicate solving this problem should use the advantages of a diff-list as much as possible and use built-in predicates as few as possible.

P.S. This is not a riddle/challenge or something, I just need some help in solving it ;) I can think of not-so-effective solutions, but I am new to this type of data structure and i'm sure i'm missing something.
private message EMail
beerhunter
groupmastergroupmastergroupmastergroupmastergroupmastergroupmaster
Should divide_list only divide the list in one possible way, or does it have to create other ones on backtracking? If it's the first case, here's how to do it for regular lists:

divlist([], [], []).
divlist([H|T1], [H|T2], L) :- divlist(T1, L, T2).

Difference lists would be almost the same, since you don't need to append anything.
private message EMail
unknown user
You see this is exactly why i never liked prolog. Even after having taken a course in it, it still took me minutes, to understand how the 2 lines of code worked :).
EMail
ZhekaS
groupmastergroupmastergroupmastergroupmaster
Actually, about the regular lists there is no problem. But I was thinking about something like to take the first and last members of the list and append them to the two resulting lists. The last member is the problem - to get it i have to scan the whole list. But in the difference list, in fact, the end of the list is pointed by the second member of the pair, so theoretically it can be accessed without scanning..
private message EMail

Topic: "Prolog difference lists" (page 1 of 1)

1