【问题标题】:How to convert a list of numbers to a list of words in Prolog?如何将数字列表转换为 Prolog 中的单词列表?
【发布时间】:2019-02-22 19:04:39
【问题描述】:

我正在尝试编写一个 Prolog 程序,给定一个像 [1, 2, 3] 这样的数字列表,它将它们转换为代表这些数字 ['one', 'two', 'three'] 的单词列表。

到目前为止我的代码:

totext(0, 'zero').
totext(1, 'one').
totext(2, 'two').
totext(3, 'three').
totext(4, 'four').
totext(5, 'five').
totext(6, 'six').
totext(7, 'seven').
totext(8, 'eight').
totext(9, 'nine').

translate([], []).
translate([Head|Rest], [TranslatedHead|TranslatedRest]) :-
   totext(Head, TranslatedHead),
   translate(Rest, TranslatedRest).

当我加载gprolog 并查阅文件时,如果我这样做了:

translate([], X).

我正确理解:

X = []
yes

但是当我这样做时

translate([1,2], X).

我明白了:

uncaught exception: error(existence_error(procedure,totext/0),translate/0)

我对 Prolog 很陌生(这是我的第一个 Prolog 程序),我不知道这里出了什么问题。有任何想法吗?谢谢。

【问题讨论】:

  • 当我将您的代码加载到gprolog 并执行translate([1,2], X). 时,我得到X = [one, two]。我敢打赌你在translate 后面加了一个空格。请注意错误中的translate/0,这意味着translate 的“无参数”。你输入translate ([1,,2], X).了吗?那是行不通的。另外,您可以使用maplist 进行这种列表处理:maplist(totext, Numbers, Names)。试试maplist(totext, [1,2,3], Names)
  • 这是完整的程序吗?好像少了点什么?
  • @WillemVanOnsem 什么都没有。它按原样工作。
  • 这是完整的程序,我把它保存为“test.pl”。我打开 gprolog 然后做咨询('test.pl')。试试看,还是不行。
  • @lurker:我的意思是,由于我们没有收到错误,因此两者看起来不同步:产生错误的程序和此处共享的程序。

标签: prolog gnu-prolog


【解决方案1】:

您的代码已更正,但您的 GNU Prolog 版本已损坏。从源代码重新编译 GNU Prolog 应该可以修复它。损坏的 GNU Prolog 构建的常见症状是谓词存在错误,其中始终报告为元数为零的谓词通常不存在于被调用的代码中。

附:损坏的 GNU Prolog 安装似乎通常在使用 Ubuntu 时发生。你能确认这也是你的情况吗?

【讨论】:

  • 是的,我正在运行 Ubuntu。我通过执行 sudo apt install gprolog 获得了 gprolog。我会尝试以其他方式获得它
  • 这里也一样。我在 Ubuntu 上,并且从源代码进行了全新构建。
  • 在 Ubuntu 上从源代码重建 gprolog 1.4.5 解决了这个问题并且代码可以正常工作。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-02
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多