0

Prolog SWI.

Let's say I have a recursive function that adds X items to list in every iteration. Something that looks like:

func(...,BigList):-
     func2(...,CurrentList),
     BigList = [ CurrentList | Tail ],
     func(..., Tail).

I tried to remove parts which are not important, to make it easier to read.

I'll explain: func is suppose to add some items to BigList. In every iteration, func2 initializes CurrentList, which is being added to BigList.

The problem is that BigList looks like:

[[iter1item1,iter1item2,...,iter1itemX],[iter2item1,iter2item2,...,iter2itemX],..[iterXitem1,iterXitem2,...iterXitemX]]

Instead of:

[iter1item1,iter1item2,...,iter1itemX,iter2item1,iter2item2,...,iter2itemX,..iterXitem1,iterXitem2,...iterXitemX]

I'll just say that it might be a simple solution, but I'm new to Prolog, and 20 minuts of Googling didn't really help. I recognize the problem but have no idea how I suppose to write the code such that it will work as I want it to.

Mockingbird
  • 1,023
  • 9
  • 17
  • 2
    Use the built in predicate: `append(CurrentList, Tail, BigList)` – lurker Mar 06 '14 at 21:35
  • @mbratch, I've found this predicate, the question is where am I suppose to add this line? Thanks. – Mockingbird Mar 06 '14 at 21:40
  • 1
    Instead of `BigList = [CurrentList | Tail],` you use `append(CurrentList, Tail, BigList),`. Depending upon how your predicate works, you may have to swap the `append` call and the query to `func` in sequence. btw, first google hit on "prolog append list" is: http://stackoverflow.com/questions/11539203/how-do-i-append-lists-in-prolog :) – lurker Mar 06 '14 at 21:41
  • @mbratch - Solved! thanks. If you can explain shortly how does Prolog picks Tail as an empty list in the recursive call, it will be great. – Mockingbird Mar 06 '14 at 21:46
  • Yeah the 'append' isn't the problem. I didn't know how to use both 'append' and let Tail be the empty list in this example (I googled for recursive examples). – Mockingbird Mar 06 '14 at 21:48
  • You'll need a base case for `func`. Something like, `func(..., []).` (Maybe you already have one you're not showing.) `append` handles the empty list just fine. – lurker Mar 06 '14 at 21:51
  • Yeah I got a base func. Thanks again. :) – Mockingbird Mar 06 '14 at 22:01

0 Answers0