【问题标题】:convert same function/concept of C++ to prolog将 C++ 的相同功能/概念转换为 prolog
【发布时间】:2015-06-14 17:49:24
【问题描述】:

我只是想知道是否可以通过使用 I/O 将 c++ 代码的这个概念转换/获取到 prolog?如果可能的话,怎么做?因为有人告诉我,prolog 不是一种强大的编程语言,所以我们一次只能输入一个输入,但是通过在 prolog 中使用 I/O,也许我们可以在文件中搜索输入。

#include <iostream>
using namespace std;   
int main ()
{
  int i, x;
  int id[5];

  cout << "Please enter an integer value: ";
  cin >> i;
  cout << "The value you entered is " << i<<"\n";

  for(x=0; x<i;x++){

     cout << "Enter id: ";
     cin>>id[x]; 
     }

  for(x=0; x<i;x++){
    cout << "\nYou have enter id "<<x+1<<": "<<id[x];
    }  
   cout<<"\n";

   system("pause");
   return 0;
}

【问题讨论】:

  • 在 Prolog 中执行您的 C++ 示例程序所做的事情不仅可能而且很简单。编程语言的“力量”不是在一维尺度上衡量的”。在这样的衡量标准中,需要定义“强大”(这是否意味着实时效率?实现的简单性和/或简洁性?多样性标准库中的方法/函数?等等)。Prolog 在某些方面非常强大。甚至比 C++ 更强大。;)
  • 好吧,我问了上面c++代码中用户输入的大小,他说这是不可能的,因为Prolog并不强大。也许就其无能做很多事情而言。但是当我在互联网上搜索时,我找不到答案,所以我只是想也许这毕竟是真的。
  • 查看functor/3arg/3 作为创建和使用任意长度的模拟数组的一种可能性。
  • 您需要小心使用答案更新问题和引入新问题。这会使问答线程有点混乱。最好打开一个新问题。但是对于您的代码:您的 check/1 谓词使用整数参数调用,但您的 check/1 子句的内容在 read_file/2 谓词中使用该参数作为列表。所以他们不会统一,会失败。
  • 对不起。我不知道。然后我会为这个问题提出新的问题。顺便说一句,再次感谢@lurker。你是最棒的。

标签: c++ input io prolog


【解决方案1】:

有几种方法可以编写 Prolog 中显示的示例程序。一种简单的方法是:

main :-
    write('Please enter an integer value: '),
    read(N),
    integer(N),
    N > 0,
    length(L, N),
    maplist(read_n, L),
    write_list(L).

read_n(N) :-
    write('Enter id: '),
    read(N),
    integer(N).

write_list(L) :-
    write_list(L, 1).
write_list([], _) :- nl.
write_list([H|T], N) :-
    format('~nYou have entered id ~w: ~w', [N, H]),
    N1 is N + 1,
    write_list(T, N1).

试运行:

| ?- main.
Please enter an integer value: 4.
Enter id: 5.
Enter id: 6.
Enter id: 3.
Enter id: 6.

You have entered id 1: 5
You have entered id 2: 6
You have entered id 3: 3
You have entered id 4: 6

yes
| ?-

【讨论】:

  • 哇!我想为一些简单的事情撞头。非常感谢@lurker。
  • 对不起,如何让它检查txt文件中的答案(ID号)是否在文件中并在Prolog屏幕上打印出来?
  • @umika1150 这将取决于文本文件的格式。 SWI Prolog has a suite of I/O routines 你可以从中挑选一些可以完成工作的东西。
  • 我对代码进行了一些更改,并编辑了如上所示的问题。你能告诉我有什么问题吗?我该怎么做才能正确?在它可以读取和检查文件之前,我无法平静或平静。
猜你喜欢
  • 1970-01-01
  • 2016-08-25
  • 2015-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多