Re: [eclipse-clp-users] product of a list of expressions

From: Marco Gavanelli <marco.gavanelli_at_...17...>
Date: Tue, 15 Sep 2009 11:06:09 +0200
liu.yu.senior.china wrote:
> Dear all,
> 
> I don't find any predicate to calculate the product of a list directly. I use the following code to calculate the product of a list.
> 
> A=[E1,E2,E3,E4],
> dim(Pr,[4]),
> ( for(K,1,4),
> foreach(Ai,A),
> foreachelem(Pi,Pr),
> param(A,Pr)
> do
> ((K==1)->(Pi = Ai);(Pi = Pr[K-1]*Ai))
> ).
> 
> If it is a list of constants and I use 'is/2' in the if else statement, then everything works well. However, if it is a list of expression, then it is not working and I get a huge Pr. It seems to fall into a wrong recursion. I need the product of the list to build a constraint. Any suggestion is appreciated.

Dear Liu, Yu,

if you just have to compute the product of the list as an expression, 
you can define a predicate, like the following:

prod_list([X],X):-!.
prod_list([H|T],P):-
     P = H*P1,
     prod_list(T,P1).

then you can invoke it as follows:

[eclipse 2]: A=[E1,E2,E3,E4], prod_list(A,P).

A = [E1, E2, E3, E4]
E1 = E1
E2 = E2
E3 = E3
E4 = E4
P = E1 * (E2 * (E3 * E4))
Yes (0.00s cpu)

Is this what you need?

Cheers,
Marco

-- 
Marco Gavanelli, Ph.D. in Computer Science
Dept of Engineering
University of Ferrara
Via Saragat 1 - 44122 Ferrara (Italy)
Tel  +39-0532-97-4833
Fax  +39-0532-97-4870
http://www.ing.unife.it/docenti/MarcoGavanelli/
Received on Tue Sep 15 2009 - 09:06:34 CEST

This archive was generated by hypermail 2.3.0 : Wed Sep 25 2024 - 15:13:20 CEST