相关疑难解决方法(0)

Prolog DCG语法规则中的堆栈溢出:如何有效或懒惰地处理大型列表

我正在解析一个由一系列行组成的相当简单的文件格式,每行都有一些空格分隔的字段,如下所示:

l 0x9823 1
s 0x1111 3
l 0x1111 12
?
Run Code Online (Sandbox Code Playgroud)

我正在使用SWI-Prolog.这是我到目前为止的DCG:

:- consult(library(pure_input)).

load_trace(Filename, Traces) :-
    phrase_from_file(trace_file_phrase(Traces), Filename).

trace_file_phrase([]) --> [].
trace_file_phrase([T|Ts]) --> trace_phrase(T), trace_file_phrase(Ts).

trace_phrase(access(Type, Address, SinceLast)) -->
    access_type(Type), space,
    address(Address),  space,
    nat(SinceLast),    newline.

access_type(load)  --> "l".
access_type(store) --> "s".

address(Number) --> "0x", hexnum(Number).

hexdigit(N)  --> digit(N).
hexdigit(10) --> "a". hexdigit(11) --> "b". hexdigit(12) --> "c".
hexdigit(13) --> "d". hexdigit(14) --> "e". hexdigit(15) --> "f".
hexnum(N) --> hexdigit(D), hexnum(D, N).
hexnum(N, N) --> [].
hexnum(A, N) --> hexdigit(D), …
Run Code Online (Sandbox Code Playgroud)

prolog swi-prolog dcg

16
推荐指数
3
解决办法
2451
查看次数

在Prolog中构建表达式树

我正在寻找一种在Prolog中构建表达式树的方法.我已经做了一些实验,并提出了以下工作代码(只处理常量和加号表达式):

const(_).
plus(_, _).

eval(const(R), R).

eval(plus(A, B), R) :- number(A), number(B), R is A+B.
eval(plus(A, B), R) :- number(A), eval(B, B_R), R is A+B_R.
eval(plus(A, B), R) :- eval(A, A_R), number(B), R is A_R+B.
eval(plus(A, B), R) :- eval(A, A_R), eval(B, B_R), R is A_R+B_R.
Run Code Online (Sandbox Code Playgroud)

这种方法有没有更简单的替代方案?我是否必须为我计划添加到程序中的每个操作员定义这4个案例?

prolog expression-trees dcg

3
推荐指数
2
解决办法
2219
查看次数

标签 统计

dcg ×2

prolog ×2

expression-trees ×1

swi-prolog ×1