list - Prolog 中的简单平方程序

标签 list prolog

为什么下面的简单程序不起作用?

main :-
    squares([1,2,3,4,5], L),
    writeln(L).

squares([H|T], Outl) :-
    Sq is H*H,
    squares(T, [Sq|Outl]).
squares([], []).

输出为:

?- main.
false.

[Outl] 替换 Outl (在 squares([H|T], Outl) 中)没有帮助。

使用 =#= 代替或 is 也没有帮助。

也没有用squares([], P)代替squares([], [])

最佳答案

这是 maplist 的绝佳候选者。

定义一个元素的平方:

squared(X, XX) :- XX #= X * X.

然后应用maplist:

squared_list(L, LL) :- maplist(squared, L, LL).

通过在这里使用 #= 而不是 is/2,它的行为更加相关:

| ?- squared_list([1,2,3], L).

L = [1,4,9]

yes
| ?- squared_list(L, [1,4,9]).

L = [1,2,3] ? ;

(1 ms) no
| ?-

关于list - Prolog 中的简单平方程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38177232/

相关文章:

Java 同步集合与对象

java - Google Foobar 数字站

python - 在列表中拆分列表

python - 在列表中查找邻居

prolog - 列表中每个元素的事实 Prolog

Prolog - 命题逻辑中的公式

list - 如何避免 SWI-Prolog 中的 "out of global stack"错误?

java 保存列表<JButton>

prolog - 如何写一个谓词 minmax(L, X, Y)?

使用列表的 Prolog 到 Datalog 代码转换