在prolog中读取文件并将其转换为列表

在prolog中读取文件并将其转换为列表,prolog,Prolog,在prolog中查找将file.txt转换为以下列表的代码: 3 3 10 80 30 40 50 20 10 2 3 5 6 6 2 6 9 4 6 8 1 List1=[3,3] List2=[10,80,30] List3=[40,50,20,10] Cost=[[2,3,5,6],[6,2,6,9],[4,6,8,1]] 完整代码: :- use_module(library(dcg/basics), except([eos/2])). lists(Input_

在prolog中查找将file.txt转换为以下列表的代码:

3  3
10 80 30
40 50 20 10
2  3  5  6
6  2  6  9
4  6  8  1

List1=[3,3]
List2=[10,80,30]
List3=[40,50,20,10]
Cost=[[2,3,5,6],[6,2,6,9],[4,6,8,1]]
完整代码:

:- use_module(library(dcg/basics), except([eos/2])).

lists(Input_path) :-
    DCG = read_lists(Lists),
    phrase_from_file(DCG,Input_path), !,
    Lists = [List1,List2,List3,List4,List5,List6],
    format('List1=~w~n',[List1]),
    format('List2=~w~n',[List2]),
    format('List3=~w~n',[List3]),
    format('Cost=[~w,~w,~w]~n',[List4,List5,List6]).

eos([], []).

read_lists([]) --> call(eos).
read_lists([List|Lists]) -->
    read_list(List),
    (
        "\n"
    |
        []
    ),
    read_lists(Lists).
read_lists([]) --> [].

read_list([Item|Items]) -->
    number(Item),
    whites,
    read_list(Items).
read_list([]) --> [].
运行示例:

?- lists("C:/data.txt").
List1=[3,3]
List2=[10,80,30]
List3=[40,50,20,1]
Cost=[[2,3,5,6],[6,2,6,9],[4,6,8,1]]
true.

代码解释

虽然可以使用递归代码以及手动保存和传递变量来解析列表,但使用definite子句语法()进行解析更容易

在执行DCG时,有预先编写的谓词库。使用SWI Prolog时,DCGs最流行的库是

这行代码引入了库。然而,eos/2导致了一个错误,所以我将其排除,并手动将其添加到代码中

:- use_module(library(dcg/basics), except([eos/2])).
DCG是隐藏两个状态变量的子句,可以使用

所有使用
-->
而不是
:-
的代码都是DCG

使用DCGs的一种常见方法是使用,但从文件中读取数据,然后使用短语是非常常见的,因此可以使用更好的谓词

库中DCG中的两个子句是
number//1
whites//0

eos
用于蒸汽末端,用于
read\u列表的基本情况//1

用于写出结果


剩下的是标准的简单序言。

因此不是一个代码编写服务,您必须展示您迄今为止尝试过的内容以及它不起作用的原因。到时候,这里的人会很乐意帮忙的。非常感谢。此代码可用于生成3*3的二维列表。你能修改代码,这样它就可以生成一个n*n的2D列表吗?同时,我有一段代码,你能帮我调试一下吗?我非常感谢你,米奇非常感谢你!我已经把它作为新问题发布了。我期待你的帮助