io - 在 prolog 中的文件中搜索

标签 io prolog instantiation-error

你好,我试图创建一个代码,从输入文件中找到给定的字符并打印出它的位置,这就是我“在我发现的类似问题的帮助下”得到的结果

process2(Text,POS):-
    open('houses.txt', read, In),
    get_char(In, Char1),
    find(Char1, In,Text,POS),
    close(In).

find(Text,In, Text, 0).
find(Char,In,Text,POS) :-
    POS is POS1 +1,
    get_char(In, Char2),
    find(Char2,In,Text,POS1).

但是编译器会抛出此错误: 错误:is/2:参数未充分实例化

最佳答案

处理输入时,始终首先考虑 DCG:

:- use_module(library(pio)).

process3(File, Text, POS) :- phrase_from_file(find(Text, POS), File).

find(Text, [P|Ps]) -->
    lazy_list_character_count(P), Text, !,
    find(Text, Ps).
find(Text, Ps) --> [_], find(Text, Ps).
find(_Text, []) --> [].

This finds all positions of the input string:

?- process3('/home/carlo/.swiplrc', `file`, P).
P = [51, 174, 254, 452, 549, 1977, 2106, 3682, 4033|...] ;
false.

编辑按照鲍里斯的建议,削减可能会删除一些合法的解决方案。 所以这是一个免费版本。

find(_Text, []) --> [].
find(Text, [P|Ps]) -->
    lazy_list_character_count(P), Text,
    find(Text, Ps).
find(Text, Ps) --> \+Text, [_], find(Text, Ps).

关于io - 在 prolog 中的文件中搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36250346/

相关文章:

java - 从文件中读取 ArrayList 作为对象?

c - 重定向标准输入

prolog - 在 Prolog 中创建 Groebner 基础 SAT 求解器

Prolog 平方差

recursion - 这可以在 Prolog 中进行尾递归吗?

c - 如何将标准输出重定向回终端窗口

java - Java NIO 在阻塞模式下相对于传统 I/O 的优势?

prolog - 基本 prolog 程序不返回 FALSE

c# - Java、C# 和 Prolog 反射机制

prolog - 查阅文件时参数未充分实例化