首页 > 解决方案 > 从其他谓词调用​​时谓词返回 false

问题描述

我在 Prolog 中有这个程序

su([], Counter, Counter).
su([G|O], N, Count) :- Counter is Count + G, su(O,N,Counter).

custom_sum(L,X) :- su(L,X,0).

write_file :-
   write('Type list: '),
   read(L1),
   tell('file.txt'),
      write(L1), write(.), nl,
   told.

read_file :-
   write('Reading from file...'), nl,
   see('file.txt'),
      read(L),
   seen,
   write('sum of list elements: '),
   custom_sum(L,Sum),
   write(Sum), assertz(my_sum(Sum)).

当我尝试使用 custom_sum 时,一切都很好。与 write_file 相同。但是 read_file 在“write('列表元素的总和:')”之后立即返回 false。好像 custom_sum 在这里是个问题。

标签: prolog

解决方案


出于好奇,我运行了您的代码而没有更改任何内容。您的代码在 Windows 10 上使用 SWI-Prolog 的系统上可以正常工作。

Welcome to SWI-Prolog (threaded, 64 bits, version 8.1.24)
SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.
Please run ?- license. for legal details.

For online help and background, visit https://www.swi-prolog.org
For built-in help, use ?- help(Topic). or ?- apropos(Word).

?- consult("C:/Users/Groot/Documents/Projects/Prolog/SO_question_180.pl").
true.

?- custom_sum([1,2,3],R).
R = 6.

?- working_directory(Working_directory,'C:/Users/Groot/Documents/Projects/Prolog/SO_question_180/').
Working_directory = 'c:/users/groot/documents/prolog/'.

?- working_directory(D,D).
D = 'c:/users/groot/documents/projects/prolog/so_question_180/'.

?- write_file.
Type list: [1,2,3].

true.

?- read_file.
Reading from file...
sum of list elements: 6
true.

?- 

我唯一的猜测是您在提示符下错误地输入了列表。

应该是[1,2,3]. You need the[ ]和 end period .


创建的内容file.txt

[1,2,3].

推荐阅读