问题
I am attempting to write a predicate for the following task.
Write a predicate distances(Bs, B, Ds) where Bs and Ds are lists of variables such that the ith element of the Ds is the absolute difference between the variable B and the ith element of Bs
know this is incorrect but it what I believe I roughly should be trying to do
distances([],_,[]).
distances([H|T],B,A) :-abs(H - B,A),distances(T,B,A)
Do I need to return the result of the abs predicate into the recusive call to distance?
I can use abs to calculate the correct value for each entry in the list but how do I then put that information into a list which can then be returned?
回答1:
A predicate does not return. A predicate succeeds, fails, (gets stuck in an infinite loop, or raises an error). One uses unification to provide results. In fact here your third parameters Ds
should probably provide the result.
We thus can unify the absolute value D
to the head of the list of the third parameter, and recurse on the tail Ds
:
distances([], _, []).
distances([H|T], B, [D|Ds]) :-
abs(H - B, D),
distances(T, B, Ds).
来源:https://stackoverflow.com/questions/60979954/build-a-list-with-abs-in-prolog