简体   繁体   English

Prolog - 将带有元素结果的列表与一个奇怪的尾部相乘?

[英]Prolog - Multiply a list with an element results with a weird tail?

I want to multiply two lists, where I take the left list and multiply it by each element of the right list. 我想将两个列表相乘,我在左侧列表中将其乘以右侧列表中的每个元素。

For example: 例如:

?- multLists([3,4,2], [4,7,8], R).
R = [[12,16,8],[21,28,14],[24,32,16]].

For that I wrote a helper predicate that takes a list and multiplies it by a single scalar: 为此,我编写了一个辅助谓词,它接受一个列表并将其乘以一个标量:

multListElem([], _, _).
multListElem([H|T], Result, Elem) :- 
    multListElem(T, W, Elem),
    Z is H*Elem,
    Result = [Z|W].

But now, when I run ?- multListElem([1,2,3], X, 3). 但现在,当我运行?- multListElem([1,2,3], X, 3). I get: 我明白了:

1 ?- multListElem([1,2,3], X, 3).
X = [3, 6, 9|_G1840].

What is that weird tail _G1840 ? 什么是奇怪的尾巴_G1840

The bug is here: multListElem([],_,_) . 错误在这里: multListElem([],_,_) When the first list is empty, the result is empty, so you must write multListElem([],[],_). 当第一个列表为空时,结果为空,因此您必须编写multListElem([],[],_).

When you work with lists, you can use functional idioms like maplist : 当您使用列表时,您可以使用功能成语像MAPLIST

multLists(L1, L2, R) :-
    maplist(mult_one_list(L1), L2, R).

mult_one_list(L1, Elem, R) :-
    maplist(mult_2_numbers(Elem), L1, R).

mult_2_numbers(V1, V2, R) :-
    R is V1 * V2.

maplist applies the first argument to each element of each list (passed to it as an argument). maplist将第一个参数应用于每个列表的每个元素(作为参数传递给它)。

your base case leave uninstantiated the tail: change to 你的基本情况留下未实例化的尾巴:改为

multListElem([],[],_).

and it will work. 它会起作用。

@Joel76 already addressed your problem, and exposed a better approach using maplist. @ Joel76已经解决了你的问题,并使用maplist暴露了一种更好的方法。 If you have lambda.pl available here is a compact formula solving the problem 如果你有lambda.pl可用,这是一个解决问题的紧凑公式

?- maplist(\A^B^maplist(\X^Y^(Y is X*A), [3,4,2], B), [4,7,8], R).
R = [[12, 16, 8], [21, 28, 14], [24, 32, 16]].

edit of course the proper interface would be 编辑当然适当的界面

multLists(L1, L2, R) :-
    maplist(\A^B^maplist(\X^Y^(Y is X*A), L1, B), L2, R).

The second bug that @false pointed it's difficult to understand but easy to fix: 第二个错误@false指出它很难理解,但很容易修复:

multLists(L1, L2, R) :-
    maplist(\A^maplist(\X^Y^(Y is X*A), L1), L2, R).

The first bug I would call a feature: it's very useful that lambda works with the closure, and A is declared then... Just my 2 cents... 第一个错误我会叫一个特点:它是非常有用的拉姆达的工作原理与关闭,并且A 声明 ,然后...只是我的2美分...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM