Build a list with abs() in prolog

痞子三分冷 提交于 2021-02-11 06:27:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!