在Prolog中乘以两个多项式

时间:2014-11-14 18:29:47

标签: prolog

我正在尝试使用Prolog来实现乘以两个多项式的多项式乘法。下面是SML中给出的代码,但我需要在Prolog中使用它。 SML的测试解决方案是poly_mult([1.0,5.0,1.0],[3.0,~10.0,15.0]);并将返回val it = [3.0,5.0,~32.0,65.0,15.0]:真实列表我试图在Prolog中编写代码,但我所拥有的是不正确的。有人可以帮忙吗?谢谢!

IN SML

fun poly_add (M,nil) = M
|  poly_add (nil,N) = N
|  poly_add ((m:real)::mr, n::nr) = (m+n)::poly_add(mr,nr);

fun scalar_mult (nil,m) = nil
|  scalar_mult((m:real)::mr,n) = (m*n)::scalar_mult(mr,n);

fun poly_mult (M,nil) = nil
|  poly_mult (M,n::nr) = poly_add (scalar_mult(M,n), 0.0::poly_mult(M,nr));

我在PROLOG中有什么

poly_add(Constant,[],Constant) :- !.
poly_add([],Constant2,Constant) :- !.
poly_add([Head1 | Head2], [Tail | Tail2], [HeadSum |TailSum]) :-
    HeadSum is Head + Tail,
    poly_add(Head2, Tail2, TailSum).

scal_mult([],Head,[]) :- !.
scal_mult([Head | Head2], [Tail], [HeadMult | TailMult]) :-
    HeadMult is Head * Tail, 
    scal_mult(Head2, Tail, TailMult).

poly_mult(Constant,[],[]) :- !.
poly_mult([Constant], [Tail | Tail2]) :-
    poly_add(scal_mult([Constant, Tail]), [0 | poly_mult] ([Constant, Tail2]).

1 个答案:

答案 0 :(得分:3)

poly_sum(Ms,[],Ms) :- Ms = [_|_].
poly_sum([],Ns,Ns).
poly_sum([M|Ms], [N|Ns], [S|Ss]) :-
   S is M+N,
   poly_sum(Ms, Ns, Ss).

scal_prod([],_Sc,[]).
scal_prod([M|Ms], Sc, [P|Ps]) :-
   P is M*Sc,
   scal_prod(Ms, Sc, Ps).

poly_prod(_,[],[]).
poly_prod(Ms,[N|Ns], Xs2) :-
   poly_prod(Ms,Ns, Xs1),
   scal_prod(Ms, N, Ps),
    poly_sum(Ps, [0.0|Xs1], Xs2).


?- poly_prod([1,2,3,4],[5,6,7],Xs).
Xs = [5.0, 16.0, 34.0, 52, 45, 28] ;
false.