Prolog:如何生成简单的数学表达式? [英] Prolog: How to generate simple math expressions?

查看:31
本文介绍了Prolog:如何生成简单的数学表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写(不计算)数字列表的所有状态,这意味着:

I need to write (not calculate) all the states of list of number that means :

输入:

Numbers: 1,2,3
Operators: +,-,/,*

输出:

1+2+3
1-2-3
1/2/3
1*2*3
1+2-3
1+2/3
1+2*3
1-2+3
1-2/3
1-2*3
1/2+3
1/2-3
1/2+3
1*2+3
1*2-3
1+2-3

在下降代码中只显示1+2+3

如何将它们开发到所有州?

How can I develop them to all states?

list_sum([Item], Item).
list_sum([Item1,Item2 | Tail], Total) :-
   list_sum([Item1+Item2|Tail], Total).

推荐答案

Carlo Capelli 发布的一个不错的解决方案的变体让我们能够说明一个有用的编程习惯用法,以更好地利用第一参数索引:

A variation of the nice solution posted by Carlo Capelli allows us to illustrate an useful programming idiom to better exploit first-argument indexing:

list_combine([N1| Ns], Os, Nt) :-
    list_combine(Ns, N1, Os, Nt).

list_combine([], N, _, [N]).
list_combine([N2| Ns], N1, Os, [N1, O| Nt]) :-
    member(O, Os),
    list_combine(Ns, N2, Os, Nt).

这个想法是通过将列表的头部和尾部分开来传递我们想要遍历的列表,并将两者作为参数传递,尾部作为第一个参数,如上例所示.

The idea is to pass the list we want to walk by separating the list head from the tail and pass both as argument with the tail as first argument, as exemplified above.

在最初的解决方案中,Prolog 编译器一般不会区分只有一个元素的列表和一个或多个元素的列表.但它会区分空列表(原子)和至少包含一个元素的列表(复合词).另请注意,除了 member/2 上的预期选择点之外,原始版本在对 list_combine/3 谓词的调用上为每个递归调用创建了一个虚假的选择点 谓词调用.

In the original solution, the Prolog compiler will generally not distinguish between a list with just one element and a list with one or more elements. But it will distinguish between an empty list (an atom) and a list with at least one element (a compound term). Note also that the original version creates a spurious choice-point, for each recursive call, on the call to the list_combine/3 predicate in addition to the intended choice-point on the member/2 predicate call.

这篇关于Prolog:如何生成简单的数学表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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