Prolog - DCG - 随机句子 [英] Prolog - DCG - random sentence

查看:58
本文介绍了Prolog - DCG - 随机句子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Prolog 的新手,我正在尝试编写一个小程序,该程序将从 DCG 中随机给出一个句子.

I'm new to Prolog, and I'm trying to write a small program that will give a random sentence from a DCG.

我之前的思路是用 findall/3 列出所有可能的句子,然后用 random_member/2.

My previous way of thinking was to use findall/3 to make a list of all possible sentences, and then using random_member/2.

它工作了一段时间,直到语法变大,我开始因为递归而出现堆栈错误......

It worked for a little while, until the grammar got bigger and I began to get stack errors because of recursion...

然后我想到了另一种方法:在给定时刻制作一组所有可能的术语,应用random_member来获取下一个术语,递归调用相同的函数,直到我得到空列表...

I then thought of another way : make a set of all possible terms at a given moment, applying random_member to get the next term, recursively call this same function, until I get the empty list...

但是我怎样才能得到一个不完整谓词的所有可能的答案呢?我怎样才能在 set 中得到它?

But how can I get a set of all possible answers to an incomplete predicate ? And how can I get it in a set ?

有关信息,我的 DCG 如下所示:

For information, my DCG looks like this:

s --> pronoun(X), verb(X), location.
pronoun(1) --> [i].
pronoun(2) --> [you].
verb(1) --> [am].
verb(2) --> [are].
location --> [here].
location --> [there].

我对解决方案的想法(其中 List 是已连接术语的列表):

My idea of the solution (where List is the list of the already concatenated terms ) :

createRandomSentence(List) :- 
    setof(H, s([List|[H|_]], []), Set),
    random_member(Pick, Set),
    append(List, [Pick], List2)
    <recursive call (haven't figured out this one either yet)>

...

提前致谢!:)

推荐答案

对我来说似乎是一项艰巨的任务.我会用另一种策略来解决这个问题,即在 DCG 中插入 selectors 来区分替代方案.类似的东西

Seems a though task to me. I would tackle it with another strategy, namely inserting selectors in DCG where you want discriminate alternatives. Something like

s --> pronoun(X), verb(X), location.
pronoun(1) --> {this}, [i].
pronoun(2) --> [you].
verb(1) --> [am].
verb(2) --> [are].
location --> {this},[here].
location --> [there].

% here choice just between 2
this :- random(0,2,1).

产生的结果

?- phrase(s,L).
L = [i, am, there] ;
L = [you, are, there].

?- phrase(s,L).
L = [you, are, there].

这篇关于Prolog - DCG - 随机句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆