在 prolog 中使用 abs() 构建一个列表 [英] Build a list with abs() in prolog

查看:61
本文介绍了在 prolog 中使用 abs() 构建一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为以下任务编写谓词.

I am attempting to write a predicate for the following task.

写一个谓词 distances(Bs, B, Ds) 其中 Bs 和 Ds 是变量列表,使得Ds的第i个元素是变量B与Bs的第i个元素的绝对差

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) 

是否需要将 abs 谓词的结果返回到对 distance 的递归调用中?

Do I need to return the result of the abs predicate into the recusive call to distance?

我可以使用 abs 来计算列表中每个条目的正确值,但是如何将该信息放入一个列表中,然后可以返回?

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?

推荐答案

谓词不返回.谓词成功、失败(陷入无限循环或引发错误).一种是使用统一来提供结果.事实上,这里你的第三个参数 Ds 应该可以提供结果.

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.

因此我们可以将绝对值D统一到第三个参数列表的头部,并在尾部Ds上递归:

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).

这篇关于在 prolog 中使用 abs() 构建一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆