1
votes

Write a predicate triangle(Bs, Ds) where Bs a list of the positions of the foo and Ds is the (single) list of differences in position. Use the built-in predicate append and the your own distances predicate.

This is related to this questions : Build a list with abs() in prolog

distances([], _, []).
distances([H|T], B, [D|Ds]) :- abs(H - B, D), distances(T, B, Ds).

triangle([],[]).
triangle([H|T], [D|Dt]) :-  distances(T,H,D), triangle(T,Dt).


?- triangle([1,2,3],A).
A = [[1, 2], [1], []].

The Solution I require

?- triangle([1,2,3],A).
A = [1,2,1].

The answer is correct but it is a in list of lists.

I'm having trouble turning Ds into a single list. I have tried using append in various positions within the predicate but either get repetitions or the predicate evaluates to false. How can I turn Ds into a single list [1,2,3] with append?

1
So the solution should be [1,2,1]? - Willem Van Onsem
Yes [1,2,1] that is the correct - BlueBerry

1 Answers

1
votes

You can append the list D with Dt, instead of using [D|Dt] where you thus prepend the list with one element D:

triangle([],[]).
triangle([H|T], Ds) :-
    distances(T, H, D),
    append(D, Dt, Ds),
    triangle(T, Dt).