Prolog 遍历列表 [英] Prolog iterating over list

查看:129
本文介绍了Prolog 遍历列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Prolog 示例列表程序并尝试对它们进行一些操作.但是,我被困在某个点上,找不到任何解决方案或示例.

I am working with Prolog sample list programs and triying to do some operations on them. However, I am stuck at a point and couldn't find any solution or sample.

我想编写一个函数,它接受两个整数列表并返回一个浮点值.两个列表大小相等.浮点值是比较结果除以列表大小.

I want to write a function which takes two lists of integers and return a float value. The two lists size are equal. The float value is the result of comparison divided by list size.

该函数应该将第一个列表的每个元素与第二个列表的每个元素进行比较.一对 (i, j) 是 i 是第一个列表中元素的位置,j 是第二个列表中元素的位置.如果元素i大于元素j,比较结果加1.如果元素i小于元素j,比较结果减1.如果相等,什么都不发生.在上述操作结束时,我们返回上述浮点值.

The function should compare every elemen of first list to every elemen of the second list. A pair (i, j) is that i is the location of element in first list and j is the location of the element in second list. If element i greater than element j, result of comparison is incremented by 1. If element i less than element j, result of comparison decremented by 1. If equal, nothing happen. At the end of the above operation, we return the float value described above.

示例:

retVal([4,5,3], [8,2,1], Result).

应该返回结果 = (-1+1+1-1+1+1-1+1+1)/3 = 0.33

should return Result = (-1+1+1-1+1+1-1+1+1) / 3 = 0.33

在面向对象的语言中,它就像在控制台上打印一些东西一样简单.但是,我在 Prolog 中没有任何想法.提前致谢.

In object oriented language, it is as simple as printing something on the console. However, I don't have any idea in Prolog. Thank you in advance.

推荐答案

你所描述的文字可能是这个片段

What you describe by words could be this snippet

retVal(L1,L2, Result) :-
 findall(S, (member(X1,L1), member(X2,L2), (X1 < X2 -> S = -1 ; S = 1)), L),
 sum_list(L, Sum),
 length(L1, Len),
 Result is Sum / Len.

唉,测试结果不符合你的预期

Alas, the test outcome doesn't match your expectation

?- retVal([4,5,3], [8,2,1], X).
X = 1.

正如 liori 在他的评论中指出的那样,您的手动计算是不正确的...

As liori noted in his comment, your manual calculation is incorrect...

这篇关于Prolog 遍历列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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