Prolog HTTP 动态添加链接到 html

Prolog HTTP dynamically add links to html

我是 prolog 和声明式编程的新手,我努力实现以下目标。

我正在关注 this tutorial,现在想在一个页面上显示多个链接。显示哪些链接取决于某些事实/变量。

这是我当前的代码:

link_collection(Request) :-
http_parameters(Request,
[
    foo(Foo, [optional(true)])
]),
reply_html_page(
    [title('Dynamic Link Collection')],
    [
        a([href='/questionalice'], 'Question Alice'),       /* Should only show if has(investigate, body) is true */
        a([href='/questionbob'], 'Question Bob'),          /* Should only show if Foo = bar */
        a([href='/investigatebody'], 'Investigate Body')   /* Show always */
    ]
).

请注意,"permutations" 的数量不允许我仅 "or" link_collection 语句。我也希望条件可以任意复杂。

您的问题可以在相当笼统的上下文中回答,也就是说,即使不考虑 HTTP 的具体用例。

一般的问题似乎是:我如何动态地 select一些可用选项的子集。

为此,假设您不将每个 link 表示为 "itself",而是表示 形式 Link-Condition , 解释为 Link 应该只包含 if Conditiontrue.

让我们先考虑我们要表达的条件,并定义何时它们为真。重要的是,您的条件还取决于 Foo 的值,因此必须考虑到这一点:

is_true_with_foo(_, has(investigate, body)) :- has(investigate, body).
is_true_with_foo(Foo, Foo = bar)            :- Foo = bar.
is_true_with_foo(_, true).

因此,这描述了 何时 特定条件为真,也取决于 Foo.

的值

现在,您的示例条件可以表示如下:

links_conditions(Foo,
    [
        a([href='/questionalice'], 'Question Alice')-has(investigate, body),
        a([href='/questionbob'], 'Question Bob')-(Foo = bar),
        a([href='/investigatebody'], 'Investigate Body')-true
    ]).

要描述列表的 子序列 ,请考虑使用 DCG ()。

例如:

links_subset([], _) --> [].
links_subset([L-Cond|Ls], Foo) -->
        (   { is_true_with_foo(Foo, Cond) } ->
            [L]
        ;   []
        ),
        links_subset(Ls, Foo).

您现在可以拨打:

?- links_conditions(Foo, LCs0),
   phrase(links_subset(LCs0, no), LCs).

并在 LCs 中获得剩余的 link 秒。在这种情况下:

LCs = [a([href='/questionalice'], 'Question Alice'),
a([href='/investigatebody'], 'Investigate Body')].

因此,我们可以在回复中使用结果link:

link_collection(Request) :-
        http_parameters(Request, [foo(Foo, [optional(true)])]),
        links_conditions(Foo, LCs0),
        phrase(links_subset(LCs0, Foo), LCs),
        reply_html_page([title('Dynamic Link Collection')], LCs).

请注意 Foo 在这些谓词中是如何传递的。

P.S.: 您的示例代码段存在基本语法错误,因此我怀疑您的代码能否正常工作。