2
votes

I'm trying to write a recursive function that passes a list down to itself and at each level adds an element to that list. The final list should be reported back as a solution to the predicate. But I can't figure out how to do this. The form of the problem basically looks like this:

solve(List, NumberOfSteps) :- NumberOfSteps = 10 . //Stops after 10 recursive steps
solve(List, NumberOfSteps) :-
    append NumberOfSteps to List,
    NumberOfStepsIncremented is NumberOfSteps + 1,
    solve(List, NumberOfStepsIncremented) .

So I here I want to call solve(List, 1) and have Prolog come back with an answer that looks like:

List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ;
true

I can get Prolog to create the list and print it out at the end. I can do this by using the built in-predict append(List, NumberOfSteps, List2) and then passing List2 down through the recursion and printing it at the end, but List and List2 aren't unified there and the actual answer that Prolog gives me is List = [] ; true

I have a feeling I might be approaching the problem the wrong way but I'm stuck!

Thanks.

2

2 Answers

1
votes

I figured it out. This is what it should have looked like:

solve(List, NumberOfSteps) :- NumberOfSteps = 10 . //Stops after 10 recursive steps
solve([LHead | LTail], NumberOfSteps) :-
    LHead = NumberOfSteps,
    NumberOfStepsIncremented is NumberOfSteps + 1,
    solve(LTail, NumberOfStepsIncremented) .
1
votes

I'll extend the comment by Will Ness to your answer and will show the simpler correction:

solve([NumberOfSteps], NumberOfSteps) :-
    NumberOfSteps = 10, !. % Stops after 10 recursive steps
solve([LHead | LTail], NumberOfSteps) :-
    LHead = NumberOfSteps,
    NumberOfStepsIncremented is NumberOfSteps + 1,
    solve(LTail, NumberOfStepsIncremented) .